Powershell script that executes another powershell remotely

Question: It's a long story, but I need to create a SQL trigger that executes a script remotely which executes another script remotely (yeah, I know). I'm using PowerShell.
I have started at the end:
Get-Service –Name "service" –ComputerName "Server2" | Set-service –Status Stopped

Get-Service –Name "service" –ComputerName "Server2" | Set-service –Status Running

This works just fine.
Then, the script that will be executed on the trigger:
Invoke-Command –computername "cluster" –command {d:\adminscripts\RestartServer2Service.ps1}

(yes, I use a NLB cluster, and it's reading the script)
But, I get this:

Cannot find any service with service name 'service'.

Any thoughts? Any help will be appreciated.
Thanks
Comment: Right off the top of my head, service names are case sensitive. Is this service actually named "service"? or maybe "Service"? In fact, are you sure it's even named "service"?
Comment: Thanks for trying ehhe. But the name it's ok. The first script (those two lines), which it's restartServer2Service.ps1 works fine. It's only when i use the invoke-command when it does not.
Answer: -command is not a valid parameter for Invoke-Command. Use -FilePath instead to trigger your second script.
Also, ensure you have the proper credentials to execute these scripts.
Answer: This is almost certainly a two-hop issue. If I use Enter-PSSession to connect to ServerA, and then run Get-Service spooler -ComputerName ServerB, I get the exact same "cannot find any service with service name" error.
However, if I run Enter-PSSession ServerA -Authentication CredSSP -Credential (Get-Credential), then the Get-Service command runs fine.
The problem is the second hop -- going from the first remote computer to the second (and third); it's a "bridge too far" for the default authentication protocol used by PS remoting. The solution that I use for this sort of problem is CredSSP.
You can find more details about the problem and how to enable/use CredSSP in this Scripting Guy article.
Comment: I finally ended up doing something to avoid it, because my first hop could call itself and the server/client thing was chaotic. But you were right. Thanks.


Looking for folders containing bare git repositories

Question: If they were working copy of git repositories, we could start simply with the approach of looking for every folder with the name ".git" (find . -type d -name ".git"), as answered here.
But in big storages, how to detect all folders containing bare git repositories?
Comment: https://stackoverflow.com/a/46758507/1290731
Answer: I use the following code:
locate -b \*.git |
    while read path; do
        if [ -f "$path" ]; then
            echo "$path is a gitlink file (perhaps in a submodule)"
        elif [ -d "$path" ]; then
            if [ "`basename \"$path\"`" = .git ]; then
                echo "$path is repository"
            else
                echo "$path is bare repo"
            fi
        fi
    done

Warning 1: To use locate you need your system to be configured to run updatedb regularly (usually nightly from cron)
Warning 2: The code supposes all your bare repositories are named name.git. Mine are.
Comment: This doesn't find bare repositories, but regular ones.
Comment: Works for me. `name/.git` are regular repositories, `name.git` are bare ones.
Comment: That's the problem, they might have lots of different names not following the convention `name.git`
Comment: Conventions are to make things convenient. Those who don't follow them punish themselves unnecessary. Well, then testing for the content like in the linked duplicate is the only solution.


Can a struct of doubles be typecast to an array of doubles in C?

Question: Is this legal in C?
<code>struct Doubles
{
  double a,b,c;
};

void foo(struct Doubles* bar)
{
  double* baz = (double*)bar;
  baz[0]++;
  baz[1]++;
  baz[2]++;
}
</code>
I know that it "works" on MSVC 2010, but I don't know if it's legal, or if different layouts could cause UB.
Comment: @anjruu Use an array if you want to iterate.
Comment: @anjruu You will have to call the members, unless you want to have undefined behavior.
Comment: While it should work OK with most compilers, the question I have for you is how is better than using `bar->a`, `bar->b`, and `bar->c`?
Comment: @RSahu I was hoping to iterate over the members of the struct in a loop, since I need to do the exact thing on each of the members. I can wrap the operation in a function, and then call the function with a pointer to the three members (which is probably what I'll do, given that the answer seems to be "no, this is not totally safe"), but it's a little less convenient.
Comment: @self I am using an existing library. The struct in question represents a point, and the original authors of the code chose to represent a point as a struct with members for the x, y, and z positions.
Answer: This leads to undefined behaviour. The layout of the struct is not totally prescribed by the standard.  For instance, there may be padding.
Comment: I think you explained well.
Comment: Maybe add that for efficiency and to easily fulfill the "compatible type" and "union" requirements, after each member in just about every implementation only the minimal neccessary amount of padding is added to satisfy alignment constraints. Thus, the initial part of a struct starting with two `T` would be compatible to an array of two `T` in practice.
Comment: The layout is implementation-defined (and in practice always defined the way you want it to be); that is not the issue that causes undefined behavior. Rather, undefined behavior here is caused by aliasing. An object of type `struct Doubles` cannot alias an object of type `double[3]`, and the compiler is allowed to assume they don't alias, meaning reads and writes may be reordered freely in ways that break your code.
Comment: @R.. Strict aliasing rules apply to the fundamental type, which is `double` in both cases. So, no, aliasing does not render this code UB.
Comment: Maybe. There're also the array bounds rules. `double* baz = (double*)bar; baz[0]++;` is legal, `baz+1` is legal as a pointer one past the end of the "length-1 array" `bar.a`, `baz[1]++` is UB (dereferencing thast pointer), and `baz[2]` simply invokes illegal pointer arithmetic (UB) before the dereference takes place. So there are lots of issues here.
Comment: @R.. cmaster I agree there is no aliasing problem, but restrictions, R. stated, apply. I wouldn't even allow the baz+1 since there is no array.
Comment: @this: The C standard is explicit that `&x+1` is valid pointer arithmetic for any `x` where `&x` is valid.
Comment: @R.. Do you have the reference, I can only find that stated for an array. 6.5.6,8 Nevermind, 6.5.6,7 clears that up.
Answer: The compiler is allowed to pad/pack the structure however it likes, so strictly speaking, your code isn't 100% safe.  It'll work on most implementations, though.
Comment: @cmaster we are talking about the standard rather than any specific implementation
Comment: Afaik, the memory layout of a `struct` is described quite strictly, i. e. it is guaranteed to use the requested order. And the padding within a structure will be the same as in an array.
Comment: There are limitations: Only after members, any structs with the same initial sequence must have them at the same offsets.
Comment: @cmaster Padding in struct same as an array? Really? Where is that specified in the standard?
Comment: @DavidHeffernan What do you need padding for? You need it, to align the next member to a boundary that allows fast access by the CPU. Nothing more or less. And the CPU does not care whether it is loading from a `struct` or an array, heck, it doesn't even know. Consequently, any sane compiler must use the same padding in both cases.
Comment: @cmaster - yes, the fields have to be in order (among other restrictions).  What's that got to do with padding/packing?
Comment: @CarlNorum If I know the alignment of the values, and I know the order of the values, I can **calculate** the precise offset of each struct member. Yes, the standard does not require the padding in struct and array contexts to be the same, but it even defines the `_Alignof` operator, which yields **the** alignment of a type. It would be extremely curious if a compiler used a larger alignment than that in *any* context. The trick will work in any sane environment, even without the explicit blessing of the standard.


I have an easy Text mining frequency question

Question: I have a very simple question. I am doing a simple frequency analysis where I am looking at two documents and comparing the frequency of the top used words in each document. I want to do a comparison of the two documents in R, but the problem is that one document has 10x more words than the other document. What would be the best way to normalize so that I have two side by side frequency bar graphs that allow me to compare the most frequent terms. I hope that makes sense. No need to provide code. I can figure out the code I just want to know how to present the bar graphs. I was thinking (frequency of word x)/(total number of words in document y).
Thanks!
Comment: practically you are thinking correct !
Answer: I think, as you mention, the frequency of a particular word divided by the total number of words in the document is a very reasonable way to standardize.  For presentation purposes, you may want to multiply that proportion by some fixed number (like 1000) so that it's easier to process (i.e. comparing 4.6 vs. 5.8 instead of 0.00046 vs. 0.00058).
Also, I'd recommend stemming all the words in the document, if you haven't done so already (so words like "run", "running", etc. all are grouped together).  R has some great functionality for this, too.


Wrap node template

Question: Using the blog module, I'm setting a custom template for the individual blog articles (node--blog.tpl.php) which contains a list item and the content inside.
However, I can't figure out where I should be putting my wrapping
 tag? If I put it in either page.tpl.php or region--content.tpl.php then the entire page content is (understandably) wrapped including pagination and other elements. I just need to wrap the list items.
Thanks and please be gentle with a newb :)
EDIT: code
page.tpl.php
...
<?php print render($page['content']); ?>
...

region--content.tpl.php
<?php if ($content): ?>
 <div class="<?php print $classes; ?>">

   <?php print $content; ?>

<?php endif; ?>

node--blog.tpl.php
...

 #content#

....

Comment: This question appears to be off-topic because it is about  code you wrote, for which you want to write better code, or you want to understand why it doesn't work, but you didn't show the code you are using, or the part of the code that is relevant for the question. See [Help Center](http://drupal.stackexchange.com/help/on-topic).
Comment: @Mołot Apologies, I've now added my code. It's core Drupal stuff (using Zen theme). I need to work out where to put `` so it correctly wraps _only_ the list items (being populated by `node--blog.tpl.php`. Thanks
Comment: it should be `node` not the page or region
Comment: @Drupalist I'm using a custom node template (`node--blog.tpl.php`) for each list item but I need to wrap _all_ list items in a `` tag.
Answer: Taking a guess that you're talking about the /blog page, the content is built in blog_page_last(). The nodes themselves will be in $build['nodes'] when that function returns.
As with pretty much everything in Drupal there are a bunch of different ways to alter that content; I think the easiest in this case would be to use hook_page_alter():
function MYMODULE_page_alter(&$page) {
  if (current_path() == 'blog') {
    $page['content']['system_main']['nodes']['#prefix'] = '
';
    $page['content']['system_main']['nodes']['#suffix'] = '
';
  }
}

Comment: Added to template.php and that worked - thanks Clive! Thanks for the link to the docs - I'll have a read through to try and better understand. This seems insanely difficult for the sake of two HTML tags.
Comment: Welcome to Drupal, where a complicated website will take you about an hour to build, and changing a few HTML tags will take about a day and a half ;) If I could suggest some more reading, [Render Arrays](https://drupal.org/node/930760) will help to understand what's going on with the `$build` that gets returned from the blog function, and what the `#prefix` and `#suffix` stuff really means

Wrap node template


Describing the language generated by this grammar

Question: I'm working on this discrete math problem

Describe the language generated by the grammar $G = \{\Sigma, \Delta, S, \Pi \}$, where $\Sigma = \{0, 1 \}$, $\Delta = \{S, X, Y, Z \}$ and $\Pi = \{S \rightarrow 0X | 1Y, X \rightarrow 1Y |1Z, Y \rightarrow 0X | 0Z, Z \rightarrow 0|e \}$.

From my understanding, the language generated should be something like this
$$L = \{ 01110111 \}$$
there is no "loop" where a number goes back to the variable. I'm confused on how to solve this, I need enlightenment. Any help would be great.
Comment: Do some cases, what do you mean by $L=\{01110111\}$. Do you see that in the word you are going to produce you can not have $11$ as substring? Can you have $00$?
Comment: The word can either start with 0 or 1 and must be followed by a 1 which should be followed by a 0 and end with a 0. That's what I think. L is just the longest word that could be accepted @Phicar
Comment: Amm i really do not know what you mean by the longest word accepted, either way what i was asking you is well written in Brian's answer.
Answer: For convenience I repeat the list of productions:
$$\begin{align*}
S&\to 0X\mid 1Y\\
X&\to 1Y\mid 1Z\\
Y&\to 0X\mid 0Z\\
Z&\to 0\mid\epsilon
\end{align*}$$
Notice that every $X$ production adds a $1$ to the string, and every $Y$ production adds a $0$.
Suppose that you begin a derivation by applying $S\to 0X$. Then you can alternately apply $X\to 1Y$ and $Y\to 0X$ as often as you like, but eventually you must apply either $X\to 1Z$ or $Y\to 0Z$, depending on which non-terminal symbol you have at that point. At this point you will have a string that begins with $01$, then alternates $0$s and $1$s, and ends in $Z$. Finally, the $Z$ either disappears or is replaced by $0$.
If you begin by applying $S\to 1Y$, you get a string that begins with $10$, then alternates $1$s and $0$s, and ends in $Z$, and again the $Z$ either disappears or is replaced by $0$.
Thus, at the stage when the string ends in $Z$, the rest of it can be any alternating string of $0$s and $1$s of length at least $2$. Thus, if $L_0$ is the set of strings of alternating $0$s and $1$s of length at least $2$, your language is
$$L=L_0\cup\{x0:x\in L_0\}\;.$$
The shortest strings in $L$ are those produced by the derivations
$$S\Rightarrow 0X\Rightarrow 01Z\Rightarrow 01$$
and
$$S\Rightarrow 1Y\Rightarrow 10Z\Rightarrow 10\;.$$
The shortest non-alternating string is the one produced by the derivation
$$S\Rightarrow 1Y\Rightarrow 10Z\Rightarrow 100\;.$$
The shortest string that has two distinct derivations is $010$, which is derived both by
$$S\Rightarrow 0X\Rightarrow 01Z\Rightarrow 010$$
and by
$$S\Rightarrow 0X\Rightarrow 01Y\Rightarrow 010Z\Rightarrow 010\;.$$
Comment: Ohh, I'm starting to understand it now. Can you explain the difference between `finding the language accepted by an automation` vs `finding a regular expression that defines the same language`?
Comment: @Calypso: There are various ways to describe a language. One is to characterize the words in the language in some way; I did this by identifying them as the words consisting either of at least two alternating zeroes and ones, or such a word followed by a single zero. Another is to give a regular expression that defines the language. Such a regular expression can be considered a description of the language, but it's not the only possible way of describing the language.
Comment: If I try entering a string 0101 into this machine, it ends with 0101z where z can "disappear" Is this valid too?
Comment: @Calypso: Yes, that's fine; that's a string of alternating zeroes and ones, and it's of length $\ge 2$.


What is the workflow for development using EJB3 with Eclipse Galileo and Glassfish v3?

Question: I'm starting to learn EJB3 and I'm a bit lost when it comes to setting up Eclipse. I've got Glassfish v3 prelude downloaded and set up in Eclipse, but when I attempt to publish my EJB project to the server, I'm told that the server is incompatible with the EJB3 facet of the project.
What would the proper steps be to create a new EJB3 project with a JSP/Servlet-based client?
Answer:
Download and install GlassFish v3 (which is out since december), not the prelude version
Install the GlassFish v3 server adapter (right-click the Server view, then New > Server, click on Download additional server adapters and install the GlassFish v3 adapter)
Define a new GlassFish v3 Server
Create a new Enterprise Application Project (from File > New > Other... > Java EE > Enterprise Apllication Project)
Write some code, deploy the project, do some changes and save them (changes get deployed by the plugin on save) and test again. Note that GlassFish v3 preserves session state across redeployments which is awesome for productivity. Check this screencast illustrating these features.
Comment: Apparently I had Glassfish v3 final, but I didn't have the right server adapter in Eclipse, so I've managed to resolve that problem. Thanks. One thing I still don't understand is when, creating an EJB project, it puts the implementation classes for session beans in a separate client project. The book I'm reading (Enterprise JavaBeans 3.0) gives me the impression that they should be stored together.


Recursividade no entity-framework

Question: Estou iniciando no c# e estou tendo umas dificuldades com o Entity-Framework. Tenho o seguinte cenário:
public InstituicaoMap()
{
    // Primary Key
    HasKey(t => t.IdInstituicao);

    // Properties
    Property(t => t.Nome)
    .IsRequired()
    .HasMaxLength(255);
}

public CampanhaMap()
{
    // Primary Key
    this.HasKey(t => t.IdCampanha);

    // Properties
    this.Property(t => t.Texto)
        .IsRequired()
        .HasMaxLength(160);

    this.Property(t => t.DataEdicao)
        .IsFixedLength()
        .HasMaxLength(8)
        .IsRowVersion();

    // Relationships
    this.HasRequired(t => t.Instituicao)
        .WithMany(t => t.Campanhas)
        .HasForeignKey(d => d.IdInstituicao);
}

Estou implementando um CRUD de campanhas, e no momento estou cirando o método "IEnumerable<Campanha> List()" (que lista todas as campanhas cadastradas).
Aparentemente esta funcionando. Para cada campanha retornada na "lista" há um objeto Instituicao dentro. Até ae tudo bem. O problema é que dentro da Instituicao há uma lista de campanhas, que há instituições, que há outra lista de campanhas... e assim vai.
1 - Estou preocupado com o consumo de memória e/ou algum problema que essa recursividade pode ocasionar.
2 - Estou enviando este retorno para a View via JSON (pois a paginação da grid será feita com AJAX/JSON).
return new ContentResult
{
    Content = JsonConvert.SerializeObject(v),
    ContentType = "application/json"
};

Neste retorno, estou recebendo um erro de "looping infinito" do JsonConvert. De fato, pois o objeto campanhas está recursivo.
O que posso fazer?
Comment: Sua dúvida se parece muito com uma pergunta que fiz aqui:http://pt.stackoverflow.com/questions/35109/serializar-lista-de-objetos-para-json-a-circular-reference-was-detected-while-s
Answer: Você pode utilizar a anotação  em sua lista, ou mapear para ignorar, em sua configuração. O primeiro modo é mais simples, bastando fazer isso:
[JsonIgnore]
public virtual Instituicao Instituicao{get;set;}

Da segunda forma, ficaria assim seu CampanhaMap:
public CampanhaMap()
{
    // Primary Key
    this.HasKey(t => t.IdCampanha);

    // Properties
    this.Property(t => t.Texto)
        .IsRequired()
        .HasMaxLength(160);

    this.Property(t => t.DataEdicao)
        .IsFixedLength()
        .HasMaxLength(8)
        .IsRowVersion();

    // Relationships
    this.HasRequired(t => t.Instituicao)
        .WithMany(t => t.Campanhas)
        .HasForeignKey(d => d.IdInstituicao);

    this.Ignore(t => t.Instituicao);

}

Ou, se não que isso, pode desabilitar o Leazy Loading do EF em seu contexto. Algo parecido com isso:
  public YouContext(): base("name=SchoolDBEntities")
    {
        this.Configuration.LazyLoadingEnabled = false;
    }

Comment: ainda existe uma terceira opção, informar ao JSON.NET que o tipo Instituicao e Campanha são referencias, isto pode ser feito ao colocar o atributo `[JsonObject(IsReference = true)]` ou `[DataContract(IsReference = true)]` nas classes, ou utilizando a opção `PreserveReferencesHandling = PreserveReferencesHandling.Objects`, mas no caso dele, por se tratar de um relacionamento `n:n`, isto pode vir a gerar um objeto JSON enorme.
Answer: Uma outra maneira seria vc criar uma classe própria para suas necessidades.
Utilizando o AutoMapper no seu projeto e não utilizar as classes do EF para exibição e retorno.
Tem uma matéria do Eduardo Pires falando sobre SOLID .
Eu aconselho a não utilizar o Lazy Loading pois ele faz consultas separadas na base. A Vandagem é que quando você precisa do dado é só chamar a propriedade que a consulta é feita automaticamente.
Conselho utilizar o Eager Loading onde vc diz para o EF o que vc precisa carregar.
Eu me matei muito com EF6 não é fácil é bem confuso e não tem muitas materias sobre. Aconselho ver esses sites...
http://www.eduardopires.net.br/?s=solid&submit=Pesquisar
http://www.entityframeworktutorial.net/

Recursividade no entity-framework


Node.js mock context.req.headers.referer

Question: I implemented a redirect back to the previously visited page in a project and now have to adjust some tests which are failing because:
Cannot read property 'headers' of undefined
TypeError: Cannot read property 'headers' of undefine

I searched for some time but could not find a good solution or transfer the given answer to my current problem.
Function
export const getServerSideProps: GetServerSideProps<Props> = async (ctx) => {
  ...

  const referer = ctx.req.headers.referer
  let backlink = referer

  if (!referer) {
  ...

    backlink = ...
  }

  return {
    props: {
      ...initialProps.props,
      product,
      backlink,
      ...
  }
}

Test
it('getServerSideProps should return product', async () => {
    mocked(getProductByKey).mockResolvedValueOnce(mockedProducts[0])
    const ctx = {
      query: { productKey: mockedProducts[0].key } as ParsedUrlQuery,
    }

    const result = await getServerSideProps(ctx as GetServerSidePropsContext)
    expect((result as any).props.product).toEqual(mockedProducts[0])
  })

Is there a way to mock the context.req.headers.referer? I would also need this for my own yet-to-be-written test for the redirect back.
Answer: Well, it just seems you have to add properties to your variable ctx.
The error is : Cannot read property 'headers' of undefined.
I can see const referer = ctx.req.headers.referer where ctx.req is undefined.
Two possibilities :

First : it's a logic error, req or req.headers may be undefined sometimes, you should replace your javascript const referer = ctx.req.headers.referer by const referer = ctx && ctx.req && ctx.req.headers && ctx.req.headers.referer to add checks.

Second : it's a test error, req and req.headers will always be defined and your mock is missing it. Just replace in your spec file :

    const ctx = {
      query: { productKey: mockedProducts[0].key } as ParsedUrlQuery,
      req: { headers: {
        referer: 'backlink', // or undefined
      } }
    }

Your error should be fixed and you can edit the referer value (for the moment 'backlink') for other tests if needed.
Comment: Thank you. I implemented both of your suggestions.


Is the following logic true?

Question: Is the following logic true?
$ (\forall x)(\forall y)[(p(x) \wedge S(x,y)) \rightarrow Q(y)] \wedge (\exists x)B(x) \wedge (\forall x)(B(x) \rightarrow p(x))\wedge (\forall x)(\exists y)S(x,y) \longrightarrow (\exists x) Q(x) $ $$ $$ I have tried in the way-
 Let p(x) denote dog and Q(y) denote rabit . S(x,y) denote dog chases rabit . But how to execute , please help me doing this?
Answer: That's not a "logic", it's a sentence. But yes, it's true.
To prove this, you'll mainly need the following principle of logic: $$(\exists x)\varphi \wedge (\forall x)(\varphi \rightarrow \psi) \rightarrow (\exists x) \psi$$
Since I want you to see how this kind of thing is done, I'll do this problem for you, just this once.

Theorem.
Assume:

$(\forall x)(\forall y)[(p(x) \wedge S(x,y)) \rightarrow Q(y)]$
$(\exists x)B(x)$
$(\forall x)(B(x) \rightarrow p(x))$
$(\forall x)(\exists y)S(x,y)$

Then:

$(\exists x) Q(x).$

Proof. By 1., it suffices to show $$(\exists x) (\exists y)(p(x) \wedge S(x,y)).$$
By 3., it suffices to show $$(\exists x) (\exists y)(B(x) \wedge S(x,y)).$$
By 2., it suffices to show $$(\exists x) (\exists y)S(x,y).$$
But in the presence of 2, which guarantees the existence of an element, this follows from 4. This completes the proof.
By the way, if this is homework, you'll have to solve the problem using the specific rules / formal system given. That is, you're probably not allowed to use informal reasoning like I do here.

Is the following logic true?


How to enable the MySQL Slow query log (5.5.15)

Question: Need some help. I've looked around topics here on stack and on mysql's website and none of the configurations ever work for me. I need to enable the MySQL slow query log as well as teh general query log. I want to do it in my config file rather than as a SET statement because I assume that would reset whenever mysql was rebooted?
What am I missing?! Every site says something completely different... I'm using MySQL 5.5.15. This is my current config:
[mysqld]
local-infile=0
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
skip-external-locking

query_cache_limit=8M
query_cache_size=64M
query_cache_type=1

long_query_time=2
slow_query_log_file=/var/log/mysqld.slow.log

max_connections=100
max_user_connections=10
interactive_timeout=20
wait_timeout=20
connect_timeout=6

thread_cache_size=128
key_buffer=16M
key_buffer_size=256M

join_buffer=1M
max_allowed_packet=16M
table_cache=1024
read_buffer_size=2M
sort_buffer_size=2M
max_connect_errors=10

# Try number of CPU's*2 for thread_concurrency
thread_concurrency=4
myisam_sort_buffer_size=64M

[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

Answer: Add slow_query_log=1 to your config file.
Reference
Comment: GENIUS! For some reason when I tried using that before mysql failed to start up again >_<... Do you know how to turn the general query log on as well and specify the file?
Comment: `general_log=1` and `general_log_file=/var/log/mysqld.general.log`
Comment: http://dev.mysql.com/doc/refman/5.5/en/query-log.html
Comment: why 1?  is that milliseconds? why not 5 or 10?
Comment: @Rick - it's just a boolean on or off. Valid values are 0 or 1.


How can I use the AsyncCTP with an TFS APM Method (Query.Begin/EndQuery)?

Question: Would like to try using AsyncCTP with TFS.  Currently have a long running method that calls RunQuery on a TFS Query instance.
Query exposes the APM methods BeginQuery() and EndQuery().  As I understand it, the recommended approach to wrap these using AsyncCTP is something like: (example from docs)
Task<int>.Factory.FromAsync(stream.BeginRead, stream.EndRead, buffer, offset, count, null);

Further, have wrapped it in an extension method as in the docs so my actual method looks like:
public static Task<WorkItemCollection> RunQueryAsync(this Query query)
{
    if (query== null)
        throw new ArgumentNullException("Query");

    return Task<WorkItemCollection>.Factory.FromAsync(query.BeginQuery, query.EndQuery, null);
}

...but this fails to compile.  Getting an "invalid argument" intellisense error that, frankly, I can't really understand because the types and format look correct.  One possible issue might be that the Query APM methods expect an ICanceleableAsyncResult whereas the Task factory is expecting an IAsyncResult -- but looking at the TFS API, ICanceleableAsyncResult is a specialization of IAsyncResult.
Not sure whether i'm doing it wrong or its just not possible.  Would love to be able to do it the AsyncCTP way but may have to go back to the APM pattern -- ugh!
Comment: See my updated answer; I compiled it myself this time, which always helps ;). P.S. Robert Harvey meant no disrespect when he deleted your answer; Stack Overflow is meant to me a Q&A site rather than a forum. You can ask related follow-up questions or make comments (like "it doesn't compile" :) by clicking the "add comment" link under the relevant answer.
Answer: Update: My Nito.AsyncEx library now includes a TeamFoundationClientAsyncFactory type, which can be used instead of rolling your own implementation below.

The TFS API is not strictly following the APM pattern because it does not take a state parameter, and this is preventing the built-in TaskFactory.FromAsync from working.
You'll have to write your own FromAsync equivalent, which can be done using TaskCompletionSource:
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.TeamFoundation.Client;

public static class TfsUtils<TResult>
{
  public static Task<TResult> FromTfsApm(Func<AsyncCallback, ICancelableAsyncResult> beginMethod, Func<ICancelableAsyncResult, TResult> endMethod, CancellationToken token)
  {
    // Represent the asynchronous operation by a manually-controlled task.
    TaskCompletionSource<TResult> tcs = new TaskCompletionSource<TResult>();
    try
    {
      // Begin the TFS asynchronous operation.
      var asyncResult = beginMethod(Callback(endMethod, tcs));

      // If our CancellationToken is signalled, cancel the TFS operation.
      token.Register(asyncResult.Cancel, false);
    }
    catch (Exception ex)
    {
      // If there is any error starting the TFS operation, pass it to the task.
      tcs.TrySetException(ex);
    }

    // Return the manually-controlled task.
    return tcs.Task;
  }

  private static AsyncCallback Callback(Func<ICancelableAsyncResult, TResult> endMethod, TaskCompletionSource<TResult> tcs)
  {
    // This delegate will be invoked when the TFS operation completes.
    return asyncResult =>
    {
      var cancelableAsyncResult = (ICancelableAsyncResult)asyncResult;

      // First check if we were canceled, and cancel our task if we were.
      if (cancelableAsyncResult.IsCanceled)
        tcs.TrySetCanceled();
      else
      {
        try
        {
          // Call the TFS End* method to get the result, and place it in the task.
          tcs.TrySetResult(endMethod(cancelableAsyncResult));
        }
        catch (Exception ex)
        {
          // Place the TFS operation error in the task.
          tcs.TrySetException(ex);
        }
      }
    };
  }
}

You can then use it in extension methods as such:
using System.Threading;
using System.Threading.Tasks;
using Microsoft.TeamFoundation.WorkItemTracking.Client;

public static class TfsExtensions
{
  public static Task<WorkItemCollection> QueryAsync(this Query query, CancellationToken token = new CancellationToken())
  {
    return TfsUtils<WorkItemCollection>.FromTfsApm(query.BeginQuery, query.EndQuery, token);
  }
}

Comment: Stephen, have you tried how those perform with multiple queries / workitemstore activities going on from the same client concurrently? MS mentions that each thread should open its own WorkItemStore instance in multi-threaded scenarios (http://msdn.microsoft.com/en-us/library/bb130347.aspx).
Comment: I do not have a TFS server available (we use SVN or Hg). My code just provides a `Task` wrapper for the existing `ICancelableAsyncResult` APIs, so the threading restrictions would be identical. The MSDN doc you referenced talks about multithreading but not concurrent operations from a single thread.
Comment: Yeah concurrency != multithreading but I meant if the underlying TaskScheduler would indeed use separate thread(s).. then it 'could' be a problem. Need to dig a little bit deeper, benchmark and see what happens.


Is there a way I can align the histogram with the function plot in this graph?

Question: Here's a plot I currently have: (using Python)

The darkorange curve is my function, generated from
plt.plot(x,Yt,color = 'darkorange')

while the histogram comes from
plt.bar(dic.keys(), dic.values(), width=np.abs((rang2-rang1)/N), color='lightcoral')

From this graph we can see they are not quite aligned at the bottom (where both of them should  be 0), I'm wondering is there a way I can make them aligned? Thanks!!
Comment: Just double checking, are they really both supposed to be zero?
Comment: @M Z Ahh, good point, I just realized the curve should be really close to 0, but not strictly equal to. Thanks for the comment:)
Answer: you might need to play around with the offset number below
offset = 0.01

Yt = [y-offset for y in Yt]

plt.plot(x,Yt,color = 'darkorange')

note that if you want to only offset outside the peak range of the function (the spiky part in the middle) you would need a non-constant offset.


Iterate over django m2m through model objects

Question: I have the following ManyToMany relationship in my project:
class Borrador(models.Model):

    nombre = models.CharField(
        max_length=40,
        help_text=_('Nombre para identificar al borrador.')
    )
    productos = models.ManyToManyField(
        Producto,
        through=Articulo,
    )

class Articulo(models.Model):

    producto = models.ForeignKey(
        Producto,
        on_delete=models.SET_NULL,
        null=True
    )
    borrador = models.ForeignKey(
        'Borrador',
        on_delete=models.SET_NULL,
        null=True
    )
    unidades = models.IntegerField(
        default=1
    )

class Producto(models.Model):

    nombre_amistoso = models.CharField(
        max_length=40,
        help_text=_('Nombre corto para identificarlo facilmente.'),
        verbose_name=_('Pseudónimo')
    )
    nombre_fabricante = models.CharField(
        max_length=60,
        help_text=_(
            'Nombre largo que le da el fabricante al producto.'
        ),
        verbose_name=_('Nombre real')
    )
    fabricante = models.ForeignKey(
        'Fabricante',
        on_delete=models.SET_NULL,
        blank=True,
        null=True
    )
    # etc...

As you can see, Articulo model acts as a through intermediary model to retrieve additional info.
I'm trying to iterate over all the Articulo objects associated with a given Borrador object.
At the moment I got it working by doing this:
class Borrador(models.Model):

    # [...]

    def tramitar(self, usuario, solicitar=False):

        articulos = self.productos.through.objects.filter(
            borrador=self
        )
        for articulo in articulos:
            # do stuff

My first attempt was the one below, but it returns all Articulo objects in the database
articulos = self.productos.through.objects.all()
for articulo in articulos:
    # do stuff

Is there a better way to do this? I imagined a simple self.productos.through shoul work, but it isn't the case...
Thanks in advance!
J.
Comment: Couldn't you just do `Borrador.Articulo.all()`?
Comment: Haven't tried, but I think Willem's answer is the right answer anyway. Thanks though!
Answer: You can access the Articulos through the related_name=… parameter [Django-doc] of the ForeignKey:
def tramitar(self, usuario, solicitar=False):
    articulos = self.articulo_set.all()
    # …
Comment: Oh damn, I was so focused on the m2m relationship that I forgot I have a ForeignKey I could use (as I've done multiple times in the same project). Thanks a lot!


CMD: Sleep and hit any key, at the same time?

Question: i have this batch file, which makes constantly a loop. I want the user to be able to terminate it in the batch, not just clicking the X.
This is what i need (somehow):
<code>@echo off
:proc
cls
rem All kind of stuff...
echo Hit any key to terminate...
sleep 1
@pause>nul
</code>
But, of course, sleep and pause can't work at the same time.
How is it possible?
Answer: Remove the pause and change the message to "Hit Ctrl + C to terminate". Presumably the script has a "goto :proc" that you are not showing?
Comment: Yeah, but then, it asks if i'm sure; i don't want that.
Comment: I don't think there is any way of avoiding this message - certainly many of the suggested fixes I've seen like using the "start" command don't work. IMHO, the best solution, if it is possible for you, is to switch to a better command interpreter, such as MSYS bash.
Comment: The problem is, that it is not possible. Isn't it possible, on VBScript, or so?
Answer: More recent editions of Windows has the TIMEOUT command that does just this.
http://technet.microsoft.com/en-us/library/cc754891%28v=ws.10%29.aspx


Do I need a server written in node.js instead of a regular nginx/Apache?

Question: I'd like to use node.js to add basic functionality to a static site:

user authentication and permissions
basic content management (archiving, tags, search)

The examples at nodejs.org show how to start a server, written in JS, but coding an entire http server seems to be an overkill, and definitely doesn't strike me as a very secure solution. Is this really necessary when a standard web server can be used?
What would be the most straightforward way of integrating node.js code behind a server like nginx?
Comment: Not sure if you really need to use NodeJS for your requirement. Can you post some more details about what you are trying to build?
Comment: I'd like to use node for user authentication, setting permissions, archiving content and possibly site-wide search. Ideally, I want to add these features in a modular fashion with the minimum amount of code necessary.
Answer: You can use Apache and Node.js at the same time, on different ports.
Let Apache handle HTTP, and use Node.js on other port to handle your chat, or your real time notification system or whatever you want to do with Node.js
You don't have to use Node.js to serve HTML if you don't want to do so. In fact it's not a good idea, unless you really expect a benefit (because your server will handle tons if IO or if you have such a small/simple web that you don't need a monster like Apache behind).
Comment: My site is mainly static content, but I need to create user classes and control content access. Some blog-like functionality would also be great to improve usability. I don't expect concurrency to be a big issue, and nginx should be perfectly fine for handling the load. Node allows me to use only Javascript so it is much more practical than learning new languages/frameworks. Not much beginner-level information is available though. :(
Answer: If you don't know you need node.js then you probably don't. Node is really meant for real-time applications and highly available and dynamic content being accessed thousands of times per second. For what it sounds like you are making it might be best to use a less efficient but easier solution from the Ruby side. Ruby is super easy to learn and has many great beginner documents. Specifically look into Ruby on Rails and Sinatra.
Another more practical option would be to skip all of this and just use Wordpress. I work for a web development company and 90% of sites end of being wordpress, even the dynamic ones. Wordpress has a huge library of plugins and apis to allow for ultra-customizability. For Wordpress' true power it is best to use a private hosting of it from wordpress.org rather than a shared hosting like wordpress.com.
Comment: I know that node is ideal for asynchronous apps, but it is also a great platform for the future, and is built around a language I can use right now (JS). If the Express framework can be fairly easily implemented, it is a much more practical solution than learning Ruby from scratch... A CMS is completely out of the question due to bloated code and poor scalability.
Comment: If you feel comfortable with node then definitely give it a try. I can give few recommendations as to what libraries to use, but when it comes to security that is entirely dependent on the environment you are in. Check out the following libraries for scalability. [Flatiron](http://flatironjs.org/) will probably be the most familiar to a front-end javascript user and it can be on the server and in the browser!
Comment: Flatiron looks promising, but I guess it will come down to trial and error. Unfortunately, due to the lack of more comprehensive node.js tutorials and books, it is very hard to determine what the learning curve would be as opposed to going with a better documented language and framework like RoR. I am willing to bet on node.js, but I am torn between uncertainty and potentially a lot of wasted time. :(


A guitar or bass with precisely parallel strings (normal guitar strings fan out)

Question: Background
Normal guitars have strings that fan out somewhat towards the bridge. There can be as much as a centimetre's overall difference between the width at the nut and the width at the bridge. I presume this is mostly traditional. As I understand it, it may be because people originally plucked strings with their fingertips and the fingers had to be able to get in between the strings.
Nowadays we use fingernails and picks of all kinds. It seems sensible to remove this restriction. My guess is that it will make picking between strings much faster  if we have strictly parallel strings with a narrower bridge.  Also left-hand fingering of chords would have to change less as the strings wouldn't space out
Question
Apart perhaps from Hawaiian types of guitar, has anyone ever made a parallel-stringed guitar?  Are they available for sale?
Are there any disadvantages?
NOTES

I am an experienced guitarist and have played classical, electric and bass guitars for many years.

Most classical players use their nails these days (I'm one). Also the strings on a classical guitar are more widely space at the nut than say electric. There should be plenty of plucking room.

I intend to suggest this idea to manufacturers. In addition to having a question, I am publishing this idea here. If I have invented the idea of a parallel-stringed guitar, I don't want anyone to patent it (including me). I believe all such innovations should be free for all to experiment with. I do not want any financial remuneration for myself if this turns out to be a good idea. I just want to see if if has been tried or will be tried. This would apply to classical, acoustic, and electric guitars.
Comment: classical?.....
Comment: I play classical but to tell you the truth I am not sure if they are truly parallel but I think it is.
Comment: 9mm spacing at nut and 11mm at bridge, you are correct.  Though I suspect the change is more noticeable for an electric.
Comment: I agree with you
Comment: @ ggcg - It would be interesting to try (and easier) on a classical guitar. I might try it! I've added an edit to my answer.
Comment: There is no reason an electric can't be built that way.
Comment: @ggcg - It's easy enough to check.  Measure and you'll find a big difference.
Comment: @ggcg - 2mm doesn't sound much but for a six-string instrument it adds up to a whole centimeter wider at the bridge than at the nut. That's a lot.
Comment: What makes you think a parallel guitar would be easier to pick faster? I don't mean to challenge your idea or say that it wouldn't be, I'm just trying to understand the argument for this better. When I play I do find that wider string spacing helps with picking (especially at speed), and narrower string spacing helps with fretting, but I've been playing less than a year and don't use fingernails, so perhaps for a more experienced player the tradeoff would be less severe.
Comment: It would be a coincidence if the "ideal" string spacing were exactly the same for both the bridge and nut end of the guitar.  I think it's unlikely that a guitar with precisely parallel strings is built that way solely for playability.
Comment: Chapman Stick is a lot like electric guitar and has parallel strings. It's played by tapping, and this points to the direction that parallel strings might not be by the best choice for picking. I'm quite sure that you can find an obscure 60s electric with parallel strings too if you look hard enough. They tried pretty much everything back then and only a few designs stuck.
Comment: I find wider string spacing makes it much easier for me to hit the target string with my pick when I'm picking alternate individual strings using a plectrum vs finger picking.  I would be more inclined to do the opposite if I changed the spacing ration between the nut and bridge (make the spacing even wider at the bridge).  But that's just me and my personal experience.  Of course I'm not trying to do any super fast picking - so accuracy vs speed is my primary concern.
Answer: I would guess that a luthier has thought this and tried this already, but there are reasons why it wouldn't take off.
First is that we already have a sense of what a guitar should be shaped like, and the associated parts exist. You'd have to custom-build bridges and pickups if the strings get grouped much tighter, and your neck blanks would have to be much wider if instead we widened the nut.
I mean, I already think bridge pin spacing is a bit tight for me...
And I've played 12-strings, and the lack of space between the string pairs made me feel like I couldn't dig in and play dynamically, and I suspect the narrower spacing of parallel strings at standard nut width would be similar.
So this is very much where, if you had one, I'd pick it up and give it a shot, but I'd never custom order one just to see.
Comment: I agree with you Dave, it's not a restriction like Chasly says, I NEED the extra space! For bass even more so. Chasly, try turning a guitar over and placing your right hand by the nut to get a sense of what an instrument like that would feel like. What do you think?
Comment: @John Belzaguy  - Interesting. Instead I just tried plucking as near the nut as possible with the guitar the normal way around. I quite liked it. I think I'm going to have to buy a cheap guitar and try this properly!
Comment: @chasly-supportsMonica I guess you don't have mini baseball bat upright bass player fingers like I do! Are you thinking of using an electric or acoustic? I assume steel string since classical guitars are close to the same width on both ends...
Comment: @chasly-supportsMonica, I think something like an archtop with a trapeze tailpiece and a bridge held down by string tension would be your easiest way forward, even if a low-end one still costs the same as maybe five Tele copies. Good luck!
Comment: @John Belzaguy - I already have most types of guitar. You'd be surprised. If you measure them, you'll find they all fan out considerably. Yes - maybe my fingers are slim enough to make this idea better for me but not for everyone.


Android - is there a way to add an options menu to a listItem

Question: I display some items as a list and I was wondering whether there was a way to add a little dropdown to the right of the screen for each item in the list giving the options of delete/edit.
Is that possible? Rigth now I list things like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >

<include android:id="@+id/header"
         layout="@layout/header"
         android:layout_height="wrap_content"
         android:layout_width="fill_parent"/>

<TextView
    android:id="@+id/no_problems"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Enter the business(es) you want to plan or choose from your existing list."
    />

    <ListView
    android:id="@android:id/list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@+id/label"
        android:textSize="20px" >
    </ListView>

        <Button
    android:id="@+id/add_problem_ok"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/light_best_blue"
    android:text="Plan a New Business"
    android:layout_marginTop ="15dp"
    />
</LinearLayout>

and in the listView I have this:
<?xml version="1.0" encoding="utf-8"?>

    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="10dp"
        android:textSize="16sp" >
    </TextView>

Thanks!
Comment: Wouldn't it be better if you add a context menu to each item,that way , a menu will pop up if the user touches the item for approx 2 seconds, You can add all the  options there.
It will also help in reducing the clutter.
Comment: @amanmadaan yes that migth be nice, but many users wouldnt know to touch the menu for 2 seconds :)
Comment: I think you should give it a try, context menus are a standard these days and all the regular Android users know how they work. You can add some info about them in a help file or a pop up.
Well, i  have presented my case :), Just in case you find that they are right for you, feel free to have a look at
[this](https://github.com/appliedXml/Tarang/blob/master/src/com/bvp/miniproject/ViewSavedMessagesActivity.java)
Answer: If u want to look good then use quickaction-dialog for Option Menu.
here the whole example quickaction-dialog
Comment: thanks, I looked through it but I am not sure I understand how to get the layout to render it in any reasonable way.
Answer: Just add spinner in ur list item layout, then set adapter to tat spinner with in getView() method.
for ex. ur list_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >
 <TextView android:id="@+id/nameTV" android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:padding="10dp"
        android:textSize="16sp" >
    </TextView>

<Spinner android:id="@+id/actionSP" android:layout_width="wrap_content"
        android:layout_height="fill_parent" />
</LinearLayout>

then UR getView()
    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {
        final ViewHolder viewHolder;

        if (view == null) {
            viewHolder = new ViewHolder();

            view = mInflater.inflate(R.layout.list_item,
                    null);
            viewHolder.nameTV = (TextView) view
                    .findViewById(R.id.nameTV);

            viewHolder.actionSP = (Spinner) view
                    .findViewById(R.id.actionSP);

            ArrayAdapter<String> reasonAdapter = new ArrayAdapter<String>(
                    mApplication, android.R.layout.simple_spinner_item,
                    mYourActionsArray);

            reasonAdapter
                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            viewHolder.actionSP.setAdapter(reasonAdapter);

            viewHolder.actionSP
                    .setOnItemSelectedListener(new OnItemSelectedListener() {

                        @Override
                        public void onItemSelected(AdapterView<?> arg0,
                                View arg1, int position, long arg3) {
                        }
                    });
                view.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) view.getTag();
        }

        viewHolder.nameTV.setText("Some Value");

return view;
        }
ViewHolder class
class ViewHolder {
    TextView nameTV;
    Spinner actionSP;
}

Comment: I have not worked with spinners before.  Is it another name for a small drop-down menu item?  Also, I am not sure how to add that drop-down menu item to the right side of the listitem in the layout xml.
Comment: ya spinner s d name of drop-down menu in android, i've update my answer with layout


Struts 2 Action: parameter access

Question: I defined an action like this:
<action name="login" class="tognetti.site.actions.AuthenticationAction">
 <param name="defaultURI">/secure/listaAnnunci.action</param>
    <result>/login.jsp</result>
</action>

I can I access the param from inside the action?  Thanks
Answer: You need to implement the Static Parameters interceptor my good man:
<action name="login" class="tognetti.site.actions.AuthenticationAction">
   <interceptor-ref name="defaultStack"/>
   <interceptor-ref name="staticParams">
      <param name="defaultURI">/secure/listaAnnunci.action</param>
   </interceptor-ref>
   <result>/login.jsp</result>
</action>

Then have your Action implement Parameterizable and your param's will be added to the request params map.
Comment: Great! If I extend the struts-default package I have only to implement the interface. Thanks!

Struts 2 Action: parameter access


Insert value into ObjectNode and return JsonNode in Jackson json library

Question: I am trying to insert a value into a json object in the following format and save it to the database.
<code>  {
        "mainObject": {
            "childObject1": {
                "validator": {
                    "dataType": "TEXT",
                    "regEx": "^[a-zA-Z0-9_]*{3,10}$"
                },
                "input": "Enter data value here"
            },
            "childObject2": {
                "validator": {
                    "dataType": "TEXT",
                    "regEx": "^[a-zA-Z0-9_]*{3,10}$"
                },
                "input": "Enter data value here"
            }
        }
    }
</code>
I need to enter values in the tag where it says input. Something like this:
<code>{
    "mainObject": {
        "childObject1": {
            "validator": {
                "dataType": "TEXT",
                "regEx": "^[a-zA-Z0-9_]*{3,10}$"
            },
            "input": "Input 1"
        },
        "childObject2": {
            "validator": {
                "dataType": "TEXT",
                "regEx": "^[a-zA-Z0-9_]*{3,10}$"
            },
            "input": "Input 2"
        }
    }
}
</code>
I have tried the following code snippet in java.  I am able to insert data into the right node.
<code>String output = "{
    \"mainObject\": {
        \"childObject1\": {
            \"validator\": {
                \"dataType\": \"TEXT\",
                \"regEx\": \"^[a-zA-Z0-9_]*{3,10}$\"
            },
            \"input\": \"Enter data value here\"
        },
        \"childObject2\": {
            \"validator\": {
                \"dataType\": \"TEXT\",
                \"regEx\": \"^[a-zA-Z0-9_]*{3,10}$\"
            },
            \"input\": \"Enter data value here\"
        }
    }
}";
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(output);
ObjectNode newMetadata = (ObjectNode)  rootNode.path("mainObject").path("childObject1");
newMetadata.put("inputValue", "Input 1");
</code>
My problem is how to update and write this back to the mainObject node. At the moment the child nodes input tag is updated with the value, i want to update the mainobject with this and save to database.
Comment: `At the moment the child nodes input tag is updated with the value, i want to update the mainobject with this and save to database.`. What do you mean? You want to update the tree and then write it back to a string?
Comment: @Bogdan, apologies for the question. Maybe it was misleading. Actually what I wanted was something which i had already achieved in the code i had pasted. I was looking at the wrong variable when i was trying to solve the issue and hence thought the right node was not being updated and decided to post here.i dont know how to close this question or mark it answered.
Answer: I have already pasted the code that had the answer. I was looking at the wrong node. I mentioned in my previous comment, I didn't really see an option to close the question. To make it clear, the answer was that as soon as I write to the child nodes, the parent node will have the property as well. That is working code which does not really need a fix, as I said I was looking at the wrong node.


HTML5/CSS3: Como fixar um item de lista não ordenado no fim de todos os itens

Question:

/*   Nav retratil  */
/*=================*/
#something,
nav ul li, inputr,
nav ul input:checked ~li label.abrir {
    display:none;
}

nav ul input:checked ~li,
nav ul li.fixo, li.abrir {
    display: block;
}

nav ul li label {
    color: red;
    font-weight: 900;
    margin-left: 110px;
    cursor: pointer;
}
nav ul li label.abrir {
    align:right;
    cursor: copy;
}

<input type="checkbox" id="something">

    Texto para impressão

#1

#2

#3

#4

#5

#6

#7

#8

    Ver mais ↡

    Ocultar ↟

#9

#10

#11

#12

No trecho   Ocultar ↟   como deixo fixo no final somente na renderização do HTML, utilizando apenas HTML5/CSS3?
Comment: Não entendi direito, vc quer que o "Ocultar" seja sempre o último item é isso? Não ficou muito claro...
Comment: @hugocsl, não. Quero que este item cujo texto é "ocultar", sempre esteja no final da lista. Seja sempre o ultimo elemento.
Answer: Se eu entendi bem tem uma forma de muda a ordem sim somente com CSS, primeiro vc tem que definir a UL como display:flex e direção em column, depois disso vc define uma classe para esse item que deve sempre estar por último, e coloca o atributo CSS oreder:2; nele.

Flex items have a default order value of 0, therefore items with an integer value greater than 0 will be displayed after any items that have not been given an explicit order value.

PORTUGUÊS "Os itens flex têm um valor de order padrão de 0, portanto, os itens com um valor inteiro maior que 0 serão exibidos após qualquer item que não tenha recebido um valor de order explícito."
Todo item dentro de um container flex tem por definição order:0, então ao colocar "manualmente" oreder:2 nele ele sempre será o item com maior valor index, e sempre será o último da lista.
Aqui tem uma documentação da Mozilla mais detalhada de como funciona o order dos flex-items https://developer.mozilla.org/pt-PT/docs/Web/CSS/CSS_Flexible_Box_Layout/ordenacao_dos_itens_flex
Veja o resultado:

/* Nav retratil */
/*=================*/
#something,
nav ul li,
input,
nav ul input:checked ~ li label.abrir {
    display:none;
}

nav ul input:checked ~ li,
nav ul li.fixo,
li.abrir {
    display: block;
}

nav ul li label {
    color: red;
    font-weight: 900;
    margin-left: 110px;
    cursor: pointer;
}
nav ul li label.abrir {
    text-align:right;
    cursor: copy;
}

ul {
    display: flex;
    flex-direction: column;
}
.last {
    order: 2;
}

        <input type="checkbox" id="something">

             Texto para impressão

#1

#2

#3

#4

#5

#6

#7

#8

             Ver mais ↡

             Ocultar ↟

#9

#10

#11

#12

Comment: :D ;)
Valeu!!!!!!
Comment: :D valeu @hugocsl, é exatamente isto que preciso!
Comment: @britodfbr legal jovem! Essa solução pode quebrar seu galho em outras situações, pois ela não altera a ordem dos elementos no HTML, apenas na página quando é renderizada :D boa sorte ai!


Interpreting interactions in a linear model vs quadratic model

Question: I have a crop yield data collected across many locations for 1996-2006 period and a predictor measuring heat availability.
I formulated a model like this;
mdl <- lmer(yield ~ year * heat  + (1|location))

Fixed effects:
              Estimate  Std. Error t value
(Intercept)  -75411.13  24435.28  -3.086
year          38.89     12.20      3.188
heat         -82.56     3471.66   -0.024
year:heat     0.04      1.73       0.022

The results show me there is a positive interaction between heat and year. Is my interpretation correct: "As year increases, the relationship between heat and yield gets steeper. Implying, in 1996, heat decreased yield more than in the year 2006".
Adding to the equation is a quadratic term:
mdl <- lmer(yield ~ year*(heat + I(heat^2)) + (1|location))

 Fixed effects:
                Estimate   Std. Error    t value
(Intercept)    -97816.61  25645.12       -3.81
year            50.07     12.8            3.91
heat            20499.87  8192.63         2.50
I(heat^2)      -632.20    228.56         -2.76
year:heat      -10.22     4.08           -2.50
year:I(heat^2)  0.31      0.11            2.76

I do not understand how to interpret the interaction when both linear and quadratic term are present in the model?
Can anyone explain (perhaps a bit simply) how to interpret this interaction and what does it mean for crop yield, heat and year? It would be great if a rough graphical explanation is shown as well.
Answer: My favorite way to understand an interaction between two continuous predictors (e.g. heat and year) is to plot it with the full range of one predictor on the x-axis and a few different lines representing potentially interesting values of the other predictor --- I usually pick three, representing low, medium, and high levels of the predictor, but you can play around with it depending on your data.
For your specific case, here is some example code. First, since you didn't provide example data, I'll generate some that (very roughly) matches the parameter estimates you provide:
set.seed(24601) # to get exactly the same results as mine, use this set.seed()

# generate data
year <- 1996:2006
heat <- rnorm(n=20, mean=50, sd=15)
location <- letters[1:10]

library(tidyverse)
my_data <- base::expand.grid(year=year, heat=heat, location=location) %>%
  mutate(yield = -75411.13 + 38.89*year - 82.56*heat + 0.04*year*heat + rnorm(nrow(.), sd = 50))

Basically, I just used the fixed effect estimates from your model and added a little normal noise. For your own purposes, of course, you will use your real data and real fitted models.
Model 1 (interaction, linear effects only)
# run model
library(lme4)
mdl <- lmer(yield ~ year * heat  + (1|location), data = my_data)

From your question, it seems like you're interested primarily in the overall fixed effects (not the estimates for individual locations, etc.), so I'll focus on that. If you want to get into visualizing the results for individual locations, I recommend this awesome blog post: https://tjmahr.github.io/plotting-partial-pooling-in-mixed-effects-models/
Here are the fixed effects as I estimated them (they're a bit different from your estimates, so your plot will look a bit different, too, but I think it's close enough to be useful):
> (fe <- summary(mdl)$coefficients[1:4,1])
  (Intercept)          year          heat     year:heat
-74219.711477     38.293178   -117.339456      0.057416

Now let's plot it to take a look at that interaction. I'll choose to put heat on the x-axis and have three representative lines for low, medium, and high values of year, but you could switch and do it the other way if you prefer. I'll use those values (the full range of heat and the three example values of year) to generate predicted yield scores for each combination based on the fixed effects estimates from the model.
# select values for plotting
# full range of heat, and selected low, med and high values for year
plot_df <- expand.grid(heat=heat, year=c(min(year), mean(year), max(year))) %>%
  mutate(yield = fe[1] + fe[2]*year + fe[3]*heat + fe[4]*year*heat)

Now I'll plot those predicted yield values as lines.
plot_interaction <- ggplot(plot_df, aes(y=yield, x = heat, color = as.factor(year))) +
  geom_line(size=2) +
  labs(color = "year") +
  # tweak plot appearance
  scale_color_brewer(palette = "Dark2") +
  theme(legend.position = "top") +
  theme_classic()

plot_interaction

So what do we see here? First of all, the interaction is very small relative to the individual effects of year and heat --- the lines look almost parallel. But you know from the parameter estimates that it is significantly different from zero, so it's there even if it's small. heat has a negative effect when year = 0 (ideally, you will have centered both predictors before estimating the model, so this would be "at the mean of year"), and the positive interaction term indicates that as year increases, the effect of heat gets less negative, so it weakens. What you should look for in the plot is the slope to be a bit shallower for higher years than for low years.
Model 2 (linear and quadratic effects, with interactions)
The second model seems much more complicated, but it's actually just as easy to plot, almost! We'll do the same procedure as before, first getting the fixed effects from the model then generating some plotting data with the full range of heat, selected values of year, and predicted values for yield based on the fixed effect estimates.
First, since I don't have your real data, I'm re-generating another dataset that will (roughly) match the parameter estimates of the second model, so we can get a more or less accurate plot.
my_data <- base::expand.grid(year=year, heat=heat, location=location) %>%
  mutate(yield = -97816.61 + 50.07*year + 20499.87*heat - 632.2*heat*heat - 10.22*year*heat +.31*year*heat*heat + rnorm(nrow(.), sd = 50))

Run the second model:
mdl <- lmer(yield ~ year*(heat + I(heat^2)) + (1|location), data = my_data)

Get the fixed effects:
fe <- summary(mdl)$coefficients[1:6,1]

> round(fe, 3)
   (Intercept)           year           heat      I(heat^2)      year:heat year:I(heat^2)
    -95838.400         49.083      20410.924       -631.207        -10.176          0.310

Close enough. :) Now generate the plotting data.
# full range of heat, and selected low, med and high values for year
plot_df <- expand.grid(heat=heat, year=c(min(year), mean(year), max(year))) %>%
  mutate(yield = fe[1] + fe[2]*year + fe[3]*heat + fe[4]*heat*heat + fe[5]*year*heat + fe[6]*year*heat*heat)

We can use exactly the same plotting code as before, just feed it the updated dataframe:
plot_interaction %+% plot_df

Now we can see that the general effect of heat on yield is negative, with an accelerating effect, so that there's a steeper negative slope at higher levels of heat. Moreover, we can see that the effect of heat depends on year (i.e. the interaction), such that heat drops off more sharply in earlier years than later years.
You should be able to generate plots for your own data using this code. I always find having a visual is extremely helpful when interpreting interactions, especially in models with more than a few coefficients (such as your model 2).
(Note that if the ranges for heat and year are pretty different in your data to what I came up with generating these data, then your plots might look quite different even though the parameter estimates are similar.)
A final note on plotting and interpreting interactions
My guess from your parameter estimates is that you didn't center year and heat before estimating the model, which is why I didn't either. But you probably should. Not only does it ease some model estimation issues like multicollinearity, it makes interpreting your interactions easier since 0 values are more meaningful. For example, the parameter estimates you're getting for heat are the predicted change in yield for each additional unit of heat when year = 0. Unless you've centered year (or you're studying heat and yields in antiquity), you're probably talking about values far outside of the range of your data. Your estimate for the effect of heat will be much more meaningful if you center first.
Comment: Thanks a lot. This is a very detailed responses and makes things quite clear for me.
Answer: Taking derivative respect to heat we get marginal effect that is:
$\frac{\partial yield}{\partial heat}=2500-2*632*heat-10*year+2*0.31*year*heat$
We can rearrange part of interest of ME in the following way:
$year*(-10+0.62*heat)$
It means that greater heat we have then slower it's positive effect decline with each year.
So suppose we have 10 heat. Then each next year the effect will decline by $-10+0.62*10\approx-4$ compare to previous year. However suppose that $heat>\frac{10}{0.62}$ so for example $heat=100$. Then each year heat effect will grow by extra $-10+0.62*100\approx52$.
Also heat may change year by year so its effect will vary. Wheather we expected to have positive or negative time tendency depends on heat value.
Comment: The last line is not really clear: "It means that greater heat we have then slower it's positive effect decline with each year." Would it be possible to break it down even more. Maybe compare an early year in relation to later year to illustrate.
Comment: Thank you. This is really useful.  I am finding a bit difficult to understand where the numbers are coming from. For example: in the equation: `2500−2∗632∗heat−10∗year+2∗0.31∗year∗heat`. Where is 2500 coming from? Why are you multiplying by 2 in 2∗632∗heat?
Comment: 20500 is coefficient for heat in your regression table, I confused it with 2500. Multiplying by 2 is due to derivative of square.


How to prevent a Git object from getting garbage collected?

Question: From what I understood any object gets garbage collected when they have no refs.
What is the best way to prevent collection of objects that we want to persist in the database?
A use case is when in a pull request one makes changes (maybe according to a code review) and previous commits become detached, they are not going to be merged in the repository but they should always be available in order to allow tracing of the changes in the pull request.
Example:

CommitA fixes a bug
Create a pull-request for it
Somebody reviews and suggests a change, linking to a specific line in the code
Change code, amend CommitA and re-commit as CommitA2

Now CommitA2 is what will be in the change history, but the pull-request will still have a link pointing to the old CommitA.
In some years we want to be able to see what the pull-request was about and what its comments were referring to.
How does one prevent the commit from being collected by GC?
Give it a tag is the first solution that comes to my mind.
Comment: I'm pretty sure you want to keep the commit reachable. Give it, or any of it's descendants, a ref. I litter my local repos with non-shared branch names to keep commits around.
Comment: yes, using tags is the best solution because if it's about archiving commits, you don't want to use a branch ref that could be updated by mistake.
Answer: With Git 2.42 (Q3 2023), "git pack-objects"(man) learned to invoke a new hook program that enumerates extra objects to be used as anchoring points to keep otherwise unreachable objects in cruft packs.
In other words, you can record the objects you do not want to see gone after a git gc:
cat refs/pull/137/head > ./precious-objects
pr137=$(cat refs/pull/137/head)
rm -Rf refs/pull/137

git config gc.recentObjectsHook ./precious-objects
git prune --expire=now
git show -p ${pr137}

See commit 4dc16e2, commit 01e9ca4 (07 Jun 2023) by Taylor Blau (ttaylorr).
(Merged by Junio C Hamano -- gitster -- in commit 58ecb2e, 23 Jun 2023)

gc: introduce gc.recentObjectsHook
Helped-by: Jeff King
Signed-off-by: Taylor Blau

This patch introduces a new multi-valued configuration option, gc.recentObjectsHook as a means to mark certain objects as recent (and thus exempt from garbage collection), regardless of their age.
When performing a garbage collection operation on a repository with unreachable objects, Git makes its decision on what to do with those object(s) based on how recent the objects are or not.
Generally speaking, unreachable-but-recent objects stay in the repository, and older objects are discarded.
However, we have no convenient way to keep certain precious, unreachable objects around in the repository, even if they have aged out and would be pruned.
Our options today consist of:

Point references at the reachability tips of any objects you consider precious, which may be undesirable or infeasible if there are many such objects.

Track them via the reflog, which may be undesirable since the reflog's lifetime is limited to that of the reference it's tracking (and callers may want to keep those unreachable objects around for longer).

Extend the grace period, which may keep around other objects that
the caller does want to discard.

Manually modify the mtimes of objects you want to keep.
If those objects are already loose, this is easy enough to do (you can just enumerate and touch -m each one).
But if they are packed, you will either end up modifying the mtimes
of all objects in that pack, or be forced to write out a loose
copy of that object, both of which may be undesirable. Even worse,
if they are in a cruft pack, that requires modifying its *.mtimes
file by hand, since there is no exposed plumbing for this.

Force the caller to construct the pack of objects they want to keep themselves, and then mark the pack as kept by adding a ".keep" file.
This works, but is burdensome for the caller, and having extra packs is awkward as you roll forward your cruft pack.

This patch introduces a new option to the above list via the gc.recentObjectsHook configuration, which allows the caller to specify a program (or set of programs) whose output is treated as a set of objects to treat as recent, regardless of their true age.
The implementation is straightforward.
Git enumerates recent objects via add_unseen_recent_objects_to_traversal(), which enumerates loose and packed objects, and eventually calls add_recent_object() on any objects for which want_recent_object()'s conditions are met.
This patch modifies the recency condition from simply "is the mtime of this object more recent than the cutoff?" to "[...] or, is this object mentioned by at least one gc.recentObjectsHook?".
Depending on whether or not we are generating a cruft pack, this allows the caller to do one of two things:

If generating a cruft pack, the caller is able to retain additional objects via the cruft pack, even if they would have otherwise been pruned due to their age.
If not generating a cruft pack, the caller is likewise able to retain additional objects as loose.

A potential alternative here is to introduce a new mode to alter the contents of the reachable pack instead of the cruft one.
One could imagine a new option to pack-objects, say --extra-reachable-tips that does the same thing as above, adding the visited set of objects along the traversal to the pack.
But this has the unfortunate side-effect of altering the reachability closure of that pack.
If parts of the unreachable object graph mentioned by one or more of the "extra reachable tips" programs is not closed, then the resulting pack won't be either.
This makes it impossible in the general case to write out reachability bitmaps for that pack, since closure is a requirement there.
Instead, keep these unreachable objects in the cruft pack (or set of unreachable, loose objects) instead, to ensure that we can continue to have a pack containing just reachable objects, which is always safe to write a bitmap over.

git config now includes in its man page:

gc.recentObjectsHook
When considering whether or not to remove an object (either when
generating a cruft pack or storing unreachable objects as
loose), use the shell to execute the specified command(s).
Interpret their output as object IDs which Git will consider as
"recent", regardless of their age. By treating their mtimes as
"now", any objects (and their descendants) mentioned in the
output will be kept regardless of their true age.
Output must contain exactly one hex object ID per line, and nothing
else. Objects which cannot be found in the repository are ignored.
Multiple hooks are supported, but all must exit successfully, else the
operation (either generating a cruft pack or unpacking unreachable
objects) will be halted.
Comment: See also [commit 4c237d2](https://github.com/git/git/commit/4c237d2ca2b5aa1f8b79e9ac5e1afa907436fbfe) and its [merged commit 25d5952](https://github.com/git/git/commit/25d59524bbc79b4f4560fca1b9b22c8c36780636).
Answer: Refs don't have to be branches or tags, you can keep local refs to anything you want.
Here's a simple "make me another snapshot ref for pull 137",
next=$((`git rev-list --no-walk --count --glob=refs/snap/pull/137/head-v*`+1))
git update-ref refs/snap/pull/137/head-v$next refs/pull/137/head


Error: Schematic input does not validate against the Schema: {...}, Data path "" must NOT have additional properties(...)

Question: I am creating custom schematics, which I want to use to generate component files in a separate Angular project. For this purpose I am using conditional templates relying on optional parameters declared in my schema.json file. The problem is that when I try to generate the component like this:

ng g subscription-component:component --foo --path="/app" new

I get the following error:
Error: Schematic input does not validate against the Schema: {"foo":true,"path":"/app","name":"new"}
Errors:

Data path "" must NOT have additional properties(foo).

Here is my schema.json file:
{
"$schema": "http://json-schema.org/schema",
"$id": "Schema",
"type": "object",
"properties": {
    "path": {
        "type": "string",
        "format": "path"
    },
    "name": {
        "type": "string",
        "$default": {
            "$source": "argv",
            "index": 0
        }
    },
    "foo": {
        "type": "boolean",
        "default": false
    }
},
"required": [
    "name"
]

 }

The collection.json file in my Angular project:
{
  "$schema": "../node_modules/@angular-devkit/schematics/collection-schema.json",
  "schematics": {
    "component": {
      "aliases": [
        "c"
      ],
      "description": "A blank schematic.",
      "factory": "./subscription-component/index#subscriptionComponent",
      "schema": "./subscription-component/schema.json"
    }
  }
}

and my file:
import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'app-<%= dasherize(name) %>-component',
    templateUrl: './<%= dasherize(name) %>.component.html',
    styleUrls: ['./<%= dasherize(name) %>.component.scss'],
})
export class <%= classify(name) %>Component implements OnInit <% if (foo) {%>, OnDestroy <% }%> {

<% if (foo) {%>
private readonly subscription: Subscription = new Subscription();
<% }%>

constructor() { }

ngOnInit(): void {
}

<% if (foo) {%>
ngOnDestroy(): void {
    this.subscription.unsubscribe();
}
<% }%>
}

Any idea how to fix this?
Comment: https://gist.github.com/koilami/c3574dc873fd2ed1ea7e863cc9d97f36. Thus, the optional parameters of the custom schema.json file were passed to the external schematic. So to fix that I changed my code to this: externalSchematic('@schematics/angular', 'component', {path: _options.path, name: _options.name}).
Comment: Hello, what version of Angular schematics are you using ?
Comment: Oh that's indeed tricky, I see exactly ! That's why we always need to get back to simpler cases to solve these problems out ! I'm glad you reloved that, Schematics are great but not easy to work with ;)
Comment: Hi, I am using version 13.3.2 of @angular-devkit/schematics
Comment: Ok, I tested with this version, on an empty project with the exact same schema and command line and it worked ... you can check this out : https://github.com/aboudard/angular-schematics-test the code is very simple, just to test the command.
Comment: Thank you for taking the time to answer my question. I managed to figure out what was causing the issue. In the factory function in the index.ts file, I am calling an externalSchematic from @schematics/angular to first generate a component and then I am overwriting is content.
Answer: I removed the following code from my angular.json and it worked for me.
"schematics": {
 "@schematics/angular:component": {
   "styleext": "scss"
  }
},


Profile2_path form_alter - Anonymous user form - access denied problem

Question: I have created a custom profile type and given it a unique registration path using profile2 registration path. I am attempting to form alter the custom fields but I cant seem to find a way to view the from as admin in order to view the form array.
Whenever I go to the custom path of offers/register as admin I get an 'access denied'. How can I view this form that is for anonymous users whilst logged in as admin so that I can kpr($form);?
Thanks in advanced.
Answer: I set devel module permissions of 'Access developer information' to anonymous user .
Make sure to disable this module on a production site.


Add class to views row instead of replace system classes

Question: I have this code:
function theme_preprocess_views_view_unformatted(&$vars) {
  $view = $vars['view'];
  $rows = $vars['rows'];

foreach ($vars['view']->result as $id => $row) {

    if (!empty($row->field_field_image)) {
      $vars['classes_array'][$id] = 'has_field';
    }
    else {
      $vars['classes_array'][$id] = 'has_no_field';
    }
  }
}

It works, but replaces all system original classes.
How to just add class?
I tried with $vars['classes_array'][$id][] but I'm getting: Fatal error: [] operator not supported for strings
Answer: Your question is simply a PHP programming question, and not entirely Drupal related. But here goes:
function theme_preprocess_views_view_unformatted(&$vars) {
  $view = $vars['view'];
  $rows = $vars['rows'];

foreach ($vars['view']->result as $id => $row) {

    if (!empty($row->field_field_image)) {
      $old_class_values = $vars['classes_array'][$id];
      $vars['classes_array'][$id] = $old_class_values . ' has_field';
    }
    else {
      $vars['classes_array'][$id] = $old_class_values . ' has_no_field';
    }
  }
}


How to check the network status in react-native app

Question: i am struggling about this point, that if in my mobile i am in poor network connection, Some how i am calling the service, it will take more time to call the service

Is there any possibility to increase the fetch timeout (or)
How to tell the user that u are in poor internet connection.
For checking of internet connection i used the networkInfo, But it help only for connection is there are or not, But it doesn't giving any information about the Speed of the network.

If Possible can any one give me suggestions that, How can i solve this, Any help much appreciated
 I am using the react-native version:0.29.0
Answer: If you just want to know whether the device has an active internet connection, you can use e.g. isConnected from React Native's NetInfo:
import { NetInfo } from "react-native";

NetInfo.isConnected.addEventListener(
  "connectionChange",
  hasInternetConnection =>
    console.debug("hasInternetConnection:", hasInternetConnection)
);

However I'm not sure how to find out how good the connection is.
Comment: NetInfo is now deprecated. Use [react-native-community/react-native-netinfo](https://github.com/react-native-community/react-native-netinfo) instead.
Comment: The original question was about "speed of the network", not the connection itself.
Comment: I see. I edited the answer to specify exactly what it achieves, to clarify that it does not check the connection quality.
Answer: In react native 0.60, importing netinfo directly from react native package has been deprecated. You have to use import NetInfo from "@react-native-community/netinfo"; at the top and its a different package, which needs to be linked to the native code. And after that you can use the NetInfo functions as it was used previously like
NetInfo.isConnected.addEventListener(
  "connectionChange",
  hasInternetConnection =>
    console.debug("hasInternetConnection:", hasInternetConnection)
);

Please check the Github doc for the same React native netinfo
Answer: NetInfo.getConnectionInfo().then((connectionInfo) => {
  console.log('Initial, type: ' + connectionInfo.type + ', effectiveType: '    + connectionInfo.effectiveType);
});
function handleFirstConnectivityChange(connectionInfo) {
  console.log('First change, type: ' + connectionInfo.type + ', effectiveType: ' + connectionInfo.effectiveType);
  NetInfo.removeEventListener(
    'connectionChange',
    handleFirstConnectivityChange
  );
}
NetInfo.addEventListener(
  'connectionChange',
  handleFirstConnectivityChange
);

this is a copy of the code in the react-native documentation, the effective type specifies if the network is 2G, 3G, EDGE or 4G.
Answer: You can use module named as react-native-offline
following are the props given on there website
**
type Props = {
    children: React.Node,
    pingTimeout?: number = 10000,
    pingServerUrl?: string = 'https://www.google.com/',
    shouldPing?: boolean = true,
    pingInterval?: number = 0,
    pingOnlyIfOffline?: boolean = false,
    pingInBackground?: boolean = false,
    httpMethod?: HTTPMethod = 'HEAD',
}

**
Answer: This question has been referenced in many places on stackoverflow. With newer versions of react native you should use the "@react-native-community/netinfo" library. NetInfo used to be part of the react-native, but then it got separated out of the core. If you want to observe network state changes just use the provided addEventListener method.
import NetInfo from "@react-native-community/netinfo";

NetInfo.fetch().then(state => {
    console.log("Connection type", state.type);
    console.log("Is connected?", state.isConnected);
});

const unsubscribe = NetInfo.addEventListener(state => {
    console.log("Connection type", state.type);
    console.log("Is connected?", state.isConnected);
});

// Unsubscribe
unsubscribe();

Answer: Here is the example:
import { NetInfo,Alert } from 'react-native';

const netStatus = await NetInfo.fetch()

if (netStatus === 'none' || netStatus === 'NONE') {
    Alert.alert("Internet not connected.!!!")
    return []
}else{
    Alert.alert("Internet connected.!!! ")
}

Answer: You can use expo-network

Install the package
expo install expo-network

You can make the next method
const [isConnected, setIsConnected] = useState(false);

const getNetworkStatus = async () => {
    const network = await Network.getNetworkStateAsync();
    console.log(network.isConnected); //true or false
    setIsConnected(network.isConnected);
}

useEffect(() => {
     //call the method
     getNetworkStatus();
}, []);
.
.
.
if(isConnected == true){
    console.log("Connected!");
}else{
    console.log("Not connected");
}

You can read de Documentation


Quais são as opções ao Rest?

Question: Atuamente a arquitetura Rest se tornou um padrão para a construção de API's e Webservices. Mas e além do Rest? O que mais existe voltado à construção de API's?
Answer: Pedro, uma API não necessariamente precisa ser Web ou seguir algum padrão de normatização que seja largamente aceito pela comunidade, tais como SOAP ou REST.
Por exemplo, caso você seja um programador .NET, você pode criar um serviço que recebe ou envia arquivos de texto com possição fixa através de uma porta TCP, você terá uma interface de comunicação entre o serviço e qual quer aplicação que o consuma.
Porém, se estivemos falando de WebServices, uma API REST será a forma mais amigavel de disponibilizar o seu serviço.
Caso o seu serviço seja consumido por aplicações das mais diversas origens, o padrão SOAP vai lhe oferecer mais ferramentas para validar o formato do request,
formas de autenticação, segurança utilizada na camada de transporte, ordem de chamada dos métodos os serviço, utilizar uma transação (Banco de Dados) do cliente dentro do seu serviço, além das outras possibilidades.

Quais são as opções ao Rest?


How do I add the "error" class when a form validation fails?

Question: I'm working with Drupal 7.56 and I am using the Webform module to create a custom form.
I used hook_form_alter() in a custom module to add a validation test.
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id=='webform_client_form_1') {
    $form['#validate'][]='mymodule_form_validate';
    return $form;
  }
}

function mymodule_form_validate($form, &$form_state) {
  $aux = $form_state['values']['submitted']['aux'];
  if ($aux != '') {
    if( /* my test */ ) {
      $text = t('Please check your input');
      form_set_error('aux', $text);
    }
  }
}

How can I add the error class when my test fails?
Comment: Welcome to Drupal Answers! I removed the second question since it was a different, unrelated question, that is probably already asked. What do you mean by _adding the "error" class_? You would not need to add a custom validation handler to verify the form field is not empty. Just mark the form field as requested, and the users would be requested to enter a value.
Comment: As side note, `hook_form_alter()` doesn't need to return the form. It is passed as reference.
Comment: Thank you. I have an other test then not empty.. I want to make the border of input red.. for requested input , the module add class error if field is empty.. I want to add the same class if my test is false.
Comment: $form['aux']['#attributes']['class'][] = 'error';  doesn't work!
Comment: $form['submitted']['aux']['#attributes']['class'][] = 'error'; doesn't work also! Any idea please? Thank you
Answer: First try removing your if test and see if you can get the form_set_error to trigger. That way you can make sure your test is correct. You should be able to call form_set_error in a validation function and it will work.
If that isn't the problem then make sure the name of your field is correct.
To answer the question about simply adding a class in form validation you can use the following:
$form_state['complete form']['aux']['#attributes']['class'][] = 'error';
It won't add to the input itself but to the field wrapper and you can style it from there. But I think figuring out why form_set_error isn't behaving how you want is your best bet. That should really be adding the error class.
Comment: Thank you! My test is correct because form_set_error works.. And I checked also my input's name and it's correct too!
Comment: @A.Sana Great, that's a good sign. So when you say `form_set_error` works what do you mean?
Comment: To answer the question about simply adding a class in form validation you can use the following `$form_state['complete form']['aux']['#attributes']['class'][] = 'error';`
Comment: Thanks @sagannotcarl, when I say form_set_error works, I want to say that my test is true.. Now what do you mean by "complete form" ? Is not 'submitted' ? Thank you
Comment: That's right. I tried that and `$form_state['completed form']` worked for me. Note that it's `$form_state` and not `$form` as well.
Comment: @A.Sana Did this work for you?
Comment: thank you for your attention. unfortunately not yet !!
Comment: @A.Sana: Can you describe exactly what happens when you call `form_set_error` in your validate function? Also what happens when you put `$form_state['complete form']['aux']['#attributes']['class'][] = 'error';` in a validate function?


Failed User Login

Question: I have developed a website in Drupal 8 and have deployed it to production. I have created 7-8 other accounts for my content management team and have granted them limited privileges for creating, editing and deleting content.
Of late, I am facing a problem with the user login form, wherein the login works sporadically. Sometimes I am able to log in as the administrator in the first attempt, sometimes I am not. In the latter case, I have to reset my password via email using the reset password option. However, this approach works only temporarily for a single session, which means that as soon as I log out, I am unable to log in. My content managers are also experiencing the same problem.
I have tried the below things but no luck.

Truncating the flood, session and all the cache tables and flood table manually from the database.
Disabling the Recaptcha module in the login form.
Enabling and disabling the HTTP Basic Authentication module.
Disabling server proxy configuration through the settings.php file.
Performing Drupal updates by running the update.php file.

The incorrect username and/or password error in the login has not been handled. When an incorrect username/password is entered the page only refreshes without displaying any custom message.
Please help!
Comment: what is the message you get in the logs ?
Comment: Try my answer to [Cannot login after moving site](https://drupal.stackexchange.com/a/206098/27710)
Comment: @AlexB Thank you for replying. First of all, sorry for responding late as I was extremely busy with personal tasks. While it's not possible to get the log messages as I'm not able to log in as the administrator, I was luckily able to get access to the backend since I had forgotten to log out from the account from another browser, Firefox. There is no log message. :(

Also, the login works when the cache is cleared, but when logged out it again stops working. In order to login again, I have to clear the cache from the backend from Firefox.

Any idea why this might be happening?
Answer: Okay, after much banging my head over the wall for nearly a week, I have found a workarpund solution to this problem by uninstalling Internal Dynamic Page Cache and Internal Page Cache modules.
The problem was that the user login form was getting cached after one successful login. Using the Chrome developer tools the following response header was getting set and sent by Drupal.
X-Drupal-Dynamic-Cache: HIT

To elimnate this I had to uninstall the above two modules.
However this is just a workaround and not a solution, since disabling these two modules will have a tradeoff with the site performance.
Anyone who knows the solution to this problem, please post it here. I shall try them and update this space.
Thank you in advance.

Failed User Login


Como excluir um selectbox com JavaScript um a um

Question: Olá...
Eu tenho um botão que ao clicar no botão "addpergunta" "clona" meu selectbox que está como "Selecione a Pergunta...". A cada clique ele adiciona mais um sempre incrementando id para que fique diferente.
Eu queria fazer o contrário, tipo... ao clicar no botão de id "cancelar" exclua os select's um por um.
Fiz o código abaixo mas ele só deixa hidden um select...

$(document).ready(function () {
    $('#cancelar').click(function () {
        var
        $('#3').html('');  // Excluindo pelo id
        $('#3').hide();
    });
});

JavaScript e HTML que adiciona o selectbox

$(document).ready(function () {
    var x = 1
    $('#addpergunta').click(function () {
        var itemCont = $("#itemCont").val();
        var novoItem = $("#1").clone();

        novoItem.attr("id", itemCont).attr("name", itemCont);

        $("#perguntas").append("
");
        $("#perguntas").append(novoItem);
        itemCont++;
        $("#itemCont").val(itemCont);
    });
});
<input type="hidden" id="itemCont" value="2" />

  <select class="form-control" name="1" id="1">
    <option value="0">Selecione a Pergunta...</option>
  </select>

    <button type="submit" id="incluir" class="btn btn-default" style="height:35px; width:70px;">Incluir</button>
    <button type="button" id="addpergunta" class="btn btn-success" style="height:35px;" title="Adicionar Pergunta">

    </button>
    <button type="button" id="cancelar" class="btn btn-danger" style="height:35px;" title="Cancelar">

    </button>

Answer: Se você é capaz de obter uma lista com cada elemento "select" que você criou, use o método $.fn.remove. Isso irá remover cada elemento (da página) que você tem em um objeto instanciado da classe do jQuery.
$("#perguntas select").remove();

Isso faria o mesmo:
$("#perguntas select").each(
/* novo estilo de função */
() =>
    /* statement único */
    this.parentNode.removeChild(this)
);

Explicação:

iterata cada elemento de um objeto do jQuery;
para cada elemento, uma remoção da página HTML.

Lembrando: você não irá perder referência aos seus elementos quando for removê-los, eles serão removidos apenas da página. Quando um elemento (que é um objeto) não é mais usado, o navegador remove ele automaticamente, isso acontece por causa do gerenciamento de memória (garbage collection).
Então, vamos supor que temos um código onde temos um elemento HTML armazenado em um objeto ou variável:
var el = document.getElementById("id");

Quando for removido da página,
el.parentNode.removeChild(el);

el ainda será um elemento HTML (em navegadores modernos, todos elementos HTML seriam objetos, mas, em navegadores antigos como MS Internet Explorer 6 um elemento HTML seria mais nativo e não poderia obter manipulação de métodos, pois a interface HTMLElement não existiria).
Edit: Esqueci que você quer remover um por um elemento. Isso vai depender da ordem. Se você quer remover o elemento primário você pode usar o método $.fn.first que irá retornar o primeiro elemento do seu objeto do jQuery, e dessa maneira você não irá precisar saber se o elemento existe já que o jQuery executa uma ação para cada elemento que tem no bolso apenas se existe (loop), em seguida você poderá remover os elemento(s) contidos no novo objeto.
$("#perguntas select").first().remove();

Ou, se você quiser remover pela ordem de baixo:
$("#perguntas select").last().remove();

Comment: Boa explicação, mas o que eu quero é remover um "select" cada vez que clicar no botão.. e com esses códigos que passou remove tudo dentro da div.
Comment: @MarcosHenrique Então você precisa capturar o primeiro elemento "select" do objeto do jQuery, checar se ele existe e finalmente remover ele, ou usar o método `$.fn.first` para capturar o primeiro elemento. Isso removerá de primário em primário.
Comment: @MarcosHenrique Editei
Comment: Fiz diferente... criei uma variável e mandei excluir enquanto for maior que 1 (Meu select original)...  Mas agradeço a ajuda, deu uma clareada boa sua explicação.
Answer: Resolvi fazendo isso...

var perguntaId = 0;
$(document).ready(function () {
    $('#addpergunta').click(function () {
        var itemCont = $("#itemCont").val();
        var novoItem = $("#pergunta_1").clone();
        novoItem.attr("id", 'pergunta_' + itemCont);

        perguntaId = itemCont;

        $("#perguntas").append('
');
        $("#perguntas").append(novoItem);
        itemCont++;
        $("#itemCont").val(itemCont);
    });
});

$(document).ready(function () {
    $('#remover').click(function () {
        console.log(perguntaId);
        if (perguntaId > 1) {
            $('br').last().remove();
            $('#pergunta_' + perguntaId).remove();
            perguntaId--;
        }
    });
});