Array prototype method: Can `this` ever be `null`?

Question: I'm looking at the Array.prototype.includes Polyfill, as shown on MDN.
There's a few lines at the top that don't make much sense to me:
// https://tc39.github.io/ecma262/#sec-array.prototype.includes
if (!Array.prototype.includes) {
  Object.defineProperty(Array.prototype, 'includes', {
    value: function(searchElement, fromIndex) {

      // 1. Let O be ? ToObject(this value).
      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

Specifically, the this == null check there.
How can this be null (or even falsy) there? How can that condition ever be true?
As far as I know there isn't a single falsy value that you could invoke .includes on, since even an empty array is truthy.
I'm sure there's a good reason for the null check being there, but what could it be?
The spec linked in the polyfill doesn't explicitly state any null check requirement.

For completeness' sake, here's the complete polyfill:

// https://tc39.github.io/ecma262/#sec-array.prototype.includes
if (!Array.prototype.includes) {
  Object.defineProperty(Array.prototype, 'includes', {
    value: function(searchElement, fromIndex) {

      // 1. Let O be ? ToObject(this value).
      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. If len is 0, return false.
      if (len === 0) {
        return false;
      }

      // 4. Let n be ? ToInteger(fromIndex).
      //    (If fromIndex is undefined, this step produces the value 0.)
      var n = fromIndex | 0;

      // 5. If n ≥ 0, then
      //  a. Let k be n.
      // 6. Else n < 0,
      //  a. Let k be len + n.
      //  b. If k < 0, let k be 0.
      var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

      function sameValueZero(x, y) {
        return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
      }

      // 7. Repeat, while k < len
      while (k < len) {
        // a. Let elementK be the result of ? Get(O, ! ToString(k)).
        // b. If SameValueZero(searchElement, elementK) is true, return true.
        // c. Increase k by 1.
        if (sameValueZero(o[k], searchElement)) {
          return true;
        }
        k++;
      }

      // 8. Return false
      return false;
    }
  });
}
Answer: I think I got it
(function() {
  "use strict";

  if (!Array.prototype.includes2) {
  Object.defineProperty(Array.prototype, 'includes2', {
    value: function(searchElement, fromIndex) {

      // 1. Let O be ? ToObject(this value).
      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. If len is 0, return false.
      if (len === 0) {
        return false;
      }

      // 4. Let n be ? ToInteger(fromIndex).
      //    (If fromIndex is undefined, this step produces the value 0.)
      var n = fromIndex | 0;

      // 5. If n ≥ 0, then
      //  a. Let k be n.
      // 6. Else n < 0,
      //  a. Let k be len + n.
      //  b. If k < 0, let k be 0.
      var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

      function sameValueZero(x, y) {
        return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
      }

      // 7. Repeat, while k < len
      while (k < len) {
        // a. Let elementK be the result of ? Get(O, ! ToString(k)).
        // b. If SameValueZero(searchElement, elementK) is true, return true.
        // c. Increase k by 1.
        if (sameValueZero(o[k], searchElement)) {
          return true;
        }
        k++;
      }

      // 8. Return false
      return false;
    }
  });
}
})();

And then
console.log(Array.prototype.includes2.call(null));
// Uncaught TypeError: "this" is null or not defined

MDN. Strict mode. "Securing" JavaScript: (link)

For a normal function, this is always an object: either the provided
  object if called with an object-valued this; the value, boxed, if
  called with a Boolean, string, or number this; or the global object if
  called with an undefined or null this...
  Thus for a strict mode function, the specified this is not boxed into
  an object, and if unspecified, this will be undefined.
Comment: So, _"strict mode"_ makes that happen? Can you tell me why?
Comment: @Cerbrus I updated the answer with an MDN blockqute.
Comment: Ah, that explains what's happening. Thanks.


Utility to show Windows domain controller reachability?

Question: Is there a utility that presents a tray icon showing domain controller reachability?
I have a laptop PC joined to a corp domain, and I roam sometimes, losing Wifi connectivity to my corp LAN. So I'd like to have a small utility that can notify me when the DC becomes reachable or unreachable, so that I can know in advance whether some Active Directory related operation is available or not.
Answer: Click on the network icon in the system tray. It will show you the names of the networks that you're connected to.


How to assign a value array from json to particular table based on ID

Question: Im working on project which need to assign a value in array from json to particular ID on multiple table in  and .
As you see below the html that contains ID in title and odds. And you can see i was writing dead for this particular html therefore i need to retrieve from backend which the particular title and odds will be change based on the backend given value.
HTML

<input type="hidden" id="k_B1_0" value="BALL">0

9.93
<input name="B1_0" class="ba">

List of array with jSON :

How do we do this ? Kindly advice Thanks you
Answer: Is this what you are looking for?

Comment: Hi Shah , exactly what i want , but can we make it to import for the title name too?
Comment: Almost similarly for title as well. Where exactly do you want title value? And what would that be? B1_0 and such?


Proposition 1.16 in Lee's Introduction to Smooth Manifolds

Question: I'm having some trouble with one of the statements in the proof for Prop. 1.16 in Lee's Introduction to Smooth Manifolds. A countable collection $\mathcal{B}$ of coordinate balls covering a manifold $M$ is given, and Lee asserts:
"For any pair of coordinate balls $B,B' \in \mathcal{B}$, the intersection $B \cap B'$ has at most countably many components, each of which is path-connected."
I'm trying to figure out why this is true. My thoughts for the "countably many components" part is as follows: If there were uncountably many components, then we could find a basis element in each of them, and since the components are disjoint, these basis elements must be distinct. This would then violate second countability. The hole here is that we can only find these basis elements if the components are open in $M$, and I don't know if this is true. Similarly I don't see why the components are path connected.
The fact that $M$, being a manifold, is locally path connected means that the components of $M$ are open and path connected, but I don't know if this is true of the components of $B \cap  B'$. If open subspaces inherit local path connectedness then I think all this would be resolved, but is that the case?
Answer: It all follows from standard general topological facts. I need that the coordinate balls are open, separable and locally (path-)connected:
The coordinate balls are locally connected, and this means (by a standard theorem) that all components of open subsets are open, so this applies to $B \cap B'$ (which is open in $B$). And open subsets of locally path-connected subsets are still locally path-connected (and so this holds of for all components of $B \cap B'$ in particular).
Also, another standard theorem is that a connected, locally path-connected space is path-connected, so all these (open) components of $B \cap B'$ are path-connected as well.
That there are only at most countably many of such components follows from the fact that in a separable space there can be at most countably many disjoint open sets (each has to contain a distinct member from a counatble dense set) (in general, a separable space is ccc) and $B$ (and $B \cap B'$) is certainly separable.
Answer: the question on countability of components of $B \cap B'$ you have solved by observation that the balls form a countable basis, let show why each component is path connected: Let define on points of $B \cap B'$ an equiv relation: $x \sim y$ iff therer exist a finite chain of balls $B_1 , B_2 ,..., B_n$ such that $x \in B_1, y \in B_n, B_i \cap B_{i+1} $ not empty. Obviously by construction you can connect all point from same equivalence class by a path , prove that it's an equivalence relation which separates $B \cap B'$ in disjoint open pieces. But $B \cap B'$ is connected, thus there not exist two or more equivalence classes und thus all points are connectable by a path.
Comment: Is it true though that local path connectedness is a property inherited by (open) subspaces?
Comment: Yes, that's why every point $x \in B \cap B'$ has an open neighborhood such that all points contained there represent the same equivalence class as $x$
Answer: It is trivial that local path-connectedness is inherited by open subspaces.  Suppose $M$ is locally path-connected, $U\subseteq M$ is open, $x\in U$, and $V\subseteq U$ is a neighborhood of $x$ in $U$.  Since $U$ is open in $M$, $V$ is also a neighborhood of $x$ in $M$, so since $M$ is locally path-connected there is a path-connected open neighborhood $W\subset V$ of $x$ in $M$.  Then $W$ is also a path-connected open neighborhood of $x$ in $U$.


check if table column has empty cell

Question: in my case i have 3 columns, every column is dependent on previous one.
user must enter all cells in column 1 so column 2 be editable then he enters column 2 to make column 3 editable.
if he cleared cell then dependent columns should be disabled.
how could i handle it using JavaScript
please find below image :
Comment: it's ADF Application
Comment: i disable and enable it. but it needs me an action like clicking a button,
so i am thinking in handling it using JS. but i don't know how to check if column has an empty cell.
Answer: I am assuming your table cell will be a af:input text .
You don't need explicitly JS to achieve this as you can achieve it in ADF itself. So if you dont have requirement to do it in JS then you can try this below way. With Button we are having action or actionListener , same way we have valueChangeListener with inputText.
Suppose you are having 2 input text (2 cells in table).
 <af:inputText value="#{bindings.ESal.inputValue}"
              label="#{bindings.ESal.hints.label}"
              required="#{bindings.ESal.hints.mandatory}"
              columns="#{bindings.ESal.hints.displayWidth}"
              maximumLength="#{bindings.ESal.hints.precision}"
              shortDesc="#{bindings.ESal.hints.tooltip}" id="it11"
              autoSubmit="true" valueChangeListener="#{bean1.textChange}"
             >
  <f:validator binding="#{bindings.ESal.validator}" />
</af:inputText>

Here make autoSubmit = true for the input text which will be
changed.
Use valueChangeListener event and create a method as textChange as
shown above. It will be triggered whenever there is a change in your input text (on tab change also it will be triggered).
 <af:inputText label="Output label"  id="ol1"
            partialTriggers="it11" binding="#{bean1.lbl}"
          disabled="true"/>

This inputText is dependent on first one. It's disabled by default.
Use PartialTrigger and assign first inputText in it.
Create a binding for this inputText which can be used in managed
bean.
  public void textChange(ValueChangeEvent valueChangeEvent) {
// Add event code here...
if(!(valueChangeEvent.getNewValue()==null ||
   valueChangeEvent.getNewValue().equals(""))) // checking input Text value
{ // if not null
    lbl.setDisabled(false);    //then enable it
    AdfFacesContext adfFacesContext = AdfFacesContext.getCurrentInstance();
    adfFacesContext.addPartialTarget(lbl); // refresh the binding
}
else
{
    lbl.setDisabled(true);    //else disable it.
        AdfFacesContext adfFacesContext = AdfFacesContext.getCurrentInstance();
        adfFacesContext.addPartialTarget(lbl);
}

}
Answer: Enable the java RowImpl for your ViewObject So you can control the returned data in the getters

check if table column has empty cell


Advice on recording a guitar

Question: How can I get the best of my gear for recording guitar (rock/blues) :
My gear:
Guitar
Digitech rp255 multi effect
Guitar amp Marshall solid state
PC
Samsung galaxy smartphone
I used to take the video and audio through my amp using my smartphone.  But the sound isn't great.
Any advice?
Comment: Do you just want to record you playing your guitar solo, or record fuller arrangements (e.g. recording drum tracks, multiple guitar lines, etc) ?
Comment: It's only one track (one guitar)
Comment: I thought of buying a USB microphone to plug to my smartphone. Is that a good idea?
Comment: I answered this same question, but about piano and voice, here:  https://music.stackexchange.com/questions/55101/how-do-i-record-piano-and-voice-music-to-the-best-of-quality/56106#56106
Answer: Three things contribute the most to the quality of a recording, in order:

The skill of the performer(s) being recorded
The skill of the recording engineer(s)
The quality of the equipment being used

Even though the equipment is the least important of the three factors, it can help a lot to have at least a minimum amount of decent equipment to get started.
The built in microphones on smart phones are usually not great, although sometimes one can get decent sound from them. Note that the speakers on smart phones are pretty much terrible, so if you're listening through the phone speakers to what you've recorded, you really have no idea yet how good or bad it is. At a minimum I would get a decent set of headphones to listen on, and ideally you would have a nice stereo system that you can plug the smart phone into.
An external microphone that will work for your smart phone might be a good next step. I wouldn't spend too much on one of these because it won't be useful except with your smart phone (usually) and a phone is pretty limited in terms of recording capabilities. You can either get a microphone that plugs into an analog headset jack or a USB microphone (if your phone can support USB). You might look at the accessories page on the web site of the company that made your phone to see what they recommend and sell.
Once you have some kind of decent mic, there is a huge amount to learn about recording. The most important ingredients to start with are levels and placement.
Pick a place to put your microphone near your amp, leave it there, and make some recordings at different volume levels. You should be able to hear the quality of the sound change with different volume levels.
Once you have a level you think sounds good, keep the level the same and move the microphone around and make different recordings. Again, you should hear some big changes in the sound with different mic placement. Try to find the combination of placement and level that sounds best.
That's just the first week or three of learning to record. There is a lot more, and there are fine gradations of just levels and placement that you can learn about over time as you develop your ear. If and when you have questions about the next steps, we'll be here.
Finally, the more you listen to your recordings, the more you might start to feel like your playing could be better or your guitar rig could be better. Daily practice and lessons are great for the first, and saving your pennies and investing in quality gear is good for the second, but don't rush out to spend a lot of money. It only makes sense to upgrade your gear when you have trained your ear to really hear the difference.

Advice on recording a guitar


Warning: array_flip(): Can only flip STRING and INTEGER values!

Question: I have a custom module that hooks into a commerce extension module.
The function splits a payment for a product and splits it to beneficiaries who helped create the product.
I use user_referance module in a field collection field in the product content type to store the beneficiary users from the system. The drupal system log shows this when running through the function
Warning: array_flip(): Can only flip STRING and INTEGER values! in      EntityAPIController->load() (line 219 of /www/opigno/profiles/opigno_lms/modules/contrib/entity/includes/entity.controller.inc).

Drupals error back trace function showed the error came from this line
  if (!empty($item_id)){
      $split_pay = commerce_funds_object_to_array(entity_load('field_collection_item',
array($item_id)));
  }

The function does run through fine but I'd like to squash any bugs that are appearing, the $item_id array only contains the user_ids of beneficiary users so i don't really understand why a non integer value is being passed
Comment: So just don't wrap  `$item_id` into array. It already is an array. Use it directly, `entity_load('field_collection_item',
$item_id)`
Comment: What exactly is in `$item_id`? It should be integer, or integer-compatible string, if you have something else there, you will have problems. Have you tried to `kpr($item_id)` before calling `entity_load`?
Comment: xdebug is showing this

$item_id = {array}[2]
0 = "12"
1 = "14"
Answer: I had a similar issue, you just have to be sure it is an integer and not a string, also you can use entity_load_single:
if (!empty($item_id)){
$item_id = (int) $item_id;
  $split_pay = commerce_funds_object_to_array(entity_load_single('field_collection_item', $item_id));
}

Comment: Not worked for me
Comment: "entity_load_single" only works for ECK , though.
Answer: If your $item_id is already array as you've mentioned:

$item_id = {array}[2] 0 = "12" 1 = "14"

then you don't need to wrap it again into array.
Use it directly, like:
entity_load('field_collection_item', $item_id);

as per @Mołot suggestion, or just make sure it's in the right expected format.
See: entity_load() API:

$ids: An array of entity IDs, or FALSE to load all entities.


Return ID on INSERT?

Question: I have an INSERT query and I want the DB to return the ID of the row I just inserted.
sqlString = "INSERT INTO MagicBoxes (OwnerID, Key, Name, Permissions, Active, LastUpdated) VALUES (@OwnerID, @BoxKey, @BoxName, 0, 1, @Date) SET @ID = SCOPE_IDENTITY();";
cmd = new SqlCommand(sqlString, con);
cmd.Parameters.AddWithValue("@OwnerID", OwnerID);
cmd.Parameters.AddWithValue("@BoxKey", BoxKey);
cmd.Parameters.AddWithValue("@BoxName", BoxName);
cmd.Parameters.AddWithValue("@Username", Username);
cmd.Parameters.AddWithValue("@Date", DateTime.Now);
cmd.ExecuteNonQuery();

I currently have this, I'm not sure what I need to do next...
Comment: Can't get your question, do you want the seed value of the row just inserted?
Answer: You just need to add @ID to the params collection and then retrieve it like this,
cmd.Parameters.Add("@ID", SqlDbType.Int, 4).Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
//Now just read the value of: cmd.Parameters["@ID"].value

Or, if you prefer this syntax:
SqlParameter param = new SqlParameter("@ID", SqlDbType.Int, 4);
param.Direction = ParameterDirection.Output;
cmd.Parameters.Add(param);

Comment: I can't make this work, after executing the command the parameter is null.  Another answer on here uses ExecuteScalar and seems to produce the right value.
Comment: `Argument 4: cannot convert from 'System.Data.ParameterDirection' to 'string'`
Comment: @Danpe = apologies, corrected above - I always find added output parameters a bit more clunky than it needs to be
Answer: Since SQL Server 2008 there was an OUTPUT clause added to the syntax of TSQL. This allows you to have the data which is affected by the DML query added to the Tabular Data Stream.
Although querying SCOPE_IDENTITY() after a query returns the correct information it forces SQL Server to execute 2 queries where the output clause limits this to one query.
Knowing this, the query being executed can be altered as follows (Assuming [Id] is the name of the identity):
INSERT INTO MagicBoxes (OwnerID, [Key], Name, [Permissions], Active, LastUpdated)
OUTPUT INSERTED.Id
VALUES (@OwnerID, @BoxKey, @BoxName, 0, 1, @Date)

Another issue is not disposing of the SqlCommand. Most of the Sql... objects in ADO.net implement IDisposable and should be disposed of properly.
Bringing everything together I would implement this piece of code as follows:
        using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["db"].ConnectionString))
        using (var cmd = new SqlCommand(@"
                INSERT INTO MagicBoxes (OwnerID, [Key], Name, [Permissions], Active, LastUpdated)
                OUTPUT INSERTED.Id
                VALUES (@OwnerID, @BoxKey, @BoxName, 0, 1, @Date) ", conn))
        {
            cmd.Parameters.AddRange(new[]
                {
                    new SqlParameter("@OwnerID", SqlDbType.Int).Value = OwnerID,
                    new SqlParameter("@BoxKey", SqlDbType.VarChar).Value = BoxKey,
                    new SqlParameter("@BoxName", SqlDbType.VarChar).Value = BoxName,
                    new SqlParameter("@Date", SqlDbType.DateTime).Value = DateTime.Now
                });

            conn.Open();

            var id = (int)cmd.ExecuteScalar();
        }

Comment: This is the best answer.
Answer: You have two options; you could declare an Output parameter called @ID; or - you could change the end to SELECT SCOPE_IDENTITY() and just use:
int id = (int)cmd.ExecuteScalar();

I prefer the formal parameter approach, but ExecuteScalar works well.
Answer: Add this to your parameters
SqlParameter IDParameter = new SqlParameter("@ID",SqlDbType.Int);
IDParameter.Direction = ParameterDirection.Output;
cmd.Parameters.Add(IDParameter);

After executing you can retrieve the id
int id = (int)IDParameter.Value;

Answer: Why don't you call the store procedure. Pass values to the store procedure to get the values inserted and from the SP return the last seed value inserted using SCOPE_IDENTITY(). Hope this help.
Comment: having a stored procedure wouldn't change anything; this is about the argument/result passing, which would be identical
Comment: Yeah you are right, I meant to say that call SP and from SP return the last seed value after insertion.

Return ID on INSERT?


Lef $f$ be a module homomorphism , $f$ is one-one if and only if $\ker f={0}$

Question: I am following Herstein's Topics in Algebra and according to that book a module may be defined on a ring without 1 (https://i.stack.imgur.com/FMeIZ.png).
So if we consider a module $M$ over a ring $R$ without $1$, then will be the statement in the question true ? If yes , then how to prove it ?
Comment: You don't need 1 in your ring in the standard proof.
Answer: Suppose that$Ker f=0$, $f(x)=f(y)$ implies that $f(x-y)=0$ and $x-y\in Ker f$ we deduce that $x-y=0$ and $x=y$.
$f$ is one to one, $f(x)=0=f(0)$ implies $x=0$.
Answer: You prove it exactly as in the case of modules over rings with unity.
In order to show the equivalence between injectivity of a map and triviality of the kernel you only use the fact that
$$
f(x-y)=f(x)-f(y).
$$
Mind that you still have $-y$ and $f(-y)=-f(y)$ even though you don't have $1$ (and so $-1$) because a module is nonetheless an additive group.
Comment: All the answers were nice , but "Mind that you still have −y and f(−y)=−f(y) even though you don't have 1 (and so −1) because a module is nonetheless an additive group." solved my doubt and hence i accept it .(But i upvoted all other answers)
Answer: If $f$ is one-to-one, then for any $x,y$ (elements of module)
$$
f(x)=f(y) \Leftrightarrow x=y
$$
$$
0 = f(x) - f(y) = f(x-y) \Leftrightarrow x = y
$$
So $x-y$ is in the kernel of $f$ if and only if $x-y=0$. Hope you can work out the rest of the proof.


Condicional para mudança de Activity

Question: Ola, estou com um problema, quero criar uma condicional em uma activity, dentro de um botão, para abrir uma outra activity no meu app.

Mas como seria essa condicional?

o meu app tem botões na main activity que leva a outras activityies. Uma dessas activityies é um cadastro, onde o usuário preenche uns dados em alguns Editexts e os salva, eu usei o SharedPreferences para Salvar esses dados.
//Exemplo
SharedPreferences anonacpref = getSharedPreferences("anonac", Context.MODE_PRIVATE);
SharedPreferences.Editor edanonac = anonacpref.edit();
edanonac.putString("anonac_texto", anonactxt.getText().toString());
edanonac.commit();

Enfim, eu gostaria de que quando os dados já estivessem salvos, quando o usuario apertasse o botão na main activity ele fosse levado para outra activity ao em vez de ser levado para a activity de preenchimento do banco de dados.

como faço pra testar se já tem algo salvo na                     SharedPreferences?
Answer: SharedPreferences anonacpref = getSharedPreferences("anonac", Context.MODE_PRIVATE);
String texto = anonacpref.getString("anonac_texto", null);
if (texto != null) {
    System.out.println("Já preenchido com: " + texto);
} else {
    System.out.println("Texto não encontrado em shared preferences.");
}

O segundo parâmetro do getString() é o valor default, a ser retornado caso não encontre o valor de "anonac_texto" no arquivo de shared preferences. No caso estou usando null.
Comment: Obrigado pela ajuda Piovezan. Eu entendi que no código que você postou, você está salvando o valor salvo no shared preferences em uma variável do tipo string, mas se os dados foram salvos, usando a shared preferences, em uma Activity e depois armazenados na variável nessa mesma activity, eu posso usar essa variável como parâmetro em outra activity? Se sim, como eu faço isso?
Comment: Não. Você busca de shared preferences em uma Activity, e em outra Activity busca de shared preferences de novo. Se quer evitar duplicidade de código, crie uma classe que leia campos específicos de shared preferences.
Comment: Poderia me dar um exemplo de código?
Comment: Veja a classe SharedPreference (sem s no final) [desse tutorial](http://androidopentutorials.com/android-sharedpreferences-tutorial-and-example/) e ela sendo usada nas classes MainActivity e SecondActivity.

Condicional para mudança de Activity


Firebase unexpectedly requires a newer version of Google Play Services

Question: I was using Firebase with the following versions in my Android app project:
compile 'com.google.firebase:firebase-core:11.2.0'
compile 'com.google.firebase:firebase-database:11.2.0'
compile 'com.google.firebase:firebase-auth:11.2.0'
compile 'com.google.firebase:firebase-messaging:11.2.0'
compile 'com.google.android.gms:play-services-ads:11.2.0'
compile 'com.google.android.gms:play-services-location:11.2.0'

//...
apply plugin: 'com.google.gms.google-services'

Then I updated my app to use the last version of Firebase, so replaced all 11.2.0 with 11.8.0 in all dependencies. It compiles fine, but now, when calling FirebaseAuth.getInstance().signInAnonymously(), the callback never returns and the sign in is not performed. This error is silent, but I had a look at the console, and I found:
Google Play services out of date.  Requires 11910000 but found 11518438

Apparently my phone has version 11.5.18 of Google Play Services installed (thus the number 11518438). I know, updating Google Play Services should fix it, BUT, how is this supposed to work in a production environment? I'm sure there will a lot of users whose Google Play Services app will also be outdated. Does this mean that all of those users will suddenly have an app that doesn't work when they update it?
I know I can use makeGooglePlayServicesAvailable() but it just doesn't feel right (for example the user might not have Internet or space for an update). Will the user be forced to update every time a new version is needed? And, where is it documented that Firebase version X requires Google Play Services version X? I cannot see anything on Firebase release notes.
Answer: The release of new Play Services and Firebase SDKs only occurs after the Play Services APK has been made available to 100% of supported Android devices.  The expectation is that these devices will self-update their Play APK.  If that hasn't happened on a user's device for whatever reason, the user is typically prompted to update their Play Services before running the app that makes use of it.
A vast majority of the time, the update happens transparently and the user never knows (or needs to know) what happened.  If you're withholding Play Services from your device, that is not a typical situation.
Comment: Why do you say it's not a typical situation? Not having automatic updates is a totally normal option you can choose on Google Play. From my experience and user base, a big percentage of users don't update their OS or apps, specially in developing countries like India, where the Internet is not very good. You only have to look at the huge Android API level segmentation to get an idea.
Comment: Play auto-updates itself and the end user cannot control that using the same mechanism as other apps.
Comment: Oh I see, didn't know that. At least it makes the issue less probable. Still Google Play Services was not auto-updated on my device, and I don't know the reason for that (I am logged in to Google Play, I have enough space in the device, and it has good internet connectivity).
Comment: Something may have gone wrong.  Maybe your device doesn't have enough free space.  You can try to force an update: https://play.google.com/store/apps/details?id=com.google.android.gms
Answer: Piggybacking on what Doug said you should be checking in your app for the correct version of google play services you compiled against
GoogleApiAvailability mApiAvail = GoogleApiAvailability.getInstance();
int status = mApiAvail.isGooglePlayServicesAvailable(this);
if(status != ConnectionResult.SUCCESS){
    mApiAvail.showErrorDialogFragment(this,status,1234);
}

This would show a dialog to the user saying they need to update/enable google play services.
This fixes the case where the device was not updated to the version you need.

...but it just doesn't feel right (for example the user might not have
  Internet or space for an update). Will the user be forced to update
  every time a new version is needed?

When you update your google play services for your app you have then declared that your app cannot function without at least that version of Google Play Services so you are forcing the user to update to be able to use your app. It is then up to the user to decide if they want to do that or not.

where is it documented that Firebase version X requires Google Play
  Services version X? I cannot see anything on Firebase release notes.

Firebase is part of google play services which is why they need to be the same version


Gradient of a function defined on a Lie group by pulling back to identity

Question: I am reading this paper dealing with optimization on Lie groups and in the introduction (second full paragraph of the second page) the authors write:
''However, a specialization in Lie group will still be helpful, because the additional group structure (joined efforts with NAG) improves the optimization; for instance, a well known reduction is to, under symmetry, pull the velocity at any location on the Lie group back the tangent space at the identity (known as the Lie algebra).''
With my limited background of differential geometry I am trying to understand this statement formally and how I can use it to design optimization algorithms (e.g. Riemannian gradient descent) when my cost function is defined on a Lie group.
Let me explain my attempt to understand how this works. Let $\mathcal{G}$ be a Lie group and $f : \mathcal{G} \to \mathbb{R}$ a smooth function. The Lie group $\mathcal{G}$ can be made into a Riemannian manifold by defining $\forall g \in \mathcal{G}$ the Riemannian metric
$$
\langle X, Y \rangle_g = {\rm trace}(XY^t), \qquad \forall X,Y \in T_{g} \mathcal{G}.
$$
I would like to obtain the Riemannian gradient of $f$ at $g \in \mathcal{G}$ with respect to the metric defined above. To do so I consider the pullback of $f$ by $L_g$ (left translation by $g$)
$$
L_g^{\ast}f = f \circ L_g,
$$
and compute the gradient $V = {\rm grad} (L_g^{\ast} f)(e)$ at the identity $e \in \mathcal{G}$ which is an element of the tangent space $T_e \mathcal{G}$.
If I multiply $V$ on the left by $g$ then I get $g V$ which is an element of the tangent space $T_g \mathcal{G}$ and I would like to think that $gV$ is the gradient of $f$ at $g$? Why would such a claim be true, something to do with left-invariant vector fields?
Clearly I do not fully understand what is going on here and I am lacking proficiency in the language of differential geometry. Any comments which will help clarify my understanding would be greatly appreciated.
Comment: The problem is that it does not suffice to compute the gradient of $f$ merely at the identity and just push it around. The gradient of $f$ is not left-invariant because $f$ is not a homomorphism.
Answer: I think you are totally correct and it is just a definition of differential for a function that confuses you. Please take a look at http://staff.ustc.edu.cn/~wangzuoq/Courses/18F-Manifolds/Notes/Lec05.pdf Definition 2.5. Here they try to use $dL_g$, the differential of left multiplication, to move the tangent vector around.


Unable to get the desired result using BackDropFilter in Flutter

Question: For a couple of times now I've played around BackDropFilter() in Flutter and it looks like I can't seem to warp my head around how it works or maybe I feel I don't have the power I should have with it, lol. Can you put me in the right direction, please?
I want the backdrop only on the Container but instead, it goes beyond the Container to the cover image.
This image contains what I want

While this is what I get

Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          ClipRRect(
            borderRadius: const BorderRadius.only(
              bottomLeft: Radius.circular(50),
              bottomRight: Radius.circular(50),
            ),
            child: Stack(
              children: [
                // Featured Image
                Hero(
                  tag: product.id,
                  child: Container(
                    height: size.height * 0.6,
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        fit: BoxFit.cover,
                        image: CachedNetworkImageProvider(
                          product.featuredImage!,
                        ),
                      ),
                    ),
                  ),
                ),

                // App Bar
                SafeArea(
                  child: Padding(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 20,
                      vertical: 10,
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        // Back Button
                        MenuButton(
                          onTap: () => Navigator.pop(context),
                          padding: const EdgeInsets.all(12),
                          icon: Icon(
                            Platform.isAndroid
                                ? Ionicons.arrow_back
                                : CupertinoIcons.back,
                            color: Constants.iconColor,
                          ),
                        ),

                        // Add to fav button
                        MenuButton(
                          onTap: () {},
                          padding: const EdgeInsets.all(12),
                          icon: const Icon(
                            Ionicons.heart,
                            color: Constants.iconColor,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),

                Positioned(
                  bottom: 0,
                  child: Container(
                    color: const Color.fromARGB(189, 49, 49, 49),
                    height: size.height * 0.2,
                    width: size.width,
                    child: BackdropFilter(
                      filter: ImageFilter.blur(sigmaX: 3.5, sigmaY: 3.5),
                      child: Row(
                        children: [
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                product.title!,
                                style: Theme.of(context).textTheme.headline4,
                              ),
                              Text(
                                product.subtitle!,
                                style: Theme.of(context)
                                    .textTheme
                                    .headline5!
                                    .copyWith(
                                        fontSize: 16, color: Colors.white54),
                              ),

                              // Rate
                              Expanded(
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    const Icon(
                                      Ionicons.star,
                                      color: Constants.mainAppColor,
                                    ),
                                    const SizedBox(width: 12),
                                    Text(
                                      product.rate.toString(),
                                      style:
                                          Theme.of(context).textTheme.headline5,
                                    ),
                                    const SizedBox(width: 12),
                                    Text(
                                      '(${product.rate})',
                                      style: Theme.of(context)
                                          .textTheme
                                          .headline6!
                                          .copyWith(
                                              color: Colors.white54,
                                              fontSize: 15),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),

          SizedBox(height: size.height * 0.02),

          //
          Expanded(
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    "Description",
                    style: Theme.of(context).textTheme.headline6!.copyWith(
                        fontSize: 18, color: Colors.white.withOpacity(0.7)),
                  ),
                  SizedBox(height: size.height * 0.015),
                  RichText(
                    text: TextSpan(
                      children: [
                        TextSpan(text: '${product.description!}... '),
                        const TextSpan(
                          text: 'Read More',
                          style: TextStyle(color: Constants.mainAppColor),
                        ),
                      ],
                      style: Theme.of(context)
                          .textTheme
                          .headline6!
                          .copyWith(fontSize: 16),
                    ),
                    maxLines: 2,
                  ),
                ],
              ),
            ),
          )
        ],
      ),
Answer: Try this
import 'dart:io';
import 'dart:math';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class HomePage extends StatelessWidget {
  HomePage({Key? key}) : super(key: key);

  Product product = Product(
      id: "001",
      featuredImage:
          'https://upload.wikimedia.org/wikipedia/commons/thumb/c/c8/Cappuccino_at_Sightglass_Coffee.jpg/1280px-Cappuccino_at_Sightglass_Coffee.jpg',
      title: "Cappuccino",
      subtitle: "With Oat Milk",
      rate: "4.5");

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: Colors.black,
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          ClipRRect(
            borderRadius: const BorderRadius.only(
              bottomLeft: Radius.circular(50),
              bottomRight: Radius.circular(50),
            ),
            child: Stack(
              children: [
                // Featured Image
                Hero(
                  tag: product.id!,
                  child: Container(
                    height: size.height * 0.6,
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        fit: BoxFit.cover,
                        image: CachedNetworkImageProvider(
                          product.featuredImage!,
                        ),
                      ),
                    ),
                  ),
                ),

                // App Bar
                SafeArea(
                  child: Padding(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 20,
                      vertical: 10,
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        // Back Button
                        MenuButton(
                          onTap: () => Navigator.pop(context),
                          padding: const EdgeInsets.all(12),
                          icon: Icon(
                            Platform.isAndroid
                                ? Icons.arrow_back
                                : CupertinoIcons.back,
                            color: Colors.white,
                          ),
                        ),

                        // Add to fav button
                        MenuButton(
                          onTap: () {},
                          padding: const EdgeInsets.all(12),
                          icon: const Icon(
                            Icons.favorite,
                            color: Colors.white,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),

                Positioned(
                  //top: size.height * 0.30,
                  bottom: 0,
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(50),
                    child: Container(
                      color: const Color.fromARGB(189, 49, 49, 49),
                      // color: Colors.green,
                      //height: size.height * 0.75,
                      padding: const EdgeInsets.all(20),
                      width: size.width,
                      child: Row(
                        children: [
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              const SizedBox(
                                height: 20,
                              ),
                              Text(
                                product.title!,
                                style: Theme.of(context)
                                    .textTheme
                                    .headline4!
                                    .copyWith(
                                        fontSize: 24, color: Colors.white),
                              ),
                              Text(
                                product.subtitle!,
                                style: Theme.of(context)
                                    .textTheme
                                    .headline5!
                                    .copyWith(
                                        fontSize: 16, color: Colors.white54),
                              ),
                              const SizedBox(
                                height: 20,
                              ),

                              // Rate
                              Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  const Icon(
                                    Icons.star,
                                    color: Colors.orangeAccent,
                                  ),
                                  const SizedBox(width: 12),
                                  Text(
                                    product.rate.toString(),
                                    style: Theme.of(context)
                                        .textTheme
                                        .headline5!
                                        .copyWith(
                                            color: Colors.white, fontSize: 15),
                                  ),
                                  const SizedBox(width: 12),
                                  Text(
                                    '(6.986)',
                                    style: Theme.of(context)
                                        .textTheme
                                        .headline6!
                                        .copyWith(
                                            color: Colors.white54,
                                            fontSize: 15),
                                  ),
                                ],
                              ),
                              const SizedBox(
                                height: 20,
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),

          SizedBox(height: size.height * 0.02),

          //
          Expanded(
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    "Description",
                    style: Theme.of(context).textTheme.headline6!.copyWith(
                        fontSize: 18, color: Colors.white.withOpacity(0.7)),
                  ),
                  SizedBox(height: size.height * 0.015),
                  RichText(
                    text: TextSpan(
                      children: [
                        TextSpan(
                          text: '${product.description!}... ',
                          style: const TextStyle(color: Colors.white),
                        ),
                        const TextSpan(
                          text: 'Read More',
                          style: TextStyle(color: Colors.orangeAccent),
                        ),
                      ],
                      style: Theme.of(context)
                          .textTheme
                          .headline6!
                          .copyWith(fontSize: 16),
                    ),
                    maxLines: 2,
                  ),
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}

class Product {
  String? id;
  String? featuredImage;
  String? subtitle;
  String? title;
  String? rate;
  String? description;

  Product(
      {this.id,
      this.featuredImage,
      this.title,
      this.rate,
      this.subtitle,
      this.description =
          "A Cappuccino is a coffee-based drink made primarily from espresso and "});
}

class MenuButton extends StatelessWidget {
  const MenuButton(
      {Key? key,
      required void Function() onTap,
      required EdgeInsets padding,
      required Icon icon})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(20.0),
      decoration: BoxDecoration(
          color: Colors.black, borderRadius: BorderRadius.circular(20.0)),
    );
  }
}

It looks like this
Comment: I ended up adding some shadows to the container to get something similar. **Note** that I made the blurStyles BlurStyle.inner


Characterstic of log

Question:
I could not understand how they got $T_{100}$ as 300 .
Can anybody please explain me .
Comment: The string "$100$" contains three digits. The number $T_{100}$ is the string "$100$" repeated a hundred times,  so the total number of digits is (the number of digits in one string) times (the number of times the string is repeated), this gives $3 * 100 = 300$. Did you not understand how they got the number of digits, or why they are taking the number of digits?
Comment: Hi. Please make questions stand on their own with text and typeset mathematics and not images of text or formula. If you already have over 1000 reputation you should know this. Voting to close.
Answer: Since the string consisting of $100$ times "$100$" has $300$ (decimal) digits, we have $$10^{299}< \underbrace{100100\cdots 100100}_{100\ times\ "100"}<10^{300}$$ hence the integer part of the decimal logarithm is $299$

Characterstic of log


mySQL How to SELECT MAX(date) from duplicate values without group

Question: I have this table:
id   obj_nr   el_nr   location   date
0    1234     1        a3         2020-01-01
1    1234     2        a2         2020-01-02
2    1234     3        a4         2020-01-03
3    1234     1        a9         2020-01-04

No i want to concat obj_nr and element_nr to find duplicates.
When i find a duplicate i wan't only to select the one with the latest date.
The result should be:
id   obj_nr   el_nr   location   date
1    1234     2        a2         2020-01-02
2    1234     3        a4         2020-01-03
3    1234     1        a9         2020-01-04

How should my query look like?
This is what i've tried:
SELECT MAX(id) id, obj_nr, el_nr, location, max(date_scanned)
FROM  element_location WHERE obj_nr = :obj_nr
GROUP BY obj_nr, el_nr, location

But this will not give me the latest duplicate.
Answer: You can filter with a subquery:
select *
from element_location el
where date = (
    select max(el1.date)
    from element_location el1
    where el1.obj_nr = el.obj_nr and el1.element_nr = el.element_nr
)

This would take advantage of an index on (obj_nr, element_nr, date desc).
Or, in MySQL 8.0, you can use window functions:
select *
from (
    select el.*,
        rank() over(partition by obj_nr, element_nr order by date desc) rn
    from element_location el
) el
where rn = 1

Comment: Perfect. It works :)
Answer: You can use the NOT EXISTS as follows:
select *
from element_location e
where not exists (
    select 1
    from element_location ee
    where ee.obj_nr = e.obj_nr and ee.element_nr = e.element_nr
      and ee.date > e.date
)


Multiple Resolution Support in Cocos2d-x v2.2.5 in Portrait mode

Question: I am working on a game in cocos2d-x which is in portrait mode.
Now, for a long time now, I've been working on how to properly achieve multi resolution in cocos2d-x but failed. I followed this great tutorial on forum, but it wasn't enough, I also searched a lot but couldn't find a solution.
I also tried with different-different policies which are available with cocos-x.
I went through all the following links & tutorials
Using these links I could achieve for all ios resolutions but not for all android screens.

http://becomingindiedev.blogspot.in/2014/05/multi-resolution-support-in-ios-with.html
http://discuss.cocos2d-x.org/t/porting-ios-game-to-android-multi-resolution-suppor/5260/5
https://www.youtube.com/watch?v=CH9Ct4R0nBM
https://github.com/SonarSystems/Cocos2d-x-v3-C---Tutorial-4---Multi-Resolution-Support

I even tried with newer version of cocos2d-x, but they also not providing anything which can support both ios and android screens.
Comment: Have you tried using CCDevice::getDPI(). It gives pixels per inch. If you need your objects to be displayed in the same physical dimension in all devices you can use this value to resize, positioning etc..
Comment: hmm okey , i will try with it.
Answer: It's working for me this way for Portrait mode:
Below the header :
typedef struct tagResource
{

     cocos2d::CCSize size;
     char directory[100];

} Resource;

static Resource smallResource   =  { cocos2d::CCSizeMake(640, 960),"iPhone" };

static Resource mediumResource  =  { cocos2d::CCSizeMake(768, 1024),"iPad"};

static Resource largeResource   =  { cocos2d::CCSizeMake(1536, 2048),"iPadhd" };

static cocos2d::CCSize designResolutionSize = cocos2d::CCSizeMake(768, 1024);

in applicationDidFinishLaunching() method :
 // initialize director

    CCDirector* pDirector = CCDirector::sharedDirector();
    CCEGLView* pEGLView = CCEGLView::sharedOpenGLView();

    pDirector->setOpenGLView(pEGLView);

    CCSize frameSize = pEGLView->getFrameSize();

    std::vector<std::string> searchPaths;

    // Set the design resolution

    pEGLView->setDesignResolutionSize(designResolutionSize.width, designResolutionSize.height, kResolutionExactFit);

    if (frameSize.height <= smallResource.size.height)
    {
        searchPaths.push_back(mediumResource.directory);
        CCFileUtils::sharedFileUtils()->setSearchPaths(searchPaths);

    pDirector->setContentScaleFactor(mediumResource.size.height/designResolutionSize.height);

    }
    else if (frameSize.height <= mediumResource.size.height)
    {
        searchPaths.push_back(mediumResource.directory);
        CCFileUtils::sharedFileUtils()->setSearchPaths(searchPaths);
    pDirector->setContentScaleFactor(mediumResource.size.height/designResolutionSize.height);
    }
    else
    {
        searchPaths.push_back(largeResource.directory);
        CCFileUtils::sharedFileUtils()->setSearchPaths(searchPaths);
    pDirector->setContentScaleFactor(largeResource.size.height/designResolutionSize.height);

   }

Answer: I use the following bit of code in my AppDelegate:
void AppDelegate::multiresolutionSupport()
{
    auto director = Director::getInstance();
    auto glview = director->getOpenGLView();

    cocos2d::Size designSize = cocos2d::Size(320, 480);
    cocos2d::Size resourceSize = cocos2d::Size(320, 480);
    cocos2d::Size screenSize = glview->getFrameSize();

    float margin1 = (320 + 640) / 2;
    float margin2 = (768 + 1536) / 2;

    if (screenSize.width < margin1) {
        FileUtils::getInstance()->addSearchResolutionsOrder("SD");
    } else if (480 <= screenSize.width && screenSize.width < margin2) {
        FileUtils::getInstance()->addSearchResolutionsOrder("HD");
        designSize = cocos2d::Size(screenSize.width / 2, screenSize.height / 2);
    } else {
        FileUtils::getInstance()->addSearchResolutionsOrder("HDR");
        designSize = cocos2d::Size(screenSize.width / 4, screenSize.height / 4);
    }

    resourceSize = screenSize;

    director->setContentScaleFactor(resourceSize.width / designSize.width);
    glview->setDesignResolutionSize(designSize.width, designSize.height, ResolutionPolicy::NO_BORDER);
}

Call it before loading any assets and you should have it working properly. I call it right after my glview is created in AppDelegate::applicationDidFinishLaunching().
How it works:

it uses a bunch of magic numbers to determine (roughly) what texture
resolution should we use: SD(@1), HD(@2) or HDR(@4) and then adjusts
design size accordingly, by dividing it on the content scale factor
it adds appropriate search paths to FileUtils it sets design
resolution and content scale factor for the engine
Answer: We are the team who made the multi resolution tutorial for the github link, it does support Android but the folders are just named using iOS naming conventions thats all.
Hope this helps.
Regards
Sonar Systems


Navbar com scroll usando SemanticUI

Question: Preciso fazer uma navbar fixed top. Quando o usuário rolar a página a navbar deve se manter no topo porém num tamanho menor, exibindo apenas os ícones e omitindo os textos.
Necessito que seja realizado no SemanticUI pois é a especificação do sistema.
Baseando em alguns exemplos obtidos na internet, consegui apenas fixar no topo, mas redimensionar e omitir os textos ainda não.
HTML:

        Usuários

        Distribuição Automática

        Relat&oacuterios

        Pesquisar

CSS:
   body {
    background-color: #FFFFFF;
}
.main.container {
    margin-top: 2em;
}

.main.menu {
    margin-top: 4em;
    border-radius: 0;
    border: none;
    box-shadow: none;
    transition:
            box-shadow 0.5s ease,
            padding 0.5s ease
;
}
.main.menu .item img.logo {
    margin-right: 4.5em;
}

.overlay {
    float: left;
    margin: 0em 3em 1em 0em;
}
.overlay .menu {
    position: relative;
    left: 0;
    transition: left 0.5s ease;
}

.main.menu.fixed {
    background-color: #FFFFFF;
    border: 1px solid #DDD;
    box-shadow: 0px 3px 5px rgba(0, 0, 0, 0.2);
}
.overlay.fixed .menu {
    left: 800px;
}
.ui.borderless.main.menu {
    background-color: #3d698e;

}

.ui.menu .item{
    color:#ffffff;
    padding-left: 4em;
}

.ui.footer.segment {
    margin: 5em 0em 0em;
    padding: 5em 0em;
}

#logo{
    padding-left: 10em;
}

JS:
    $(document)
    .ready(function() {

        // fix main menu to page on passing
        $('.main.menu').visibility({
            type: 'fixed'
        });
        $('.overlay').visibility({
            type: 'fixed',
            offset: 80
        });

        // lazy load images
        $('.image').visibility({
            type: 'image',
            transition: 'vertical flip in',
            duration: 300
        });

        // show dropdown on hover
        $('.main.menu  .ui.dropdown').dropdown({
            on: 'hover'
        });
    })
;

Foto:

Após o scroll o menu deve ficar igual desse site http://pt.stackoverflow.com.
Com uma altura pequena mas exibindo apenas os ícones e o logo pequenos`.
Answer: Não conheço esse framework, mas talvez seja de ajuda esse exemplo em jQuery:
$(window).scroll(function() {
    var alturaInicial = 200; // Valores de Exemplo
    var alturaReduzida = 75;

    if ($(this).scrollTop() > alturaInicial) {
        $(".main.menu").css({"height":alturaReduzida + "px"});
        $(".text-itens").hide();
        $("#logo").css({"width":"25%"});
    } else {
        $(".main.menu").css({"height":alturaInicial + "px"});
        $(".text-itens").show();
        $("#logo").css({"width":"100%"});
    }
});

Navbar com scroll usando SemanticUI


Is there a module that provides a field for referencing values of another field

Question: Initially I thought I could use the same field on both entities, but I want the user to be able to select unlimited values from the reference field limited to the options that could exist in the original field.
In the field settings, I need to have the ability to select a field to reference.  When looking at the field instance I'd like to be able to tell which field the value should be compared against.  The user should be able to select from all of the possible values of field A and store that selection in field B.
Changed this, as it made it sound like I wanted something similar to node reference

Entity 1: Field A
Entity 2: Field B (Values from Entity 1: Field A stored in Field B)

The goal is to be able to use Field B to find entities having Field A that are the same value
Is there any way to achieve this kind of relationship between fields?
Answer: Field reference module may help you !

Defines a field type for referencing one field from another.
This module is modelled on Node reference and usage is similar.
Depending on configuration, authors can pick fields from the same
  node/entity, from other nodes/entities, from specific revisions, from
  specific languages, or even a specific delta value within the field.
  Fields can be displayed using either the 'full' or 'teaser' mode from
  their original node/entity.
Comment: I looked at field reference but couldn't find a way to get it to allow me to select the values of the field, only the entity that has that value as an option.  Is there a way to list the values?


AngularJs or NodeJs or both

Question: I want to develop a website using JavaScript/HTML5/CSS3, because it is more flexible in UI. I read internet about AngularJS for the client side and about NODEJS: it can be used to both clent side and server side.
Can anyone kindly inform me about the cons and pros of the following:

use AngularJs for client side and other language for server side (EX : PHP ).
Use NODE.JS for build website
or can I use both?
Comment: take a look a this: http://mean.io/#!/
Comment: @cuttlas Oh, they almost got me, but the ninja on front page... Marketing people, please stop overusing buzz words and images.
Answer: If you want to check for pros & consof Angular only, here is the list:
PROS

Angular follows MV-Whatever architecture. Hence you can either MVP, MVC or MVVM.
It gives the flexibility to do two way binding. Data binding tries to get rid of writing codes manually by relieving the backend server from creating templates. MVC pipeline is also maintained by the framework itself.
DOM Manipulations at one place: You can make use of angular directives to play with the dom giving a neater code.There are some reusable tags defined by angular folks themselves in directives like ng-class, or ng-show. See Angular Directive Documentation
Test Ready: The fact that AngularJS comes linked with Dependency Injection (DI) makes it ready for unit testing by injecting mock data into controller and measuring the output and behavior.
Ionic Framework: Ionic Framework is written on top of Angular and is mainly used to build hybrid apps. So Angular is useful if you are going to extend your website into a mobile hybrid app.

Cons:

Difficult to adapt the existing code: AngularJS requires the developer to re-implement the entire transformation code which makes it extremely hard to play around while adapting existing code.
Heavy: Their are lighter frameworks like backbone and knockout, however seeing the power of Angular it can be easily negated

Now moving to your question whether Nodejs be used in conjunction to Angularjs my answer to it is:
AWESOME COMBINATION
You can have your server code residing in nodejs and use angularjs at client side keeping the architectures completely different. Since Nodejs also uses javascript there would be less of uptime for developers to learn it and start developing. Infact MEAN (Mongo-Express-Angular-Node) methodology.
Their are various boilerplates available in order to kick start your development. One can be found at MEAN
Comment: do You recommend to backonejs or MEAN.io
Comment: the question should be Backbone or Angular as both are client side framework. Well personally I would choose Angular as it is a framework which has lot of out of the box features and very little learning curve as compared to Backbone

AngularJs or NodeJs or both


HTML/JS good practices: Is it good to add too many ids?

Question: I have an HTML page where I would like to add elements to a specific list, like so:

// content

//content

.
.
.

Now I want to add new divs to that list, say with the following:

<input id="first-textbox-id" type="text">
<input id="second-textbox-id" type=text">
<button>Add new option</button>

Of course, the addition is done with jQuery code.
My question is: is it a good practice to add many such ids in HTML code and depend on them in my jQuery code, or is it a bad practice for both HTML and jQuery, and I should find other ways in my jQuery code (depending on DOM traversing, for example)?
Just for example of what I mean: will adding to many ids slow Javascript execution?
Answer: Id's are faster to query but very tedious to maintain, so I'd take the "performance hit" and make my code more obvious by using classes and id's only when necessary. In your example I would probably keep the id on the div but the input elements don't need one, a simple class will do for both jQuery and CSS or even no class at all.
Comment: @lanzz This answer and the benchmark in the provided link could be interesting: [Fastest selector method in jquery and CSS - ID or not?](http://stackoverflow.com/a/6036723/1456376)
Comment: Also, selectors like `#important-element .specific-subelement` tend to give more obvious context and are generally more readable than just `#specific-subelement`.
Comment: + 1 I would also say that ids are faster. I also want to add that in some cases you can't use this without the id - if every item is a record in a database that should be persiststed/upated for example. And the id on the the input can be important if every field has a label, that is not wrapped around it.
Comment: I have a love/hate relationship with JSPerf tho because generic tests are usually very unreliable but good tests can provide useful hints to improve your code's performance. When implementing native browser features I just choose the most convenient, in this case `querySelectorAll`.
Comment: @insertusernamehere: That's interesting but expected I guess. `getElementsByClassName` is faster than `querySelectorAll` that I suppose it's what the full string `#id .class` uses...
Comment: That's true - I only wanted to add it in addition or let's say as a note/hint.
Answer: Id selectors followed by Tag selectors are the best ones because they map directly to the native .getElementById() and .getElementByTag() methods
I would suggest that you always descend from the closest parent Id when you traverse the DOM. As in most languages there is always a readability/performance tradeoff that you will have to consider for your particular application.
Check out these performance guidelines for further insights
http://www.artzstudio.com/2009/04/jquery-performance-rules/


How to convert image to 4D Tenzor?

Question: How to convert image to 4D Tenzor (1,150,80,1) [batch_size, width, height, channels] ?
The model on which I train in the manual receives 16 images (16,150,80,1).
https://keras.io/api/layers/preprocessing_layers/categorical/string_lookup/
But I want to try using 1 image.
# 1. Read image
img = tf.io.read_file(img_path)
# 2. Decode and convert to grayscale
img = tf.io.decode_jpeg(img, channels=1)
# 3. Convert to float32 in [0, 1] range
img = tf.image.convert_image_dtype(img, tf.float32)
# 4. Resize to the desired size
img = tf.image.resize(img, [80, 150])
# 5. Transpose the image because we want the time
# dimension to correspond to the width of the image.
img = tf.transpose(img, perm=[1, 0, 2])

# 6. Convert
# ...

Comment: Use `tf.expand_dims(image, axis=0)` to cvt `[h, w, c]` to `[1, h, w, c]`.
Comment: @Innat You are my God, I've been trying to solve this for a day)
Answer: Thanks @Innat for the answer and @Vipz for confirming the solution worked. Adding the comment in the answer section for the community benefits.
 Use tf.expand_dims(image, axis=0) to cvt [h, w, c] to [1, h, w, c].

How to convert image to 4D Tenzor?


Prettier floats using yaml

Question: Whenever I use yaml dump to dump floats, they start to look ugly.
Input:
a.yaml
a: 0.000000015

When I read it in and then dump it to file again, it will look like:
dumped.yaml
a: 1.5e-08

Note that there's no fixed size I can go for, i.e. maybe someone wants to put a lot of zeros (and I am not "afraid" of e.g. a small fraction with 20 leading zeros)
Also, if you choose a fixed size, then it might look like the following (which I am trying to avoid as well)
a: 0.0000000150000

Comment: Can you clarify which library you're using? PyYAML, ruamel.yamel or something else?
Comment: Not easy though:
`"{:.30f}".format(0.01)` yields
`'0.010000000000000000208166817117'`
Comment: @SuperStormer I am using PyYAML, thanks for asking.
Comment: what is your way of choosing a fixed size?
Comment: @WalterTross I am not choosing a fixed size currently, might be the solution actually...
Answer: I haven't been able to find, in the format specification mini-language documentation, a way to format numbers the way you want them.
I propose a simple hack: to replace, in the output of PyYAML, all numbers in scientific notation with their fixed-point equivalent, like this:
import re
import yaml

# only accepts Python's/PyYAML's default scientific format, on purpose:
E_REGEX = re.compile(r'(\b|-)([1-9])(?:\.(\d+))?e([+-])(\d+)\b')

def e_to_f(match):
    sf, f0, f1, se, e = match.groups()
    if f1 is None: f1 = ''
    f = f0 + f1
    n = int(e)
    if se == '-':
        z = n - 1  # i.e., n - len(f0)
        if z < 0:
            return sf + f[:-z] + '.' + f[-z:]
        else:
            return sf + '0.' + '0' * z + f
    else:
        z = n - len(f1)
        if z < 0:
            return sf + f[:z] + '.' + f[z:]
        else:
            return sf + f + '0' * z + '.0'

e_dict = {
    'example': 1.5e-15,
    'another': -3.14e+16
}
e_txt = yaml.dump(e_dict, sort_keys=False)
f_txt = E_REGEX.sub(e_to_f, e_txt)
print(e_txt)
print(f_txt)

# output:
#
# example: 1.5e-15
# another: -3.14e+16
#
# example: 0.0000000000000015
# another: -31400000000000000.0

Answer: You can subclass yaml.Dumper to override the representer method for floats with one that only outputs standard notation. This method should be less hacky than regex substitution.
import decimal

import yaml

# from https://stackoverflow.com/a/38847691/7941251
ctx = decimal.Context()
ctx.prec = 20  # change for more precision

def float_to_str(f):
    """
    Convert the given float to a string,
    without resorting to scientific notation
    """
    d1 = ctx.create_decimal(repr(f))
    return format(d1, 'f')

class CustomDumper(yaml.SafeDumper):
    # modified from https://github.com/yaml/pyyaml/blob/master/lib3/yaml/representer.py#L171
    def represent_float(self, data):
        if data != data or (data == 0.0 and data == 1.0):
            value = '.nan'
        elif data == self.inf_value:
            value = '.inf'
        elif data == -self.inf_value:
            value = '-.inf'
        else:
            value = float_to_str(data).lower()
        return self.represent_scalar('tag:yaml.org,2002:float', value)

CustomDumper.add_representer(float, CustomDumper.represent_float)

print(yaml.dump({"a": 0.000000015}, Dumper=CustomDumper)) # a: 0.000000015

Feel free to change float_to_str to a different method for converting floats to standard notation.
Comment: I suggest to give a different name to the `Dumper` class, in order to avoid confusion with `yaml.Dumper`

Prettier floats using yaml


Request-Promise-Native ignores specified headers

Question: I am somewhat new to Nodejs. I am working on a pair of Microservices, and I need one to post data to the other.  I am using the request-promise-native library.
My code is to make the call is like this:
  const options = {
            method: 'POST',
            uri: url,
            formData: {
                command: command,
                version: version,
                session_id: sid,
                aicc_data: data
            },
            headers: {
                'content-type' : 'application/x-www-form-urlencoded'
            }
        }

         rp(options)

However, when I inspect the request as it come in to the other server, the header I have specified does not appear.
headers: { 'content-type': 'multipart/form-data; boundary=--------------------------395968157759002211606136',
  host: 'localhost:9000',
  'content-length': '513',
  connection: 'close' }

What am I doing wrong?
Answer: options includes a formData object which enforces multipart/form-data.
You should add the form object instead when you want to use application/x-www-form-urlencoded.
Comment: how do you achieve that in request-promise?
you are referring to request documentation.

thanks
Comment: @GalMargalit ["Since request-promise wraps around request everything that works with request also works with request-promise."](https://www.npmjs.com/package/request-promise#cheat-sheet) So it shouldn't make a difference.
Comment: thanks, I'm meeting some difficulties. will give it a few more shots


How frequent can we do SQL transaction log backups?

Question: I'm installing a highly critical system. If the system fails, the users wants data up to the last minute.
To achieve this, I was thinking of running Transaction Log Backups + FTP every minute. Has anybody done this before? Is this the best way to achieve the 1-minute data loss tolerance?
Appreciate any advice,
Thanks!
Answer: Well, you can do frequent tx log, but it still looses data.
Best approach is:

3 database servers, one small free edition as witness, using safe mirroring.

2 copies of the database, kept in sync.
Then use DPM (Data Protection Manager) to make near real time backups of that.
Particularly target an ugprade to SQ LServer 2012 asap and mirror the database files on both servers (total: 4 copies of the database), preferably on separate casings / raid controllers.
Yes, that gets expensive -but then "highly critical" means "pay what it takes".
And you do not need FTP - SQL Server Log File Shipping can ship out the logs itself via file share.
Comment: Thanks for the reply. The thing is this is not for mirroring. It's just for SQL Backup Only. + It is expensive. What's wrong with using regular log backup?
Comment: THat you will loose data. Point. In my world "Highly Critical" means "I am not allowed to loose data". Like financial trading applications. It means immediately "backup sytem real time mirrored in another data center". Your definition of highly critical maybe 99.99%, but this is not highly critical for the world. Also note that your system may be down for days anyway without available backup system (takes time to get a datbase server delivered and installed). The third machine can be a small virtual one.
Answer: At that frequency, you'd probably be better off using database mirroring.
Answer: For deploying High Availability solutions, I always recommend the use of HP Storage mirroring software.
http://h18006.www1.hp.com/products/storage/software/sm/


Document serialization with Doctrine MongoDB ODM

Question: I'm trying to code a class handling serialization of documents by reading their metadata. I got inspired by this implementation for entities with Doctrine ORM and modified it to match how Doctrine ODM handles documents. Unfortunatly something is not working correctly as one document is never serialized more than once even if it is refered a 2nd time thus resulting on incomplete serialization.
For example, it outputs this (in json) for a user1 (see User document) that belongs to some place1 (see Place document). Then it outputs the place and the users belonging to it where we should see the user1 again but we don't :
{
  id: "505cac0d6803fa1e15000004",
  login: "user1",
  places: [
    {
      id: "505cac0d6803fa1e15000005",
      code: "place1",
      users: [
        {
          id: "505c862c6803fa6812000000",
          login: "user2"
        }
      ]
    }
  ]
}

I guess it could be related to something preventing circular references but is there a way around it ?
Also, i'm using this in a ZF2 application, would there be a better way to implement this using the ZF2 Serializer ?
Thanks for your help.
Comment: To answer my question, @superdweebie made a great Doctrine library that he described below that contains a serializer. If you use the eager fetching then you'll have all the documents returned. For now though you might end up in circular references problem but we're working on [a feature](https://github.com/superdweebie/doctrineExtensions/issues/6) to implement a max nesting depth option.
Answer: I have a serializer already written for DoctrineODM. You can find it in http://github.com/superdweebie/DoctrineExtensions - look in lib/Sds/DoctrineExtensions/Serializer.
If you are are using zf2, then you might also like http://github.com/superdweebie/DoctrineExtensionsModule, which configures DoctrineExtensions for use in zf2.
To use the Module, install it with composer, as you would any other module. Then add the following to your zf2 config:
'sds' => [
    'doctrineExtensions' => [
        'extensionConfigs' => [
            'Sds\DoctrineExtensions\Serializer' => null,
        ),
    ),
),

To get the serializer use:
$serializer = $serivceLocator->get('Sds\DoctrineExtensions\Serializer');

To use the serializer:
$array = $serializer->toArray($document)
$json = $serializer->toJson($document)

$document = $serializer->fromArray($array)
$document = $serializer->fromJson($json)

There are also some extra annotations available to control serialization, if you want to use them:
@Sds\Setter - specify a non standard setter for a property
@Sds\Getter - specify a non standard getter fora  property
@Sds\Serializer(@Sds\Ignore) - ignore a property when serializing

It's all still a work in progress, so any comments/improvements would be much appreciated. As you come across issues with these libs, just log them on github and they will get addressed promptly.
Finally a note on serializing embedded documents and referenced documents - embedded documents should be serialized with their parent, while referenced documents should not. This reflects the way data is saved in the db. It also means circular references are not a problem.
Update
I've pushed updates to Sds/DoctrineExtensions/Serializer so that it can now handle references properly. The following three (five) methods have been updated:
toArray/toJson
fromArray/fromJson
applySerializeMetadataToArray

The first two are self explainitory - the last is to allow serialization rules to be applied without having to hydrate db results into documents.
By default references will be serialized to an array like this:
[$ref: 'CollectionName/DocumentId']

The $ref style of referencing is what Mongo uses internally, so it seemed appropriate. The format of the reference is given with the expectation it could be used as a URL to a REST API.
The default behaviour can be overridden by defineing an alternative ReferenceSerializer like this:
/**
 * @ODM\ReferenceMany(targetDocument="MyTargetDocument")
 * @Sds\Serializer(@Sds\ReferenceSerializer('MyAlternativeSerializer'))
 */
protected $myDocumentProperty;

One alternate ReferenceSerializer is already included with the lib. It is the eager serializer - it will serialize references as if they were embedded documents. It can be used like this:
/**
 * @ODM\ReferenceMany(targetDocument="MyTargetDocument")
 * @Sds\Serializer(@Sds\ReferenceSerializer('Sds\DoctrineExtensions\Serializer\Reference\Eager'))
 */
protected $myDocumentProperty;

Or an alternate shorthand annotation is provided:
/**
 * @ODM\ReferenceMany(targetDocument="MyTargetDocument")
 * @Sds\Serializer(@Sds\Eager))
 */
protected $myDocumentProperty;

Alternate ReferenceSerializers must implement Sds\DoctrineExtensions\Serializer\Reference\ReferenceSerializerInterface
Also, I cleaned up the ignore annotation, so the following annotations can be added to properties to give more fine grained control of serialization:
@Sds\Serializer(@Sds\Ignore('ignore_when_serializing'))
@Sds\Serializer(@Sds\Ignore('ignore_when_unserializing'))
@Sds\Serializer(@Sds\Ignore('ignore_always'))
@Sds\Serializer(@Sds\Ignore('ignore_never'))

For example, put @Sds\Serializer(@Sds\Ignore('ignore_when_serializing')) on an email property - it means that the email can be sent upto the server for update, but can never be serialized down to the client for security.
And lastly, if you hadn't noticed, sds annotations support inheritance and overriding, so they play nice with complex document structures.
Comment: Hi @superdweebie, thanks for your help here. I tried your serializer but ran into the problem that referenced documents are still serialized and retrieved as objects because [here](https://github.com/superdweebie/doctrineExtensions/blob/master/lib/Sds/DoctrineExtensions/Serializer/Serializer.php#L190) there doesn't seem to have a check for `$mapping['reference']` to not add them. Also what about getters that don't return strings such as date objects ?
Comment: On a side note, how would you do to expose some kind of API to access the data of your app with references to documents if you don't retrieve those in the serializer itself ?
Comment: Hey @jhuet, thanks for taking the time to give it a go. I'll add a test case for serializer ref documents (I don't think I had one). As for API, I was thinking of using something like this: http://dojotoolkit.org/reference-guide/1.8/dojox/json/ref.html. I haven't actually had need to do this (yet), which is why the code isn't all 100%. But this is a good change to harden the lib up a bit more.
Comment: No problem :) The dojox.json.ref looks like an interesting approach, do you know how widely it is adopted yet ? So far on any API i've come accross, the refered documents were just output as plain document. And btw it doesn't seem to solve how you will retrieve those refered documents in the 1st place. How do you know on the server-side if a document should be served as a reference or as a plain document if it's the 1st time it is sent ? I doubt the client should send all the documents he has knowledge of at every requests ?
Comment: @jhuet I've just pushed a few changes, as noted above. They may help.
Comment: Wow, that's what you call a _few_ changes ! Awesome job there, thanks ! There's _almost_ everything i need ;) For now i feel more comfortable using the Eager way for serializing references and of course i came accross the circular references problem. Do you think some kind of max recursion depth detector could be added ?
Answer: Another very simple, framework independent way to transforming Doctrine ODM Document to Array or JSON - http://ajaxray.com/blog/converting-doctrine-mongodb-document-tojson-or-toarray
This solution gives you a Trait that provides toArray() and toJSON() functions for your ODM Documents. After useing the trait in your Document, you can do -
<?php
// Assuming in a Symfony2 Controller
// If you're not, then make your DocmentManager as you want
$dm = $this->get('doctrine_mongodb')->getManager();
$report = $dm->getRepository('YourCoreBundle:Report')->find($id);

// Will return simple PHP array
$docArray = $report->toArray();

// Will return JSON string
$docJSON = $report->toJSON();

BTW, it will work only on PHP 5.4 and above.
Comment: @laalto, I've added code sample of using this solution. Thanks.


Algorítmo de busca binária em Python

Question: Olá, eu quero criar uma função que dado uma lista a e um valor m dentro desta lista, retorne a posição do valor m.
A minha ideia era começar com os valores extremos da lista ordenada e pegar o ponto médio até encontrar o valor m (e então retornar sua posição):
def bissecp(a,m):

    n = len(a) - 1

    i=0

    encontrou = False

    meio = int(((a[i] + a[n]) / 2))

    if m==a[i]:
        return i
    if m==a[n]:
        return n
    index = 0
    if m == meio:
        encontrou == True
        return int((i+n)/2)
    while encontrou == False:
        if m> meio:
            i+=1
            meio = int((a[i] + a[n])/2)
            if m == meio:
                 index = int((i+n)/2)
                 encontrou==True
            continue
        if m < meio:
            i += 1
            meio = int((a[i] + a[n-i]) / 2)
            if m == meio:
                index = int((a[i] + a[n-i])/2)
                encontrou==True

    return index

a = list(range(1, 100))

mas está retornando o seguinte erro :
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 28, in bissecp
IndexError: list index out of range

Answer: O maior problema na sua tentativa é que você está fazendo:
meio = int(((a[i] + a[n]) / 2))

Isso pega o elemento de "a" na posição "i", e o elemento de a
na posição "n" e tira a média -
Quando você deveria estar pegando é o elemento de "a" que
está na posição (i + n) // 2.
Sua variável "meio" é um número que possivelmente nem está na lista -
não faz sentido comparar ele com o número que está sendo buscado, na variável m.
Pode ter funcionado em alguns casos por que você passou um range, que vai de "1" em "1", mas se passar uma lista com números aleatórios, em ordem crescente, vai ficar ainda mais maluco.
Uma outra dica para te ajudar: não tem por que economizar letras nos nomes
de variáveis - isso só deixa o código mais difícil de ler. Por que "a" e "m"? Dá pra chamar de "lista" e "alvo". Daí você compara um "elemento da lista, no índice computado" com o "alvo": if lista[index] == alvo: encontrou = True.
Eu não vou sugerir pequenas modificações no seu programa, por que essa confusão de índice com o conteúdo deixa o mesmo bastante errado - tenha essas dicas em mente, e tente re-fazer o programa (vai ser mais fácil do que tentar arrumar esse código).
A última dica é que esse erro específico acontece por que em algum ponto você
tenta recuperar um elemento da lista "a" que está para além do comprimento dela. Se o algoritmo estivesse correto, isso nunca aconteceria - os índices sempre
vão se movendo pra dentro da lista. Mas como você está atualizando os índices de forma praticamente arbitrária, misturando os índices com o conteúdo da lista, não tem nada que garanta que o valor seja comportado.
Para ter uma lista de valores malucos crescentes, que você possa testar pode fazer usar o random.choices:
In [421]: import random

In [422]: lista = sorted(random.choices(range(1000), k=10))

In [423]: lista
Out[423]: [54, 73, 186, 279, 480, 508, 572, 589, 707, 845]

Answer: O algoritmo desejado na pergunta é de busca binária. Algoritmo de bissecção é um algoritmo para obtenção de raízes, também conhecido como pesquisa binária e daí talvez a confusão.
O algoritmo de busca binária pode ser implementado da seguinte forma:
def bb(a,m):

    esq = 0
    dir = len(a) - 1

    while esq <= dir:

        meio = (esq + dir) // 2  # operador // significa divisão inteira (truncada)

        if a[meio] == x:
            return meio
        elif x  meio:
            esq = meio + 1

    return -1 # retorna -1 se o elemento não foi encontrado

a = list(range(1, 100)) # não inclui o valor 100

x = int(input("Elemento a ser buscado: "))

localizacao = bb(a, x)

if localizacao == -1:
    print("Elemento não encontrado.")
else:
    print("Localização do elemento: " + str(localizacao) + ".")  # localizacao comecando em 0

Caso queira ler uma lista ordenada ao invés de gerar um range, utilize o seguinte código:
input_string = input("Entre a lista crescente de inteiros separados por espaços: ")
a  = [int(item) for item in input_string.split()]

Algorítmo de busca binária em Python


How to create a Toast when Press and Hold a button

Question: I am working on a Currency Convertor Project in Java for Android. My buttons are labelled as Currency icons and I want user to know the details about currency via Toast message I want to generate that toast message when user Click and Hold any button. In short I want to add onHoldListener(Kind of) in my Code
Answer: You can call setOnLongClickListener for your button:
 button.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {

            Toast.makeText(Context, "some text", Toast.LENGTH_SHORT).show();
            return true;
        }
    });


How to produce the minimum forecast error using R?

Question: Considering that we want to use optimize() on the interval [0,1] how can I write an R code for finding the value of β that produces the minimum forecast error without using external packages like forecast?

For simplicity assume that:

I want to use the following package:
> require(datasets)
> str(nhtemp)
 Time-Series [1:60] from 1912 to 1971: 49.9 52.3 49.4 51.1 49.4 47.9 49.8 50.9 49.3 51.9 ...

in which nhtemp is the Yearly Average Temperatures in New Haven CT.
Comment: let us know if this is a home work, if yes please let us know. Also let us know what have you tried so far from Rob's response below. I would be able to help if you clarify these questions. Also you could refer to an excellent blog from Peter Flom on asking questions about statistics in general.http://www.statisticalanalysisconsulting.com/how-to-ask-a-statistics-question/
Comment: This is a HW and I already had the tag for it! I looked at holtwinters R code but the code is really giant and I know I don't want all of its functionalities for this question. I just need more hints where to get started. I will take a look at it. Whatever I search in Google ends up using holtwinters function so it's really hard to find help.
Answer: Two simple ways. Use the forecast package:
library(forecast)
fit <- ses(nhtemp,initial='simple')
beta <- fit$model$par[1]

Or use the stats package:
fit <- HoltWinters(nhtemp,gamma=FALSE,beta=FALSE)
beta <- fit$alpha

Comment: Either will work with only one parameter to optimize.
Comment: Thank you so much for the reply. It is really instructive. However I am also curious to know what if I want to find Beta without using external packages? I know it's more of a work but what are the approaches? If you know of an algorithm or idea that would be great to add it to you answer.
Comment: also does the code you have provided assume that Y_hat_2=Y_hat_1=Y_1 ? Or how can we add this assumption to the code? I'd be happy if you explain on this. :)
Comment: Yes, $\hat{y}_1=y_1$. Then $\hat{y}_2=y_1$ as a consequence. You can write your own code using `optim` if you want to. Is this homework?
Comment: so the function name is optim not optimize? I just checked ?optim and ?optimize and RStudio has both of them! thanks!
Answer: I hope you attempted to solve the HW problem yourself. See below for the complete code on how to do this using R and Optim function for your reference. I'm also providing you some nice references for you to try solving optimization problems in the context of exponential smoothing that would assist you to learn to solve optimization problems by hand. Based on my personal experience I have to tell that Optimization is a specialized field, you would want to take a course/reading on that before you start applying these techniques to forecasting problems.
There is an excellent article click here by Rasmussen that appeared in the Omega: The international journal of management science that would provide necessary back ground on how to optimize smoothing parameters as well as initial parameters using a nonlinear optimization tool like excel solver, you could try to replicate this yourself to learn how these parameters are optimized for exponential smoothing models.
If you  are interested in solving the problem that you stated in your post using R, as Rob pointed out you need to write a function to optimize the parameter beta and then using optim function to solve for that parameter.
You can also compare the beta values with a simple exponential smoothing in the forecast package. Both are similar (Beta value: 0.186088).
require(datasets)
str(nhtemp)

y <- as.matrix(nhtemp) ## Convert time series data to a matrix format

n = length(y)

## initialize
yh = rep(NA,60) ## Y hat
fe = rep(NA,60)
yh[[1]] = y[1] ## Initialize Yhat[1] with y [1]

## function to optimize

mind <- function (b){ for (i in 2:n)  {
                        yh[i] <- b*y[i-1]+(1-b)*yh[i-1]
                      }
                      fe <- (yh-y)^2
                      obj <- mean(fe)
                      return(obj)
}
## Optimize to obtain parameter b

optm <- optim(par=c(0.2), fn=mind, gr = NULL, lower = 0, upper = 1,
              method = c("L-BFGS-B"))

## Print beta value

optm$par

## Check your answer with simple exponential smoothing from
##forecast package from Rob's code above

library(forecast)
fit <- ses(nhtemp,initial='simple')
beta <- fit$model$par[1]
beta


How to retrieve 1 document from firebase/firestore collection based on date in dart/flutter?

Question: Ofc, I know the basic way we retrieve a whole bunch of documents from a collection like so:
<code>      stream: Firestore.instance
          .collection("collection_name")
          .orderBy("date", descending: true) // new entries first
          .snapshots(),
      builder: (context, snapshot) { ....
</code>
This is fine when I'm displaying a whole bunch of data.
But I have situation where I need to do some calculations with the last added numbers, meaning I just need to get 1 document, so I what I do is sort data by date and limit by 1, then make the query for this one document like this
<code>List<DocumentSnapshot> list;
    QuerySnapshot querySnapshots;
    if (await AuthHelper.checkIfUserIsLoggedIn()) {
      String userId = await AuthHelper.getUserID();
      querySnapshots = await Firestore.instance
          .collection("collection_name")
          .orderBy("date", descending: true) // new entries first, date is one the entries btw
          .limit(1)
          .getDocuments(); // Get Documents not as a stream
      list = querySnapshots.documents; // Make snapshots into a list
      return (list ?? null);
    } else {
      return null;
    }
</code>
But is this the best way to do it ? When making this query aren't I getting the whole set of documents and discarding the rest ? Which means when this collections grows this is going get slower and slower ?
Is there a better way to retrieve the last added document ? So I can use it as list/array/map and not as stream ?
Thanks.
Answer: When you limit the query, you are only ever going to read that number of documents maximum.  It's not going to read the entire collection and discard the extras.
Comment: Hmmm, but I am sorting by date first , so doesn't that mean, it is sorting through all of it ?
Comment: No, the sort happens on the server, and it uses an index to figure out which documents to actually read.  Firestore won't let you perform any query that doesn't scale.