Annotations loaded from plist not showing

Question: This is the first time I am using a plist. I have been browsing around and I can't find any other help.
I have the code below in my viewDidLoad. How come my annotations are not showing?
    mapView.showsUserLocation = YES;
mapView.delegate=self;

NSMutableArray *annotations = [[NSMutableArray alloc]init];
NSString *path = [[NSBundle mainBundle] pathForResource:@"StationAddress" ofType:@"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
NSArray *anns = [dict objectForKey:@"GasStation"];
NSLog(@" MapView is %@",mapView);
NSLog(@"anns is: %@", anns);

for(int i = 0; i < [anns count]; i++) {
    NSLog(@"read2");

    double realLatitude = [[[anns objectAtIndex:i] objectForKey:@"Latitude"] doubleValue];
    NSLog(@" double lat value is %f",realLatitude);
    double realLongitude = [[[anns objectAtIndex:i] objectForKey:@"Longitude"] doubleValue];
    NSLog(@" double lot value is %f",realLatitude);

    NSLog(@"read3");

    MyAnnotation *myAnnotation = [[MyAnnotation alloc] init];
    CLLocationCoordinate2D theCoordinate;
    theCoordinate.latitude = realLatitude;
    theCoordinate.longitude = realLongitude;
    myAnnotation.coordinate=CLLocationCoordinate2DMake(realLatitude,realLongitude);

    myAnnotation.title = [[anns objectAtIndex:i] objectForKey:@"Name"];
    myAnnotation.subtitle = [[anns objectAtIndex:i] objectForKey:@"Address"];

    [mapView addAnnotation:myAnnotation];
    [annotations addObject:myAnnotation];
    [myAnnotation release];

EDIT MyAnnotation.h
@interface MyAnnotation : NSObject<MKAnnotation> {

CLLocationCoordinate2D  coordinate;
NSString*               title;
NSString*               subtitle;

}
@property (nonatomic, assign)   CLLocationCoordinate2D  coordinate;
@property (nonatomic, copy)     NSString*               title;
@property (nonatomic, copy)     NSString*               subtitle;

MyAnnotation.m
@implementation MyAnnotation

@synthesize title;
@synthesize subtitle;
@synthesize coordinate;

Hard Code for annotations, (this is inside viewdidload)
[mapView setShowsUserLocation:YES];

CLLocation *userLoc = mapView.userLocation.location;
CLLocationCoordinate2D userCoordinate = userLoc.coordinate;

NSLog(@"user latitude = %f",userCoordinate.latitude);
NSLog(@"user longitude = %f",userCoordinate.longitude);

mapView.delegate=self;

NSMutableArray* annotations=[[NSMutableArray alloc] init];

MKPointAnnotation *annot1 = [[MKPointAnnotation alloc] init];
annot1.title = @"TItle1";
annot1.subtitle=@"Address of title";
annot1.coordinate = CLLocationCoordinate2DMake(21.946114, 120.792778);
[mapView addAnnotation:annot1];

and I did this for 3000 of them, but they ran slow, so I am trying to find a better way
Comment: How many annotations does the first NSLog show?  Try logging the lat and long values to make sure they're correct.  Make sure `mapView` is not nil.  Also, `[MyAnnotation release];` should be `[myAnnotation release];`.
Comment: Sorry Maybe I am too newbie to understand some part of what you are asking, but This is what it come out from the first NSlog:         {
        Address = "\U5f70\U5316\U7e23\U798f\U8208\U9109\U6cbf\U6d77\U8def\U56db\U6bb5256\U865f";
        Latitude = "24.035067";
        Longitude = "120.419800";
        Name = "\U53f0\U5851\U77f3\U6cb9";
    }
and it has about 2000+ of them. When I hardcode it, it shows perfectly fine, but once i use this plist, it disapper. mapView is sure not nil, and I did change My to my. THank you for helping and look forward for your additional helps. THanks!
Comment: Or do you recommend some other to do it? Thanks you very much. @Anna Karenina
Comment: While testing, just put 3 annotations in the plist.  After the `addAnnotation` line, put this: `NSLog(@"mapView.annotCount=%d, myAnnotation.coordinate=%f,%f", mapView.annotations.count, myAnnotation.coordinate.latitude, myAnnotation.coordinate.longitude);` and see what it prints.
Comment: Temporarily change `MyAnnotation *myAnnotation = [[MyAnnotation alloc] init];` to `MKPointAnnotation *myAnnotation = [[MKPointAnnotation alloc] init];` and then add that NSLog.  What happens?
Comment: it shows all 3 annotations [3940:207] mapView.annotCount=3, myAnnotation.coordinate=24.035067,120.419800   And the annotations are still not showing up at all. What is wrong?     @AnnaKarenina
Comment: And When I put all the annotations in and run it, it says receive memory warning and it takes about 14 seconds to finish loading it. After loading it, THe map didnt show up at all. @AnnaKarenina
Comment: If you have implemented the viewForAnnotation delegate method, please add that code to the question.
Comment: I don't have ViewforAnnotation, but I have the MyAnnotation.h and .m and let me post it.
Answer: Try this.
Change:
     float realLatitude = [[[anns objectAtIndex:i] objectForKey:@"Latitude"] floatValue];

To this:
     double realLatitude = [[[anns objectAtIndex:i] objectForKey:@"Latitude"] doubleValue];
     NSLog(@" double lat value is %f",realLatitude);

(do longitude also).
Also hint:  check for your annotations in the southern Atlantic Ocean, south west of Equatorial Guinea - that's where Lat/Lon of {0,0} is, and if your data isn't converting correctly, that's where your annotations might be.
Comment: I input them in, but The are not in 0,0 either. Maybe you can advice me some other ways to work it out?
Comment: In viewDidLoad, before your loop, add `NSLog(@" MapView is %@",mapview);` and see what you get.
Comment: MapView is >
Comment: It's very odd since When I hard code it, it works fine, but once i switch to plist, it doesn't load at all
Comment: Have you tried using CLLocationCoordinate2DMake inside your for loop?
Comment: No I haven't really try coz I don't know how that work. Whenever I tried annot.coordinate = CLLocationCoordinate2DMake(@"Latitude", @"Longitude"); It keeps saying I didn't define Latitude and Longitude.
Comment: In the code I posted in this answer, it shows how to get a value for realLatitude.  Do the same for realLongitude, and then do this:  `annot.coordinate=CLLocationCoordinate2DMake(realLatitude,realLongitude);`
Comment: I did what you said and please see my repost of the question on all the way to the top regard to the change I made with your help. The annotations are still not showing. I wonder why. Or Am i using the wrong code or wrong way? or is there a better way to load all 3000 dots faster without doing plist? Thanks in advance @Rayfleck
Comment: From the code you've posted, I can't find anything wrong.  As for the 3000, I have to wonder if the user will be able to use all 3000 in a meaningful way.  Is there a more relevant subset you can show?
Comment: Subset, do you mean it eg like by city? if so, can you give me some help on that?   Yeah the code is perfectly fine but slow, and that is why i was trying to do plist.
Comment: When I am only hardcoding few hundred dots, it works perfectly fine, but when I put in all 3000, it gets very slow sometime shows memory leak. can you give me a hand on this?
Comment: Where is are the 3000 dots' data stored when you're not using a plist?
Comment: just under view did load, and when the dots are only few hundred, it load fast, but not when there are 3000. It take forever even to compile the file.
Comment: Would you be willing to zip up the project and email it to me?  I will take a look and see if I can help you.  email@example.com
Comment: wow Damn, While I was testing it out and it works!!! stupid reason. Coz I forgot to change my image name lol to the right name. But Thanks a lot!!!. And do you know how to make beginning lauch faster?


Two outlook mail accounts with only 1 sender address

Question: The users are receiving mails from 2 accounts but are supposed to send and reply only from one mail account, disregarding on what account the mail was received on.
The sender account is tagged as primary and the check mark in the sending options is already set "use primary account as standard sending address"
It works for creating a new mail too, but not when the mail is forwarded or replied on the other account.
What options do I have?
Answer: Per my knowledge, this is by design, you need to change the "from" field manually when reply or forward messages in another account in outlook. As below:


Kafka Consumer group rebalancing

Question: I'm using kafka consumer group management for processing my messages.
The processing time for my messages vary from one another. So I have set the max poll interval to 20 min for max records of 20. And I'm using 5 partition and 5 consumer instances with default config values apart from the above two.
But still I'm getting the following error intermittently:
[Consumer clientId=consumer-3, groupId=amc_dashboard_analytics] Attempt to heartbeat failed since group is rebalancing

The understanding is that rebalancing won't occur unless poll is not called before max poll interval is reached as written in consumer config Docs. But for me rebalancing occurs before 20 minutes only.
Also after few hours of running, all the assigned consumers just leave saying "Attempt to heartbeat failed since group is rebalancing" and do not join back again(Ideally should join back again).
Am I missing something here? Any leads would be helpful.
Comment: Heartbeats are the basic mechanism to check if all consumers are still up and running. If you get a heartbeat failure because the group is rebalancing,
Comment: it indicates that your consumer instance took too long to send the next heartbeat and was considered dead and thus a rebalance got triggered
Comment: @DeV but why is it taking time to send heartbeat. What I read was consumer keep on sending heartbeats in a parallel thread separate from max poll interval processing thread.
Comment: A rebalance will also occur when consumers join or leave the group.
Comment: @Nobita I added some possible reasons to cannot send heartbeat to broker. You can check my answer.
Answer: Another reason of rebalance is expiring session.timeout.ms without sending heartbeat. You can consider to increase this consumer config.
From Kafka docs:

heartbeat.interval.ms: The expected time between heartbeats to the
  consumer coordinator when using Kafka's group management facilities.
  Heartbeats are used to ensure that the consumer's session stays active
  and to facilitate rebalancing when new consumers join or leave the
  group. The value must be set lower than session.timeout.ms, but
  typically should be set no higher than 1/3 of that value. It can be
  adjusted even lower to control the expected time for normal
  rebalances. (default: 3000)

session.timeout.ms: The timeout used to detect client failures when
  using Kafka's group management facility. The client sends periodic
  heartbeats to indicate its liveness to the broker. If no heartbeats
  are received by the broker before the expiration of this session
  timeout, then the broker will remove this client from the group and
  initiate a rebalance. Note that the value must be in the allowable
  range as configured in the broker configuration by
  group.min.session.timeout.ms and group.max.session.timeout.ms. (default: 10000)

You can check this link for more information.
Even if heartbeat is sent in fixed time intervals via separate thread, in some cases heartbeat cannot be sent to broker in session.timeout.ms. Some of the possible reasons of this situation is:

Network problem
stop-the-world garbage collection in consumer or broker sides
Comment: @Nobita Yes. I experienced this kind of situation in production. If memory used by JVM (-XmX) is not enough, it leads more frequent GC. And during GC, threads including heartbeat cannot be run as expected. I suggest you to monitor GC logs with this JVM opitons to be sure:   ` -XX:+PrintGC -XX:+PrintGCDetails
 -XX:+PrintGCTimeStamps
-Xloggc:`   By the way as I mentioned in the answer, my advise is to simply increasing `session.timeout.ms`  as workaround until diagnosing main reason.
Comment: What is "stop-the-world garbage collection"?
Comment: @Nobita "Stop-the-world means that the JVM is stopping the application from running to execute a GC. When stop-the-world occurs, every thread except for the threads needed for the GC will stop their tasks. The interrupted tasks will resume only after the GC task has completed. GC tuning often means reducing this stop-the-world time."  [link](https://www.cubrid.org/blog/understanding-java-garbage-collection)
Comment: Also could memory be a reason for heartbeat failure?
Comment: And on what basis should I set the value for session.timeout.ms, like what would be the ideal value?
Comment: @Nobita this config wil affect failure detection time. So it's totaly up to your needs. Maybe you can set it to 30 seconds and then monitor. (If detecting client failure up to 30 seconds is okay for you)
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/209988/discussion-between-nobita-and-h-c-t).

Kafka Consumer group rebalancing


scala JavaTokenParsers Parser[Any] from String

Question: I am newbie in scala
Сan someone explain how string "2222222222" will be cast to Parser[Any] in example bellow? why Parser[Any] is acceptable from Sting?
object TestParser extends JavaTokenParsers
{
  def a : Parser[Any] = "2222222222"
}

what method of Parser[+T] class I need to explore for understand it?  Thanks
Answer: it's resolved by implicit conversions
implicit def literal(s: String): Parser[String]

in RegexParsers


Xamarin Method 'Plugin.Geolocator.Abstractions.IGeolocator.GetPositionAsync' not found

Question: Esta me retornando um erro:

"Method 'Plugin.Geolocator.Abstractions.IGeolocator.GetPositionAsync'
  not found"

Na versão IOS esta funcionando bem, porém no Android alguém poderia me dar uma dica?
É meu primeiro app em Xamarin
using Xamarin.Forms;
using Plugin.Geolocator;
using System.Threading.Tasks;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System;

namespace LocationSampleApp
{
    public partial class LocationSampleAppPage : ContentPage
    {
        public LocationSampleAppPage()
        {
            InitializeComponent();
            btnTeste.Clicked += BtnGetLocation_Clicked;
        }

        public async void BtnGetLocation_Clicked(object sender, EventArgs e)
        {
            await RetreiveLocation();
        }

        private async Task RetreiveLocation()
        {
            var locator = CrossGeolocator.Current;
            locator.DesiredAccuracy = 50;

            if (locator.IsGeolocationAvailable && locator.IsGeolocationEnabled)
            {
                var position = await locator.GetPositionAsync(TimeSpan.FromSeconds(100));
                if (position == null)
                    return;

                txtLang.Text = "Latitude " + position.Latitude.ToString();
                txtLong.Text = "Longitude " + position.Longitude.ToString();
            }
            else{
                await DisplayAlert("Error", "Home", "OK");
            }
        }
    }
}

Comment: voce incluiu a biblioteca no projeto android?
Comment: certifique-se de quanto trabalhar com alguma biblioteca, a mesma deve ser instalada em todos os projetos (Portable, iOS, Android e UWP).
Comment: sim esta instalada, no projeto LocationSampleApp.Droid -> "Packeges" Xam.Plugin.Geolocator tem que instalar e mais algum lugar ?
Comment: Faz o seguinte, deleta as pastas BINS e OBJ de todos os projetos depois faz um restore dos pacotes! o Xamarin é cheio desses detalhes, as vezes sempre preciso fazer isso quando passo por este tipo de problema!
Comment: funciono :D.. deleta as pastas BINS e OBJ de todos os projetos depois faz um restore dos pacotes!
Answer: Deleta as pastas BIN e OBJ de todos os projetos e em seguida faz um RESTORE dos pacotes! O Xamarin tem muito desses pequenos detalhes! ;) Espero ter ajudado!


Cross-posting from Travel

Question: We seem to be getting quite a few cross-posts from travel.
I'm a little uncertain what we should be doing about it. We can't close them as dupes of the travel site question (not in principle, the site just won't let me do it).
That leaves us to either allow karma-collecting and copy and paste answers, or close as 'cross-posting' with a link to the travel one.  I've just done that on one today, although another one I answered, primarily because he asked it on here before there was an answer on travel for him.
I think I'm now in favour of the following algorithm:

Close as off-topic with reason "question already exists on travel"
Post link to travel question.
Comment asking the OP to please not cross-post, as it's generally frowned upon on SE.

THe only issue I have with this now is if there's no answer on travel for them. Do we still follow this just because it's on Travel? I'd argue possibly yes, since anyone with an answer on either expats or travel can go post it on the un-closed one. But I'm not sure.
Thoughts?
Answer: I like your approach with a slight modification.

Decide if the question is a better fit here or on the other site (ignoring if it has answers)
If it is a better fit somewhere else close it as off-topic "Cross posting is not allowed. The identical question already exists on XX.SE." If it is a better fit here comment on the question at the other site "Cross posting is not allowed. The identical question already exists on Expats.SE."
If the question has valuable answers on multiple sites ask the mods to migrate the question to Expats.SE and then the expat mods can merge the answers

The difference being that I do not think we should automatically give away content.
Comment: Indeed, we don't want to lose content. I was more thinking of the cases where it's already answered on travel I guess.  I wonder if there's a recommendation of whether you close the second (cross-posted) question or the one that it fits better on? Otherwise travel.se peeps may be upset at us voting to close crossposted questions? They might not, just thinking out load.

Cross-posting from Travel


Is there a "successor" metric in topology?

Question:
Is there a "next" or "successor" metric in topology?

Following on from this question (the answer to which turned out to be a little more complicated than I expected, and seems to have created a certain amount of disagreement!), asking what is the boundary of a sequence of integers in the space $\mathbb{N}$, I was naturally intrigued to find out if there's a metric which says that two points are "close" if they are next to each other, i.e. one's an immediate successor of the other or there's no other point in-between.
The motivation behind this is that even the metrics and topological spaces which make no reference to $\mathbb{R}$, $\mathbb{Q}$ or $\mathbb{Z}_p$ etc., still seem to have the in-built assumption that there's a void between any two integers, an assumption seemingly without basis in the circumstances, and this seems to make the topological definition of the boundaries of a sequence of integers counterintuitive.
If we had a metric which said that only immediate successor was "in the neighborhood", or alternatively the restrict the metric to integer values: $\lvert a-b\rvert\in\mathbb{N}_{>0}$ then surely first and last elements of such a sequence could be defined as the boundary of a closed set and the integers one greater and one less than those as the boundaries of an open set.
This would seem to be a natural way to describe the topology of a discrete sequence of integers, or am I missing something?  Is there some clear advantage to the way it's done?
Comment: To restrict the metric to integer values, all you need to do is take $d(a,b)=|a-b|$ as usual, but let the set component of the metric space be the natural numbers, so that the metric space is $(\mathbb N,d)$. Then the only elements are integers, and there is no "in between", and so a neighborhood would consist of a sequence of integers.
Comment: Can you formulate the question more precisely? Like: Given a set $S$ with [some structure], does there necessarily exist a metric $d$ having the property that for all $x,y\in S$, we have [some condition on $d(x,y)$] if and only if [some condition on $x,y$ in the originally provided structure]?
Comment: You have a huge misunderstanding on the role of neighborhoods to define a topology and therefore to define boundary. Then you are trying to unify the vague understanding you have one that with ideas that you probably have seen when computing boundary of intervals in $\mathbb{R}$.
Comment: @ChrisCulter define the metric space $(\mathbb{N},d)$ with the metric $d(a,b)=\lvert a-b\rvert$. In this topology what is the boundary of the closed set $\{3,4,5\}$, and what about the same set viewed as an open set? Is there a valid reason why this apparently more intuitive definition of the topological boundaries of a sequence of integers is not used?
Comment: @Hellen what is my apparent misunderstanding?
Answer: Succinct definition of boundary starting from open sets:
Let $X$ be a set and its topology is just a collection $T\subset P(X)$ of some of its subsets that are going to be called open. The collection is required to have some properties which you can check in Wikipedia's article for topology.
The set $X$ with the collection $T$ is called a topological space.
Examples:

$X=\mathbb{R}$ and $T$ consist of the sets that can be obtained by making arbitrary unions of intervals of the form $(a,b)$.
$X=\mathbb{N}$ and $T$ consists of all possible subsets of $X$.
$X=\{3,4,5\}$ and $T$ consists of all possible subsets of $X$.

Interior: Given a topological space $X$ with topology $T$ and given a subset $A\subset X$, the interior of $A$ is the union of all elements of $T$ that are subsets of $A$.
Example:

The interior of $[a,b)$ in the topological space (1) is $(a,b)$.
The interior of $\{3,4,5\}$ in the topological space (2) is $\{3,4,5\}$.

Closure: Given a topological space $X$ with topology $T$ and given a subset $A\subset X$, the closure of $A$ is the complement of the union of all elements of $T$ that are completely outside of $A$.
Example:

The closure of the example (4) is $[a,b]$
The closure of the example (5) is $\{3,4,5\}$

Boundary: Given a topological space $X$ with topology $T$ and given a subset $A\subset X$, the boundary of $A$ is the difference of its closure minus its interior.
Example:

The boundary of example (4) is $\{a,b\}$
The boundary of example (5) is empty

The case of boundary of intervals in $\mathbb{R}$
Given an finite interval that includes or not its extreme points ($A=(a,b)$, $[a,b)$, $(a,b]$, or $[a,b]$) it is always the case that its boundary is the set of its extreme points.
Observe that the interior is the interval excluding its extreme points $(a,b)$. This is an element of the topology (see example 1) and we cannot fit any more intervals without extreme points inside $A$.
The closure is always $[a,b]$. Observe that in the complement of $A$ we can fit the intervals $(b,+\infty)$ and $(-\infty,a)$. Any other is inside those two. The complement of $(-\infty,a)\cup(b,+\infty)$ is $[a,b]$, and that is the closure.
Finally the boundary is closure $[a,b]$ minus interior $(a,b)$. That is $\{a,b\}$.

Topology from metric
Given a set $X$ and a metric $d$ on it. One can define a topology $T$ to consist of arbitrary unions of balls $B(a,r)=\{x\in X:\ d(a,x)<r\}$.
Examples:

The usual topology in $\mathbb{R}$ is of this form. Observe that the intervals $(a,b)$ are just the balls $B(\frac{a+b}{2},\frac{b-a}{2})$.

Impossibility of a topology on $\mathbb{N}$ such that the boundary of finite intervals consists of its extreme points
Assume we want to put a topology on $\mathbb{N}$ such that for every finite interval (finitely many consecutive integers) the boundary is its extreme points.
If the boundary of $A=\{a,a+1,a+2,...,a+n\}$ ought to be $\{a,a+n\}$. Then its interior would have to be $\{a+1,a+2,...,a+n-1\}$. Since $a$ and $n$ were arbitrary, that means (taking $n=1$) that all sets of the form $\{a\}$ are open (elements of the topology). By a property required for topologies, which you are supposed to read, this means that all subsets are open.
But if all subsets are open, then $A$ is open. Therefore, the interior of $A$ would have to be $A$ and its complement would have to be $A$ as well. This causes that the boundary is empty.
Thereofore, there is no such topology as we wanted. In particular, there is no such topology defined by a metric.
Answer: Topologically, in the usual metric, every subset of $\mathbb N$ has an empty boundary because every subset is open. This is not really a useful concept in $\mathbb N$.
To say the $\{3,4,5\}$ has boundary $\{3,5\}$ could perhaps be interpreted order-theoretically. The set is an interval, and what you call the boundary is its set of endpoints. Every subset of $\mathbb N$ (or any totally ordered set) is a union of intervals, though possibly not in an interesting way (the intervals could all be singletons). A boundary in your sense could be the set of endpoints of maximal intervals in the subset.
Comment: Thanks. The metric I had in mind would give the more than 2 numbers for a discontinuous sequence of integers.


Define $f(x)=x^3$ for all $x$. Verify the the $\epsilon - \delta$ criterion at each point $x_0$.

Question: Following Clayton's advice, for $\epsilon>0$, we must find a $\delta>0$ such that $|x^3-x_0^3|<\epsilon$ if $|x-x_0|<\delta$.
$|x^3-x_0^3|=|x-x_0||x^2+x_0x+x_0^2|<\epsilon$
I'm still working though.
Comment: Go back to what the $\epsilon-\delta$ actually is and show us what you know and what you have tried.
Answer: Hint: A standard technique to prove something for all $x\in\Bbb R$ is to first let it be arbitrary; i.e., let $x_0\in\Bbb R$. Prove the function is continuous at $x_0$ and then argue since $x_0$ was arbitrary, it must be true for every $x\in\Bbb R$.
Answer: Pick some $x_0$. Then try to bound $|f(x)-f(x_0)| = |x^3-x_0^3|$.
Note that since $x_0$ is a zero of the polynomial $x \mapsto x^3-x_0^3$, we must have  $(x-x_0)$ as a divisor of $x^3-x_0^3$.  That is, you can write $x^3-x_0^3=(x-x_0)p(x)$ for some polynomial $p$.
This should help in obtaining the required bounds.
Comment: But how do I find the bounds now that I'm not close to a single point (usually I pick an interval around the point of interest and use the max to create an upper bound for the inequality)?
Comment: You are close to a single point $x_0$. When you obtain a formula for $\delta$, it must have $x_0$ in there, so while you do not have an actual number, you have an expression involving $x_0$. For example, if I have an expression $x^2$ and I stipulate that $|x-x_0|<1$, then I can state that $x^2 \le (|x_0|+1)^2$, that is $x^2$ is bounded above by a 'known' quantity (even though $x_0$ is an arbitrary number).
Answer: Hint: Note that $$x^3-x_0^3=(x-x_0)(x^2+xx_0+x_0^2)$$ and $$\begin{align}x^2+xx_0+x_0^2 &= x^2-2xx_0+x_0^2+3xx_0\\ &= (x-x_0)^2+3xx_0\\ &= (x-x_0)^2+3xx_0-3x_0^2+3x_0^2\\ &= (x-x_0)^2+3x_0(x-x_0)+3x_0^2.\end{align}$$ Use these, together with triangle inequality, to rewrite $|x^3-x_0^3|$ in terms of $|x_0|$ and $|x-x_0|,$ and your choice of $\delta$ (given $\epsilon$) should become clearer.
Comment: I just end up with $|x^3-x_0^3|\le |x-x_0|(|(x-x_0)^2|+3|x_0(x-x_0)|+3|x_0^2|)<\epsilon$. I'm not sure how I'm supposed to come up with a $\delta$.
Comment: If you rewrite it as $$|x-x_0|\bigl(|x-x_0|^2+3|x_0||x-x_0|+3|x_0|^2\bigr),\tag{1}$$ then for any $c>0,$ if we have $|x-x_0|<\min\{1,c\},$ it follows that the quantity in $(1)$ is less than or equal to $$c\bigl(1+3|x_0|+3|x_0|^2\bigr).\tag{2}$$ By choosing a small enough $c$ so that the quantity in $(2)$ is less than $\epsilon$, then all that is left is to put $\delta=\min\{1,c\},$ and we're done. It's a bit of a slick trick that often comes in handy. Can you find an appropriate $c$?


How can I update the value of a specific field of my table for all rows?

Question: I am pretty new in SQL and expecially in Oracle DB and I have some doubt about how to update a specific single field values of all records of a table.
So, int an Oracle DB, I have a very simple table named PROJECT_INFO_STATUS that have the following form:
ID  STATUS
-------------
0   Closed
1   Active
2   Testing
3   Starting

As you can see in the previous snippet this table have only 2 fields: an ID (a NUMBER) and a STATUS (a VARCHAR).
What can I do to update all the rows so that the ID value is the old ID value + 1.
For example the ID value of the first row (STATUS=Closed) have to be 1 (and not 0). The ID value of the second row (**STATUS=Active) have to be 2 (and not 1). And so on.
How can I do to obtain this behavior?
Comment: is that id is primary key or reference to another table ?
Answer: Simply set the column value to itself plus one:
update project_info_status set id = id + 1;

select * from project_info_status;

        ID STATUS
---------- ----------
         1 Closed
         2 Active
         3 Testing
         4 Started

If the ID value is used as a foreign key in another table then you would need to update all of the values in that table as well, and if it's controlled by a referential integrity constraint (as it should be) then you'd need to disable the constraint while you update all related tables, and re-enable the constraint once the data is consistent again. Unless the constraint is defined as deferrable, in which case you can update both tables in the same transaction without disabling the constraint.
But if it is a key then its actual value should be irrelevant, and you shouldn't ever really need up modify a synthetic primary key value.
Answer: update PROJECT_INFO_STATUS
set ID = ID +1

you can directly add column value if it is not PK or FK
Answer: you should use update command
UPDATE mytable  SET new_column = <expr containing old_column>
then you can perform sum in the table query


Bootstrap Datepicker com CodeIgniter

Question: Boa noite turma,
Estou em um projeto PHP no CodeIgniter, onde já estou usando o Bootstrap e Morris.js (gráficos).
Preciso implementar o Datepicker agora, e fazendo da mesma forma que já havia funcionado em um teste sem o CodeIgniter não está funcionando. Alguém pode me dar uma luz?
Já linkei o css e o js, e nada. Talvez eu esteja fazendo errado. Enfim, se alguém puder me ajudar, segue a forma que estou fazendo:
No head

<link href="<?php echo base_url(); ?>assets/bootstrap/css/bootstrap.min.css" rel="stylesheet">

<link href="<?php echo base_url(); ?>assets/bootstrap/css/sb-admin.css" rel="stylesheet">

<link href="<?php echo base_url(); ?>assets/bootstrap/css/plugins/datepicker.css" rel="stylesheet">

<link href="<?php echo base_url(); ?>assets/bootstrap/css/plugins/morris.css" rel="stylesheet">

<link href="<?php echo base_url(); ?>assets/bootstrap/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

No body

E esse é o datepicker-data.js
$(function(){
        $('.datepicker').datepicker({
                autoclose: true,
        todayHighlight: true
        })
});

Chamei assim no form:
<form>

                    Data:

                            <input type="text" class="form-control datepicker" id="data">

                    Turma:
                    <select class="form-control">
                        <option>Turma 1</option>
                        <option>Turma 2</option>
                        <option>Turma 3</option>
                    </select>

            </form>

Answer: Matheus, o seu código do arquivo datepicker-data.js não está funcional, substitui por este trecho (comentado para que você entenda as modificações) e testa por favor, pois não consigo acessar seus includes locais para fazê-lo.
Segue:
/* $(document).ready somente é executado quando a página está carregada,
   do contrário o código javascript pode ser executado antes dos includes
   do jQuery e Datepicker. */
$(document).ready(function(){
    $('.datepicker').datepicker({
            autoclose: true,
    todayHighlight: true
    }); //faltava um ponto e vírgula aqui.
});

Espero ter ajudado.
Comment: Valeu, Bruno!
Muito obrigado!

Bootstrap Datepicker com CodeIgniter


Node.js Error: Unexpected server response: 301 - Running a Node.js Websocket server on Namecheap Webhost

Question: I'm trying to setup a Node.js Websocket server over at my webhost (Namecheap). However, I am getting this error:
    events.js:292
      throw er; // Unhandled 'error' event
      ^

Error: Unexpected server response: 301
    at ClientRequest.<anonymous> (D:\****\node_modules\ws\lib\websocket.js:576:7)
    at ClientRequest.emit (events.js:315:20)
    at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:596:27)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:119:17)
    at TLSSocket.socketOnData (_http_client.js:469:22)
    at TLSSocket.emit (events.js:315:20)
    at addChunk (_stream_readable.js:295:12)
    at readableAddChunk (_stream_readable.js:271:9)
    at TLSSocket.Readable.push (_stream_readable.js:212:10)
    at TLSWrap.onStreamRead (internal/stream_base_commons.js:186:23)
Emitted 'error' event on WebSocket instance at:
    at abortHandshake (D:\****\node_modules\ws\lib\websocket.js:694:15)
    at ClientRequest.<anonymous> (D:\****\node_modules\ws\lib\websocket.js:576:7)
    [... lines matching original stack trace ...]
    at TLSSocket.Readable.push (_stream_readable.js:212:10)

The code for the client and server came from here:

https://github.com/websockets/ws#Simple server
https://github.com/websockets/ws#sending-and-receiving-text-data

with ws://www.host.com/path changed to ws://<mydomainname>/<dir1>/<dir2>
Both client and server code runs properly when run locally. Http related code runs properly when used on my webhost. I am trying to get the client code to run locally and connect via websockets to my server hosted at Namecheap.
I suspect something related to the server is preventing connection. I'd ask support but I doubt if they can resolve this. Maybe there's a locked feature or something? Is there something else I could have missed?
Comment: Well, it turns out this happens if I leave out "www" in the URL the client is connecting to. Now, that I have included it, I'm getting an Error 101.
Answer: Websockets cannot work on Namecheap's hosted servers. Their incoming ports are blocked and cannot be opened for security reasons per their customer's support.
If anyone is looking for a solution just in case, try out a Heroku free account.
Comment: I contacted support last week and they opened ports 8082 and 17775 for me.


How to prevent the Enter key to submit form

Question: I have a input field (type=text) on my page. I use Bootstrap and to style the field I use next html code:
<form fole="form">

        <input type="text" class="form-control" id="add-bookmark" value placeholder="Enter URL">

</form>

In the meteor application I have event handler:
Template.new_bookmark.events({

    // add new bookmark
    'keyup #add-bookmark' : function(e,t) {
      console.log(e.which);
      if(e.which === 13)
      {

When I press any button in the input field I get the key code in the console (as I wish).  But if I press the Enter-key the console log have nothing and my page is reloaded.
Looks like the reason  of my problem is in the form-tag.  If I remove it all works fine.  What do I need to do ?  Remove the form-tag or prevent the page will be reloaded when I hit the Enter-key ?  How can I do it if the answer is second ?
Comment: check e.preventDefault(); this will be useful.
Comment: If you would allow me to ask, why are u using form if you don't want it to submit?
Comment: If you don't want a form's behaviour, don't use a form.
Comment: @Joraid, I am not sure I need a form.  The examples on the Bootstrap site I have seen use form tag.  I think I can not use form tag. Thanks.
Comment: No problem. I assume you want to send the user input to the server at some point, so you either use Form or make an Ajax request if that is the case.
Answer: The page is not being 'reloaded' it's being submitted and that is the default behaviour when you focus on the form (selecting the input field in the form) and hit enter. How to prevent that, well, add this to your form decliration:
<form name="myForm" onsubmit="return false;">

Or if you want to validate the input field before submitting, then you can use a seperate function to do the validation for you:
<form name="myForm" onsubmit="return validate();">

function validate()
{
  //pur you validation code here
  return true;
}

As for the key log, actually you will get Enter in your log, but the thing is, when you hit Enter the first action your brwoser will do is to submit the form and therefore will start send a new http reqeust and start transmitting info from the server. When that happens, your browser plugins (Firebug, console etc) will be stoped for a moment and will wait until the new page is loaded. I'm not sure about how much that is accurate, but it's how I understand it.
Comment: My CODE formatting was wron and got that line being hidden. I just fixed it now, it's visible :)


Cálculo automático de botões

Question: Estou com um projeto de cálculo de itens onde ao clicar nos botões + ou - tenho um campo que faz os cálculos automaticamente.
O problema é que dessa forma eu tenho que criar uma variável para cada item e no total são mais de 40 itens, aí fica inviável criar esse tanto de variáveis fora também fazer os cálculos.
Queria pedir a ajuda de vocês para avaliar o código e ver se conseguem uma logica mais viável.

function up() {

var valor1 = parseInt(document.querySelector('.valor1').value,10);
var valor2 = parseInt(document.querySelector('.valor2').value,10);
var valor3 = parseInt(document.querySelector('.valor3').value,10);
document.querySelector('.resultado').innerHTML = (((valor1 + valor2 + valor3)+1)*0.30).toFixed(2);

}

function down() {

var valor1 = parseInt(document.querySelector('.valor1').value,10);
var valor2 = parseInt(document.querySelector('.valor2').value,10);
var valor3 = parseInt(document.querySelector('.valor3').value,10);
document.querySelector('.resultado').innerHTML = (((valor1 + valor2 + valor3)-1)*0.30).toFixed(2);

}
input[type="number"] {
    -webkit-appearance: textfield;
    -moz-appearance: textfield;
    appearance: textfield;
}

    input[type=number]::-webkit-inner-spin-button,
    input[type=number]::-webkit-outer-spin-button {
    -webkit-appearance: none;
}

    .number-input {
    border: 1px solid #ddd;
    display: inline-flex;
}

    .number-input button.plus {
    background-color: #2eb82e ;
}

    .number-input button.down {
    background-color: gainsboro ;
}

    .number-input,
    .number-input * {
    box-sizing: border-box;
}

    .number-input button {
    outline:none;
    -webkit-appearance: none;
    background-color: transparent;
    border: none;
    align-items: center;
    justify-content: center;
    width: 1rem;
    height: 1rem;
    cursor: pointer;
    margin: 0;
    position: relative;
}

    .number-input button:before,
    .number-input button:after {
    display: inline-block;
    position: absolute;
    content: '';
    width: 0.5rem;
    height: 1px;
    background-color: #212121;
    transform: translate(-50%, -50%);
}

    .number-input button.plus:after {
    transform: translate(-50%, -50%) rotate(90deg);
}

    .number-input input[type=number] {
    font-family: sans-serif;
    max-width: 2rem;
    padding: .1rem;
    border: solid #ddd;
    border-width: 0 1.5px;
    font-size: 1rem;
    height: 1rem;
    text-align: center;
}

        <button onclick="this.parentNode.querySelector('input[type=number]').stepDown(down())" class= "down"></button>
        <input class="valor1" min="0" name="valor1" value="0" type="number">
        <button onclick="this.parentNode.querySelector('input[type=number]').stepUp(up())" class="plus"></button>

        <button onclick="this.parentNode.querySelector('input[type=number]').stepDown(down())" class= "down"></button>
        <input class="valor2" min="0" name="valor2" value="0" type="number">
        <button onclick="this.parentNode.querySelector('input[type=number]').stepUp(up())" class="plus"></button>

        <button onclick="this.parentNode.querySelector('input[type=number]').stepDown(down())" class= "down"></button>
        <input class="valor3" min="0" name="valor3" value="0" type="number">
        <button onclick="this.parentNode.querySelector('input[type=number]').stepUp(up())" class="plus"></button>

0

Answer: Você pode atribuir uma mesma classe para todos os inputs, selecionar eles com querySelectorAll e então passar um por um via forEach para fazer o cálculo:
const elements = document.querySelectorAll('.valor'); // classe utilizada para os inputs
var soma = 0;
Array.from(elements).forEach((element, index) => {
   soma += parseInt(element.value, 10);
});

Desta forma, sempre que quiser adicionar um novo, só precisa lembrar de colocar a classe que escolheu.
Também reparei que suas duas funções up()e down() fazem praticamente a mesma coisa, mudando apenas o valor -1 ou +1. Para otimizar as coisas, é sempre bom reaproveitar um código que você irá utilizar muitas vezes, tornando mais fácil manutenção, leitura, etc. Segue uma sugestão:

function calc_elementos() {
      const elements = document.querySelectorAll('.valor');
      var soma = 0;
      Array.from(elements).forEach((element, index) => {
        soma += parseInt(element.value, 10);
      });
      return soma;
    }
    function calculo(num){
      document.querySelector('.resultado').innerHTML = (((calc_elementos())+num)*0.30).toFixed(2);
    }
input[type="number"] {
    -webkit-appearance: textfield;
    -moz-appearance: textfield;
    appearance: textfield;
}

    input[type=number]::-webkit-inner-spin-button,
    input[type=number]::-webkit-outer-spin-button {
    -webkit-appearance: none;
}

    .number-input {
    border: 1px solid #ddd;
    display: inline-flex;
}

    .number-input button.plus {
    background-color: #2eb82e ;
}

    .number-input button.down {
    background-color: gainsboro ;
}

    .number-input,
    .number-input * {
    box-sizing: border-box;
}

    .number-input button {
    outline:none;
    -webkit-appearance: none;
    background-color: transparent;
    border: none;
    align-items: center;
    justify-content: center;
    width: 1rem;
    height: 1rem;
    cursor: pointer;
    margin: 0;
    position: relative;
}

    .number-input button:before,
    .number-input button:after {
    display: inline-block;
    position: absolute;
    content: '';
    width: 0.5rem;
    height: 1px;
    background-color: #212121;
    transform: translate(-50%, -50%);
}

    .number-input button.plus:after {
    transform: translate(-50%, -50%) rotate(90deg);
}

    .number-input input[type=number] {
    font-family: sans-serif;
    max-width: 2rem;
    padding: .1rem;
    border: solid #ddd;
    border-width: 0 1.5px;
    font-size: 1rem;
    height: 1rem;
    text-align: center;
}

              <button onclick="this.parentNode.querySelector('input[type=number]').stepDown(calculo(-1))" class= "down"></button>
              <input class="valor" min="0" name="valor1" value="0" type="number">
              <button onclick="this.parentNode.querySelector('input[type=number]').stepUp(calculo(1))" class="plus"></button>

              <button onclick="this.parentNode.querySelector('input[type=number]').stepDown(calculo(-1))" class= "down"></button>
              <input class="valor" min="0" name="valor2" value="0" type="number">
              <button onclick="this.parentNode.querySelector('input[type=number]').stepUp(calculo(1))" class="plus"></button>

              <button onclick="this.parentNode.querySelector('input[type=number]').stepDown(calculo(-1))" class= "down"></button>
              <input class="valor" min="0" name="valor3" value="0" type="number">
              <button onclick="this.parentNode.querySelector('input[type=number]').stepUp(calculo(1))" class="plus"></button>

0

Comment: Nossa show de bola, realmente ficou muito melhor, obrigado pela resposta.
Coloquei as suas correções no código completo funcionou 100% porém me surgiu uma nova dificuldade, vou explicar um pouco a finalidade de tudo isso, basicamente esses botões irão simular um calculador de metros cúbicos de moveis, onde a soma de todos os moveis adicionados me dará o cálculo total das medidas.
Comment: A dificuldade agora é que tenho varias medidas e não estou conseguindo fazer a soma entre eles, no exemplo usamos o valor 0.30, mas como eu faria para o input 1 adicionar 0.30 a cada clique e o 2 adicionar 0.60 por exemplo e assim por diante ? pensei em separar por classe o grupo de valores iguais e aplicar o valor no calculo dessa classe, tentei com if e else if, duas funções chamando classes diferentes e no fim somando os valores mas sem sucesso.
Comment: Dá pra fazer de várias formas, precisa mudar um pouquinho as coisas. Você pode adicionar um segundo parâmetro de valor para a função que faz o cálculo, então ela recebe esse parâmetro e calcula dentro da função mesmo. Por exemplo: `calculo(1, 0.6)`. Aí passa para o calc_elementos que recebe esse mesmo número e faz a soma.
Comment: Passei os valores como parâmetro na função do html, chamei esses dois parâmetros na função do js ficando assim calculo(num, valor) ai depois usei esses dois parâmetros no calc_elementos ficando assim ((calc_elementos() + num) * valor).toFixed(2). Até a adição do terceiro item funciona, a partir dai o calculo não funciona mais, conforme vou adicionando tem itens que soma valores totalmente fora e tem itens que subtrair mesmo eu clicando em +...
Comment: Acho que identifiquei onde esta o problema, acredito que seja no calculo com a função calc_elementos -> `((calc_elementos() + num) * valor)`  fui fazendo alguns testes isolados acredito que nesse caso as quantidades estão sendo mantidas porém ao adicionar um novo item ela pega a quantidade que ja existe multiplica pelo novo valor retornando um calculo divergente do esperado, que no caso seria a multiplicação isolada da quantidade de cada item e depois pegaria todos esses totais e somaria para apresentar a medida total de todos os itens.
Comment: No caso agora o ideal seria na verdade fecharmos essa questão para você abrir outra, já que via comentário é muito ruim de entender e solucionar o problema e considerando que o problema inicial foi resolvido.
Comment: Perfeito, para encerrar preciso fazer algo? aproveitando muito obrigado pela ajuda, adiantou bastante o projeto que estou desenvolvendo.
Comment: De nada ^^ Apenas marque a minha como resposta "aceita" caso tenha ajudado e se ainda precisar poste a nova pergunta

Cálculo automático de botões


SQL 2000 Logs disk drive bust

Question: We;ve had a disk go on our SQL server (2000) that contained all the log files, so we replaced the drive (no raid config so data lost) and now when trying to connect to Enterprise manager we cant, just getting the general connection failed message. The service seems to start ok?
Any ideas? I didn't think the log files going would screw it up this much?
Thanks,
John
Answer: Are you sure the service started ok? How are you checking?
If the databases were not cleanly shutdown then SQL Server won't automatically recreate log files as there is information in the missing log files that is required to properly run crash recovery on those databases. (See my article in TechNet Magazine Understanding Logging and Recovery in SQL Server).
Do you have backups of the databases? If not you may be looking at having to perform an undocumented and unsupported transaction log rebuild on some of the databases to make them accessible again - which usually leads to corruption (because active transactions didn't get a chance to roll-back properly), which you fix using DBCC CHECKDB.
Thanks
Answer: I think there is enough control with the query analyzer to log in and re-tell the database where the log files are.
Otherwise, you may have to cycle the SQL server service to re-create the log files and start writing to them again.

SQL 2000 Logs disk drive bust


Submit Button enable and disable in Javascript

Question: I would like to create a form with text box and submit button using JavaScript. The button should enable only when i enter a total 10 digit phone number in to text box.
Comment: Have you tried anything to accomplish what you want?
Comment: that's an honourable task, I hope you don't have any problem with it, but if you do, feel free to share your non-working code and I'm sure one of the nice people on SO will attempt to explain what you did wrong. Have a nice day
Answer: Very simple solution: https://jsfiddle.net/tkx3dcna/
HTML
<input id="phone" type="text">
<button id="btn" disabled>Send</button>

JS
var btn=document.getElementById("btn");
var phone=document.getElementById("phone");
phone.onkeyup=function(){
    btn.disabled=!(phone.value.length===10);
};

Comment: PS: there is `!==` :-)
Answer: Here you go, though Madara was right, you should try these things out yourself, no?

var num = document.querySelector("input[type='number']"),
  submit = document.querySelector("input[type='submit']");

num.onkeyup = function(event) {
  var val = this.value + '';
  if (val.length === 10) {
    submit.disabled = false;
  } else {
    submit.disabled = true;
  }
};

// Use below method instead, submit button shows immediately after the numbers are a length of 10
/*
function areYouReady() {
  var val = num.value + '';
  if (val.length === 10) {
    isReady = true;
    submit.disabled = false;
  } else {
    isReady = true;
    submit.disabled = true;
  }
  requestAnimationFrame( areYouReady );
}
areYouReady();
*/
<form>
  <input type="number" maxlength="10" required>
  <input type="submit" onsubmit="" disabled="true">
</form>
Comment: `requestAnimationFrame( areYouReady );` --- this is terribly inefficient. You better attach a listener to the input keyup events.
Comment: @zerkms read the comments. That was the first thing I did. Run the code with the listener uncommented and you'll understand why I used requestAnimationFrame
Comment: I have no idea how your commented code is relevant to what I suggested. Check the other answer if you're not sure how to deal with keyup.
Comment: @zerkms look at the code, it would listen for an onchange event. But that behaved weird. Did you even run the snippet with the commented code uncommented -_-
Comment: Again, I have no idea how my advice on using `onkeyup` event is relevant to your code with `onchange`. `.onchange` is not a solution either.
Comment: Ahh, keyup event I see, misread. I see, I'll edit the code


Why confidence interval is important when point estimator is close to zero?

Question: When the point estimator is relatively small numbers, a confidence interval is likely to contain zero, be fairly wide and include both positive and negative values.  Basically, when CI contains zero we would say that we cannot reject null hypothesis, but is there another conclusions that we can get from CI? In that case what additional information (interpretation) can provide us the confidence interval?
Comment: Search our site for [confidence interval](http://stats.stackexchange.com/questions/tagged/confidence-interval?sort=votes&pageSize=50) to obtain a full answer.
Comment: It rather depends on your hypothesis.  if you were testing a product for safety, you would want to ensure a 0% fatality rate (or to put it another way that it was 100% safe).  In this case you would be happy with a confidence interval that includes zero and would ignore the negative side of the confidence interval.
Answer: The main purpose is to inform you about out confidence in the value of the estimator. If confidence interval is very wide, it means that we have little confidence in the value. If the value is small, the we can't even say whether it's zero or not. That's it.


Como parar o $(window).scroll num consulta sob demanda

Question: Faço uma consulta sob demanda na minha página, eu trago as informações do banco enquanto o usuário usa o scroll.
$(window).scroll(function(evento){
    evento.preventDefault();
    var init = $(".canal .lista ul#dem").length;
    carregar(init + 1, init + 2, 'lista_load.asp');
});

O problema é q não sei como parar o scroll, eu faço uma verificação, fiz uma validação para que quando chegasse no fim dos itens me mostrasse um alert, e funcionou bem, queria nesse ponto que a função do scroll parasse de trazer s itens, mas não sei como fazer, alguém pode me ajudar?
Comment: já tentou o evento.stopImmediatePropagation() ?
Answer: O evento scroll não dá para cancelar. Isso é muito claro na especificação da W3C.
As únicas maneiras que sei para contornar isso são:

overflow: hidden;
um oscultador de evento que força a posição do scroll a não mudar

A primeira opção, de dar overflow: hidden; no body é muito usada em casos onde o scroll não deve acontecer. No teu caso queres que o scroll funcione até dada altura e depois pare de funcionar. Para usar esta ideia tens de ler a posição do scroll e aplicar o overflow: hidden; no body ou elemento pai do outro.
Exemplo:
CSS
div {
    height: 4000px;
    border: 1px solid #ccf;
}
.pararScroll {
    overflow: hidden;
    background-color: #eee;
}

JS
window.addEventListener('scroll', function (e) {
    var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    if (scrollTop > 1000) document.body.classList.add('pararScroll');
});

jsFiddle: http://jsfiddle.net/51p1tq4u/
A segunda opção precisa que guardes o valor da ultima posição do scroll. Assim a cada evento scroll, voltas a dizer que a posição deve ser a anterior a esse evento scroll.
Exemplo:
var lastScroll;
window.addEventListener('scroll', function (e) {
    if (lastScroll) return window.scrollTo(0, lastScroll);

    var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    if (scrollTop > 1000) lastScroll = scrollTop;
});

jsFiddle: http://jsfiddle.net/51p1tq4u/1/
E se quiseres voltar a ativar o scroll só tens de mudar o valor de lastScroll para um valor que tenha valor booleano false.


How to let a user change their own username?

Question: I can't seem to figure out how to let users change their own username. I'm running Aegir with about 10 Open Atrium sites. With permissions I've checked "change own username" for the master Aegir site, as well as the Open Atrium sites. For giggles, I enabled every role to "change own username"..
But when I try to change my username in OpenAtrium and click save, it confirms "changes have been saved", but the username doesn't actually change.  This has ballooned into a huge issue for us.  I'm hoping there is some obvious dumb thing I need to do.  Thoughts?
Comment: That's done in permissions. In Drupal 7, go to admin/people/permissions and look under User: Change own username.
Comment: I realize this should be obvious
Comment: Here you can see I "change own username" permission checked off for ALL Aegir and ALL Open Atrum roles. http://screencast.com/t/iLheAUAYJAvM
Comment: However when I change the username on my profile page and click save it doesn't change the username -- but it doesn't throw an error either. Just says "Changes have been saved."  Nope
Comment: Sorry. I guess I read/answered too quickly... :-(
Comment: No problem. I'm wondering if this is being caused by a drupal site (Open Atrium) is managed by a Aegir (Master drupal site)? Grasping at straws at this point...
Comment: Perhaps you should post your question directly here? http://community.aegirproject.org/discussion
Answer: Changing a username inside a hosted site is completely up to the OpenAtrium Drupal installation.
Aegir does not usually interact with this.
I just verified that it works OK on a clean Aegir 3 install with a standard Drupal site.
So @Bisonbleu's comment seems correct:

That's done in permissions. In Drupal 7, go to admin/people/permissions and look under User: Change own username.


ezPublish - fetch objects published between dates

Question: I need to fetch articles (or objects) published between "now" and "a month before". Code looks like this:
{def $date = currentdate()}
{def $day = currentdate()|datetime( 'custom', '%d' )}
{def $month = currentdate()|datetime( 'custom', '%m' )}
{def $year = currentdate()|datetime( 'custom', '%Y' )}
{def $fromDate = maketime(0,0,0,$month|dec(), $day, $year)}

{def $items = fetch(content, list, hash(
    'parent_node_id', 10,
    'attribute_filter', array('and',
                                    array('article/publish_date', '<=', $data),
                                    array('article/publish_date', '>', $fromDate),
                                    array( 'priority', '>=', 0 )),
    'class_filter_type',    'include',
    'class_filter_array',   array('article')
))}

Unfortunately, nothing comes out. When I remove the $fromDate array from the fetch, it works.
Comment: which version of ezpublish are you using ?
Answer: In short, your template fetch code is inaccurate (either here or in your template).
The line, "array('article/publish_date', '<=', $data)," should be "array('article/publish_date', '<=', $date)," instead to fix the variable typo.
Also your date timestamp comparison logic (operator) usage is also incorrect (I think). It has been a while since I last did what you are doing but when I did it last I used the following logic instead.
{* Example: http://example/layout/set/content_statistics.csv/(startDate)/2010-07-14/(endDate)/2010-07-19/ *}
{def $articles=false()}

{if and( is_set( $view_parameters.startDate ), is_set( $view_parameters.endDate ) )}

{def $startDate=$view_parameters.startDate|explode("-")
$endDate=$view_parameters.endDate|explode("-")}

{def $startDateTimestamp=maketime(0,0,0,$startDate.1,$startDate.2,$startDate.0)
$endDateTimestamp=maketime(23,59,59,$endDate.1,$endDate.2,$endDate.0)}

{set $articles=fetch( 'content', 'list', hash(
     'parent_node_id', 77,
     'class_filter_type', 'include',
     'class_filter_array', array( 'article' ),
     'sort_by', array( 'published', false() ),
     'attribute_filter', array( array( 'published', '>=', $startDateTimestamp ),
                                array( 'published', '<', $endDateTimestamp ) )
 ) )}
{else}

{set $articles=fetch( 'content', 'list', hash(
     'parent_node_id', 77,
     'class_filter_type', 'include',
     'class_filter_array', array( 'article' ),
     'sort_by', array( 'published', false() ),
     'limit', 10000
 ) )}
{/if}

Notice that the attribute filter date timestamp comparison operators use a very different formula, re: '>=' '<' and I think this example will work better for you.
     'attribute_filter', array( array( 'published', '>=', $startDateTimestamp ),
                                array( 'published', '<', $endDateTimestamp ) )
 ) )}

I hope this helps!
Cheers,
Heath
Note: I borrowed the above example from eZpedia but was afraid to link here as I am unsure of the policy of linking to community documentation (even when it has the answer to the question being asked): http://www.ezpedia.org/en/solution/how_to_fetch_content_based_on_view_parameter_date_range


Botão de volta ao topo não está sobrepondo o footer

Question: Estou com o seguinte problema, criei um botão de volta ao topo, posicionei ele no canto inferior direito e dei um position:fixed nele. Estou fazendo uso da biblioteca jQuery. O problema ocorria quando a barra de rolagem chegava ao final, o botão acabava se escondendo por baixo do rodapé. A solução foi diminuir o tamanho do footer na distância que eu tinha posicionado o botão do topo da página. Gostaria que quando ele chegasse ao final, ele ficasse sobrepondo o footer.
Alguém fortalece ai rapazes!

.btn-up {
        width: 80px;
        height: 50px;
        position: fixed;
        top: 480px;
        margin-left: 1260px;
        font-family: tahoma, arial;
        font-size: 1.5em;
        text-height: 50px;
        color: #FFF;
        background-color: #666;
        border: 2px solid #333;
        border-radius: 5px;
        box-shadow: 2px 2px 15px #000;
}

.btn-up:hover {
        background-color: #DC143C;
        box-shadow: 2px 2px 15px #F00;
}

<button class="btn-up">Subir</button>

Comment: Adiciona no teu Button a propriedade z-index:1
Comment: valeu Bia era isso mesmo!
Answer: Acredito que esse link o ajude:

https://www.w3schools.com/cssref/pr_pos_z-index.asp

e esse exemplo retirado também do site acima o ajude a entender melhor, sugiro que altere o valor da propriedade z-index que está em -1 para 0, para ver o seu efeito, acredito que vai resolver o seu problema.
Comment: mudei para 0 e continuou da mesma maneira, fiz o que a @Bia Silva  sugeriu e deu certo. Porém vou ler o que me mandou


Ponteiro apontando para outro ponteiro, como usar o free() corretamente?

Question: Quando tenho um ponteiro apontando para outro ponteiro como:
int *ponteiro1 = malloc(sizeof(int));
int *ponteiro2;

*ponteiro1 = 5;

ponteiro2 = ponteiro1;
free(ponteiro2);

E utilizo o comando free(ponteiro2), então estou desalocando o ponteiro1? Se sim, devo depois fazer algum tratamento para o ponteiro2?
Answer: Vamos olhar o código:
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int *ponteiro1 = malloc(sizeof(int));
    *ponteiro1 = 5;
    int *ponteiro2 = ponteiro1;
    printf("%p == %p, %d == %d\n", (void *)ponteiro1, (void *)ponteiro2, *ponteiro1, *ponteiro2);
    free(ponteiro2);
    printf("%p == %p, %d == %d", (void *)ponteiro1, (void *)ponteiro2, *ponteiro1, *ponteiro2);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Aí mostra que as duas variáveis tem o mesmo valor, e esse valor é o ponteiro. Também vemos, obviamente, que o valor contido na memória alocada é o mesmo quando derreferenciamos o ponteiro e acessamos o objeto apontado, afinal se é o mesmo endereço nas variáveis então apontamos certamente para o mesmo objeto. Nem poderia ser diferente, em lugar algum o código criou 2 objetos.
Se você considerar que free() libera um endereço da memória quando ele é liberado nada mais naquele ponto deve ser usado. Da mesma forma que você alocou só uma vez deve liberar só uma vez. Não existem duas alocações. A atribuição de uma variável na outra não está criando uma nova alocação. Em C você tem que ser explícito em tudo.
Inclusive se você tentar liberar de novo terá um comportamento indefinido.
É importante notar que o valor da variável não é zerado, você não deveria tentar acessar esse endereço depois de um free().
Algumas pessoas gostam de zerar o valor da variável para evitar um acesso indevido não percebido. Se você zerar e tentar acessar depois provavelmente quebrará a aplicação que é melhor que funcionar por coincidência e em outro momento dar resultado errado sem aviso.
Se não ficou claro, o valor da variável que é do tipo ponteiro nunca é o valor do objeto, existem dois valores completamente distintos na memória, esse tipo provoca sempre uma indireção para acessar o real objeto.
Zerando valor do objeto
O que eu achei curioso é que após o free() o valor do objeto alocado nesse endereço foi considerado 0. Dá a impressão que a função free() zera o valor, mas isso não é para acontecer. É claro que o compilador é livre para fazer o que quiser, mas teria custo e C incentiva não colocar custos ocultos que podem não ser necessários. Em geral a simples liberação ainda permitirá o acesso ao valor do objeto se nada sobrescrevê-lo.
Pesquisando um pouco parece que há caso que a liberação da memória da aplicação pode liberar a memória para o sistema operacional. Isso ocorrendo o endereço não é liberado para acessar pela aplicação. Curiosamente não dá erro e só acessa um valor neutro. Fiquei de cabelo em pé porque provavelmente gera algum custo. Não quer dizer que seja isso, pode ser que haja mudança no valor mesmo, teria que pesquisar no compilador ou biblioteca dele para identificar o que ele faz.
Pode ser que acontece só em modo debug, o que eu não gosto da ideia porque muda a semântica do código, pode até ocultar um bug. Faria mais sentido porque nesse modo a performance não é problema, mas parece uma solução ruim.
Olhando o fonte da alocação pode ter ocorrido um meio termo:
struct malloc_chunk {

  INTERNAL_SIZE_T      prev_size;  /* Size of previous chunk (if free).  */
  INTERNAL_SIZE_T      size;       /* Size in bytes, including overhead. */

  struct malloc_chunk* fd;         /* double links -- used only if free. */
  struct malloc_chunk* bk;

  /* Only used for large blocks: pointer to next larger size.  */
  struct malloc_chunk* fd_nextsize; /* double links -- used only if free. */
  struct malloc_chunk* bk_nextsize;
};

Um bloco de alocação pode ter sobrescrito nessa situação o valor do objeto. Isso não quer dizer que ocorrerá sempre, mas aconteceu um caso que não liberar para o sistema operacional, mas teve um processamento de gerenciamento de memória interno que usou a memória dentro do free().
Aí eu fico pensando que até mesmo o printf() poderia, em tese, ter feito alguma coisa que sobrescreveu o valor enquanto ele estava processando a impressão. Não acho bom e acredito ser menos provável. Não lembro dessa função fazer uma alocação no heap.
Answer: Ao fazer ponteiro2 = ponteiro1, ponteiro2 não está  a apontar para ponteiro1, mas sim estão a compartilhar o mesmo endereço de memória já que você está a atribuir a ele o valor de ponteiro1 que é esse endereço de memória.
Portanto o valor de *ponteiro2 também é o mesmo 5 que você atribuiu à esse endereço de memória ao fazer *ponteiro1 = 5.
Ao fazer free (ponteiro2), você está a liberar o endereço de memória compartilhado pelos dois ponteiros. Neste momento, tanto ponteiro1 quanto ponteiro2 estão a apontar pra um endereço que não está mais reservado pra eles.
Agora ao tentar aceder à *ponteiro1 ou *ponteiro2, ocorrerá o erro de Segmentation fault - "erro que ocorre quando um programa tenta aceder (para leitura ou escrita) um endereço na memória RAM que está reservado para outro programa (ou o próprio sistema operativo) ou que não existe."
Resposta: Já não precisa fazer nada ao ponteiro1 nem ao ponteiro2, a menos que queira fazer ponteiro1 = NULL e ponteiro2 = NULL se quiser voltar a utilizar as variáveis mais tarde.
Comment: Mais sobre `segmentation fault`: https://pt.wikipedia.org/wiki/Falha_de_segmenta%C3%A7%C3%A3o
Answer:
Quando tenho um ponteiro apontando para outro ponteiro como:

int* ponteiro1 = malloc(sizeof(int));
int* ponteiro2;

*ponteiro1 = 5;

ponteiro2 = ponteiro1;
free(ponteiro2);

Você não tem um ponteiro apontando para outro ponteiro. ponteiro1 é int*, ponteiro2 é int* e você apenas fez os dois apontarem para o mesmo lugar.
isso seria "apontar para outro ponteiro":
int   valor = 42;
int*  p2    = &valor;
int** p3    = &p2;
printf(
    "Valor: %d ponteiro2 aponta para %d. int** p3 "
    "aponta para %d\n",
    valor, *p2, **p3);

E aqui p3 aponta para um int*. Esse trecho mostra
Valor: 42 ponteiro2 aponta para 42. int** p3 aponta para 42

E utilizo o comando free(ponteiro2), então estou desalocando o ponteiro1? Se sim, devo depois fazer algum tratamento para o ponteiro2

Não, não está. Não desaloca ponteiros, desaloca áreas de memória que se supõe previamente alocadas por uma chamada a malloc() ou calloc()
O "tratamento" que deve se acostumar a fazer é invalidar os dois ponteiros imediatamente. Ponteiros perdidos são uma das maiores causas de erro em C. Vou deixar um exemplo ao final.
sobre o código como postado
Nem todo programa vai ter 5 ou 25 linhas. Logo vão ter 2.500. Evite a todo custo deixar um ponteiro inválido ou em estado desconhecido. ao invés de
int* ponteiro1 = malloc(sizeof(int));
int* ponteiro2;

*ponteiro1 = 5;

ponteiro2 = ponteiro1;
free(ponteiro2);

prefira sempre
int* ponteiro1 = malloc(sizeof(int));
*ponteiro1     = 5;

int* ponteiro2 = ponteiro1;

printf(
    "\
Valor apontado por ponteiro1: %d\n\
Valor apontado por ponteiro2: %d\n\
    ",
    *ponteiro1, *ponteiro2);

free(ponteiro2);
ponteiro2 = ponteiro1 = NULL;

Que mostra
Valor apontado por ponteiro1: 5
Valor apontado por ponteiro2: 5

Assim iniciaiza ponteiro2 já na declaração e na linha seguinte ao free() invalida os dois ponteiros.
Exemplo
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
    int* ponteiro1 = malloc(sizeof(int));
    *ponteiro1     = 5;

    int* ponteiro2 = ponteiro1;

    printf(
        "\
    Valor apontado por ponteiro1: %d\n\
    Valor apontado por ponteiro2: %d\n\
",
        *ponteiro1, *ponteiro2);

    free(ponteiro2);
    ponteiro2 = ponteiro1 = NULL;

    int   valor = 42;
    int*  p2    = &valor;
    int** p3    = &p2;
    printf(
        "Valor: %d ponteiro2 aponta para %d. int** p3 "
        "aponta para %d\n",
        valor, *p2, **p3);
    return 0;
}

que mostra
Valor apontado por ponteiro1: 5
Valor apontado por ponteiro2: 5
Valor: 42 ponteiro2 aponta para 42. int** p3 aponta para 42


Alternatives to Nodequeue?

Question: Are there any other modules that can implement the same functionality as Nodequeues i.e, making a customized list of selected nodes? I think I might be having some problems which might be related to it's permissions (I'm not sure of it as I'm still novice at Drupal). Maybe it's because it is still in beta phase for D7, I don't know...
Answer: All about that matter here.
Current options are:

Outline Designer
Weight
Nodeorder
Nodequeue
DraggableViews
Flag Weights
Sortable Grid Views Plugin
JQGRID
Answer: You can use the flag module to do something similar, and if you combine it with Draggable views and Flag weights you can re-order them. Just define a flag for each node queue you want to use.
Answer: I have replaced NodeQueue usage with Entity Collection. It's both entity and storage backend agnostic, as well as plays well with exportability.
Comment: any idea on when there will be a release? THX!
Answer: I would also like to add Entityqueue to the list as well.

A rewrite of Nodequeue for Drupal 7 based on entities.
The Entityqueue module allows users to create queues of any entity
  type. Each queue is implemented as an Entityreference field, that can
  hold a single entity type.
For instance you can create a queue of:

Nodes
Users
Taxonomy Terms

Entityqueue provides Views integration, by adding an Entityqueue
  relationship to your view, and adding a sort for Entityqueue position.

Alternatives to Nodequeue?


Does varnish ignore first_byte_timeout for pipe requests?

Question: There is a note at https://www.varnish-cache.org/docs/3.0/reference/vcl.html that says

bereq.first_byte_timeout
     The time in seconds to wait for the
  first byte from the backend. Not available in pipe mode.

Does this mean that the first_byte_timeout is ignored for all piped requests to the backend?
Answer: That is correct.
As the documentation states about pipe:

pipe is only used when Varnish for some reason can't handle the pass.
  pipe reads the request, pushes in onty the backend only pushes bytes
  back and forth, with no other actions taken.

You won't even see the X-Varnish-headers appear in piped requests.


Dialogflow V2 and passing parameters in request body to webhook

Question: I am trying to pass parameters to an intent and I am calling the intent by it's Event name.
I understand that the parameters object has to be converted from a Json to a Struct, but for some reason the parameters are not passing. What am I doing wrong?
Please note I had to copy and paste the 'structjson.js' provided by Google into the same directory as my index.js because I am exporting to Firebase Functions, and I had to place some constants inside of certain functions within the structjson.js so I could export those functions to use in my index.js file.

Expected response from Dialogflow: 'Your user ID is: 00000001'
Actual response from Dialogflow: 'Your user ID is: ${n_digit}'

Request to Dialogflow Code
import * as functions from 'firebase-functions';
import * as dialogflow from 'dialogflow';
// // Start writing Firebase Functions
// // https://firebase.google.com/docs/functions/typescript
//
export const register = functions.https.onRequest((request, response) => {

    // Instantiates a session client
    const projectId = [MY_PROJECT_ID];
    const sessionId = '123456789';
    const languageCode = 'en-US';
    let config = {
            credentials: {
                private_key: [MY_PRIVATE_KEY],
                client_email: [MY_CLIENT_EMAIL]
            }
        }
    const sessionClient = new dialogflow.SessionsClient(config);

    // The path to identify the agent that owns the created intent.
    const sessionPath = sessionClient.sessionPath(projectId, sessionId);

    var structjson = require('./structjson')

    // The text query request.
    const req = {
    session: sessionPath,
    queryParams: {
        "resetContexts": true,
    },
    queryInput: {
      event: {
        name: 'init',
        parameters: structjson.jsonToStructProto({userID: '00000001'}),
        languageCode: languageCode,
      },
    },
    };

    sessionClient
    .detectIntent(req)
    .then((responses) => {
      const result = responses[0].queryResult;
      response.send(result.fulfillmentText);
    })
    .catch(err => {
      console.error('ERROR:', err);
    });
})

structjson.js
module.exports.jsonToStructProto = function jsonToStructProto(json) {
    var structjson = require('./structjson')
      const fields = {};
      for (const k in json) {
        fields[k] = structjson.jsonValueToProto(json[k]);
      }

      return {fields};
    }

    module.exports.jsonValueToProto = function jsonValueToProto(value) {
      const valueProto = {};
      const JSON_SIMPLE_TYPE_TO_PROTO_KIND_MAP = {
        [typeof 0]: 'numberValue',
        [typeof '']: 'stringValue',
        [typeof false]: 'boolValue',
      };

      if (value === null) {
        valueProto.kind = 'nullValue';
        valueProto.nullValue = 'NULL_VALUE';
      } else if (value instanceof Array) {
        valueProto.kind = 'listValue';
        valueProto.listValue = {values: value.map(jsonValueToProto)};
      } else if (typeof value === 'object') {
        valueProto.kind = 'structValue';
        valueProto.structValue = jsonToStructProto(value);
      } else if (typeof value in JSON_SIMPLE_TYPE_TO_PROTO_KIND_MAP) {
        const kind = JSON_SIMPLE_TYPE_TO_PROTO_KIND_MAP[typeof value];
        valueProto.kind = kind;
        valueProto[kind] = value;
      } else {
        console.warn('Unsupported value type ', typeof value);
      }
      return valueProto;
    }

    module.exports.structProtoToJson = function structProtoToJson(proto) {
      if (!proto || !proto.fields) {
        return {};
      }
      const json = {};
      for (const k in proto.fields) {
        json[k] = valueProtoToJson(proto.fields[k]);
      }
      return json;
    }

    module.exports.valueProtoToJson = function valueProtoToJson(proto) {

        const JSON_SIMPLE_VALUE_KINDS = new Set([
          'numberValue',
          'stringValue',
          'boolValue',
        ]);

      if (!proto || !proto.kind) {
        return null;
      }

      if (JSON_SIMPLE_VALUE_KINDS.has(proto.kind)) {
        return proto[proto.kind];
      } else if (proto.kind === 'nullValue') {
        return null;
      } else if (proto.kind === 'listValue') {
        if (!proto.listValue || !proto.listValue.values) {
          console.warn('Invalid JSON list value proto: ', JSON.stringify(proto));
        }
        return proto.listValue.values.map(valueProtoToJson);
      } else if (proto.kind === 'structValue') {
        return structProtoToJson(proto.structValue);
      } else {
        console.warn('Unsupported JSON value proto kind: ', proto.kind);
        return null;
      }
    }

Dialogflow webhook
function receiveParams (agent) {
    const parameter = request.body.queryResult.parameters;
     const n_digit = parameter.userID;
     agent.add('Your user ID is: ${n_digit}');
  }

  let intentMap = new Map();
  intentMap.set('init', receiveParams);
  agent.handleRequest(intentMap);
});

Thank you in advance!
Comment: I would like to make a note that the fact that you have to use a struct object in that parameter is unrelated to gRPC. It is simply how the API is defined. The only thing that is really specific to gRPC here is the automatic conversion from plain JS objects to the protobuf messages that the API uses.
Comment: Nice one! Edited, thank you
Answer: You can send parameters like
{
  "fulfillmentText":"This is a text response",
  "fulfillmentMessages":[  ],
  "source":"example.com",
  "payload":{
    "google":{  },
    "facebook":{  },
    "slack":{  }
  },
  "outputContexts":[
    {
      "name":"<Context Name>",
      "lifespanCount":5,
      "parameters":{
        "<param name>":"<param value>"
      }
    }
  ],
  "followupEventInput":{  }
}

Using NodeJS client you can save params like
let param1 = [];
let param2 = {};
let ctx = {'name': '<context name>', 'lifespan': 5, 'parameters': {'param1':param1, 'param2': param2}};
agent.setContext(ctx);

and access these params like
let params = agent.getContext("<context name>").parameters;
let param1 = params.param1;
let param2 = params.param2;

Check out my complete answer here.
Comment: Now we can use `let params = agent.originalRequest.parameters;` according to [this](https://dialogflow.com/docs/reference/fulfillment-library/webhook-client) too, found out this works pretty well. Even when adding context params in the request this will pop up under the originalRequest child. Thank you for helping me get to this point, @Abhinav Tyagi.
Comment: Is this to send context parameters from a client server to the agent?
Comment: this is to save parameters to be used in subsequent conversation. This can be accessed from both clients as well as in server till the context is alive.
Comment: Ah! I see, sorry in the post I should have gave more context. The NodeJS library you sent is for the agent side (fulfillment webhook.) I am only trying to inject parameters in the payload sent from my web server to the Dialogflow agent. I'm not missing something am I? Thank you for your help and responses so far.
Comment: you can inject the parameters in the JSON as shown above :)
Comment: ? But I am using a session client object from the NodeJS client library, but the setContext method is a method from the fulfillment library not the client library
Comment: Okay I get it now, I can access these active contexts with my webhook in what you sent. I can also use #context_name.key in the ctx object I create to respond with it in my Dialogflow agent. Thank you!
Comment: If my answer solved your problem then you can upvote and mark it as answer for others to follow.
Comment: The only problem is, when I use "detectIntent()" after setting the context parameters right after the event call I can't use the context parameters in the same session ID. Any ideas?
Comment: Like when I use #context_name.key in my other intent responses it doesn't show up.


Como eu faço um switch de classes de botões que acionam um player para aparecer e ocultar?

Question: Eu tenho 3 botões no formato de Link  com as classes: .icon-play, .icon-pause e .icon-download, eu quero mudar a classe play com pause, assim como o inverso, sem influenciar o botão de download, assim que o icon-play for clicado vai mostrar um player e se o pause for ativado vai ocultar o player.
var btnplay = $(".livro-audio a").find(".icon-play");
var btnpause = $(".livro-audio a").find(".icon-pause");

$( btnplay ).click(function() {
 $( '.player-active' ).show();
 $(this).attr('class', 'icon-pause');
 if($('.player-active:visible')){
    $( ".livro-audio" ).last().css( "margin-bottom", "150px" );
    $( ".livro-video" ).last().css( "margin-bottom", "150px" );
  }
});

$( btnpause ).click(function() {
  $( '.player-active' ).hidden();
  $(this).attr('class', 'icon-play');
  if($('.player-active:hidden')){
    $( ".livro-audio" ).last().css( "margin-bottom", "80px" );
    $( ".livro-video" ).last().css( "margin-bottom", "80px" );
  }

});

Até o momento o Lucas me deu uma luz, ficando assim:
 $(".livro-audio a").click(function(){
  if($(this).hasClass('icon-play')){
   $(this).addClass('icon-pause').removeClass('icon-play');
   $('.player-active').show();
  }
 else{
   $(this).addClass('icon-play').removeClass('icon-pause');
   $('.player-active').hide();
  }
});

Só que esse código mexe com o minha terceira classe .icon-download, tem alguma forma de identificá-lo, para ele não receber as classes play e pause quando ele for clicado, obrigada.
Comment: coloca um id no botão play/pause (tipo "btnPlayPause") e muda o seletor do jquery de ``$(".livro-audio a")`` para ``$("#btnPlayPause")``
Answer: Você pode usar o addClass e removeClass para trocar o estilo no elemento.
Exemplo:

$("#player").click(function(){
  if($(this).hasClass('player_azul'))
    $(this).addClass('player_ver').removeClass('player_azul');
  else
    $(this).addClass('player_azul').removeClass('player_ver');
});
.player_azul{
  background: blue;
}

.player_ver{
  background: red;
}

Elemento

Este é apenas um exemplo que você pode adaptar ao seu caso. Em algumas situações é interessante usar também o toggleClass do jQuery.


Debian 10, cant use 2 Network Interfaces at the same time

Question: Problem and explanation:
What I want to do: Setting up the interfaces, so all can be used at the same time.
Problem: I got 3 Interfaces in total. 1 is the LAN Connection and 2 are LTE Connections tethered by phones. I'm testing the Connection via Ping -I (interface name) and only 1 Connection works. The other 2 are not working, I searched for 6 hours but didn't find an answer.
So to get to the question, my problem is that I have 3 interfaces / connections but can only use one of them. And I want to use all three at the same time

Interfaces and explanation:
The First LTE Connection is enp0s8
The LAN Connection is enp0s9
The Second LTE Connection is enp0s17
So to explain it simply. I have a LAN interface and 2 tethered LTE interfaces and when I try to ping something with the LAN interface (with ping -I [interface name] 126.96.36.199) it doesn't work, it only works on one interface and this is the first LTE Interface. Which is also the first after the loopback interface with the command "ip addr".
-ping -I enp0s8 220.127.116.11 works [First LTE Interface]
-ping -I enp0s9 184.108.40.206 doesn't work [LAN Interface]
-ping -I enp0s17 18.104.22.168 doesn't work [Second LTE Interface]

Information:
If you need any additional Information, just ask.
Route =
default        192.168.42.129    0.0.0.0         enp0s8
10.0.0.0       0.0.0.0           255.255.255.0   enp0s9
172.20.10.0    0.0.0.0           255.255.255.24  enp0s17
192.168.42.0   0.0.0.0           255.255.255.0   enp0s8

Interfaces File =
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

source /etc/network/interfaces.d/*

# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
allow-hotplug enp0s17
iface enp0s17 inet dhcp

allow-hotplug enp0s8
iface enp0s8 inet dhcp

allow-hotplug enp0s9
iface enp0s9 inet dhcp

Comment: How exactly do you want to use these three interfaces at the same time? Surely your goal is not to be able to ping remote hosts.
Comment: I want to use it with wireguard and engarde (https://github.com/porech/engarde) and the three interfaces would be a "failover/bonding" mechanism. And the only problem is that the interfaces don't all work at the same time, only one works at the same time, everything else is already working.
Comment: Hm, OK, that requires setting up policy based routing, which there are already many tutorials about.
Comment: Can you send me a link for that?
Answer: I installed Ubuntu and used Netplan to fix it.
I put this in the netplan:
network:
  version: 2
  renderer: networkd
  ethernets:
    enp0s8:
      dhcp4: yes
    enp0s17:
      dhcp4: yes
      dhcp4-overrides:
        route-metric: 200

This is the solution.


How to add kaleido package to poetry.lock file?

Question: When attempting to install "kaleido" via Poetry, I receive the following error message:
~ poetry add kaleido
Using version ^0.2.1 for kaleido

Updating dependencies
Resolving dependencies... (3.1s)

Package operations: 1 install, 0 updates, 0 removals

  • Installing kaleido (0.2.1.post1): Failed

  RuntimeError

  Unable to find installation candidates for kaleido (0.2.1.post1)

  at ~/.poetry/lib/poetry/installation/chooser.py:72 in choose_for
       68│
       69│             links.append(link)
       70│
       71│         if not links:
    →  72│             raise RuntimeError(
       73│                 "Unable to find installation candidates for {}".format(package)
       74│             )
       75│
       76│         # Get the best link

However, the "kaleido" appears in the poetry.lock file:
[[package]]
name = "kaleido"
version = "0.2.1.post1"
description = "Static image export for web-based visualization libraries with zero dependencies"
category = "main"
optional = false
python-versions = "*"

If I try to export an image, I unsurprisingly receive the following error message:
ValueError:
Image export using the "kaleido" engine requires the kaleido package,
which can be installed using pip:
    $ pip install -U kaleido

Does anyone know how to install this package via poetry (or amend the .lock file to do it manually)?
Answer: Firstly try to use a master version of poetry as advised in Github issue
or upgrade it to the latest version
pip3 install --upgrade poetry

Then try to install with kaleido with locked version:
poetry add kaleido==0.2.1

That worked in my case.
Comment: as of yesterday, almost three years later, poetry still needs a locked version of kaleido to work in my system. Just registering that, I have no idea whats causing it.
Comment: 2024 and this is still a valid comment.


Adding multiple Maps to a List using DynamoDb, Lambda, Api Gateway

Question: I'm passing a params to Api Gateway to be saved in DynamoDB using AWS Lambda Node JS.
The integration request of Api Gateway is:
#set($inputRoot = $input.path('$'))
{
  "name" : "$inputRoot.name",
  "profileImage": "$inputRoot.profileImage",
  "gender" : "$inputRoot.gender",
  "interests": #foreach ( $item in ["$inputRoot.interests"] ) $item #end,
  "surveyOne": "$inputRoot.surveyOne",
  "surveyOneAnswer": "$inputRoot.surveyOneAnswer",
  "surveyTwo": "$inputRoot.surveyTwo",
  "surveyTwoAnswer": "$inputRoot.surveyTwoAnswer"
}

The content of AWS Lambda (Node JS) to receive the params and save it to DynamoDB:
const params = {
    Item: {
      'uuid': { S: "i_" + uuidv4() },
      'name': { S: event.name },
      'profileImage': { S: event.profileImage },
      'gender': { S: event.gender },
      'interests': { SS: event.interests },
      'surveys' : {
        L: [
          {
            M: {
              'type': { S: event.surveyOne },
              'answer': { S: event.surveyOneAnswer },
            },
            M: {
              'type': { S: event.surveyTwo },
              'answer': { S: event.surveyTwoAnswer }
            }
          }
        ]
      }
     },
     TableName: 'users'
   };

   dynamodb.putItem(params, (err, data) => {
     if (err) {
      const response = {
        statusCode: 500,
        headers: {
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({status: false})
      };
      return callback(null, response);
    }

    // return status 200 if success
    const response = {
      statusCode: 200,
      headers: {
        'Access-Control-Allow-Origin': '*'
      },
      body: JSON.stringify({status: 'A new record has been added'})
    };
    return callback(null, response);

   })

But the saved item in Dynamo DB only contains one survey which is the surveyTwo. It should be 2 because I passed surveyOne and surveyTwo type and answer.
My expected result should be
{
  "name": "John Doe",
  "profileImage": "https://example.com",
  "gender": "m",
  "interests": ["Basketball",  "Swimming"],
  "surveys": [
    { "type": "question 1", "answer": "answer to question 1" },
    { "type": "question 2", "answer": "answer to question 2" }
  ]
}

Answer: I would recommend to use the DynamoDb DocumentClient Class.
You can supply the same parameters, but with native JS types.
The DocumentClient does the marshalling and unmarshalling for you, which might be the problem with your surveyTwo issue.
Your example would then look something like this.
var params = {
 TableName : 'users',
 Item: {
     uuid: 'i_' + uuidv4(),
     name: event.name,
     surveys: [
        {type: event.surveyOne, answer: event.surveyOneAnswer},
        {type: event.surveyTwo, answer: event.surveyTwoAnswer}]
     }
};

var documentClient = new AWS.DynamoDB.DocumentClient();

  documentClient.put(params, function(err, data) {
 if (err) console.log(err);
 else console.log(data);
});

Comment: Yup I just fixed the error also by using Document Client. Thanks for the answer though


Is there something equivalent to template_preprocess_search_results()?

Question: I just realized that template_preprocess_search_results() function has been left out in Drupal 8 for some reasons, although template_preprocess_search_result() (for single results) is still there.
I need to be able to manipulate the search results prior to rendering as I would with template_preprocess_search_results() in Drupal 7.
Answer: You can create a new module and inside your YOUR_MODULE.module file put this code:
function YOUR_MODULE_preprocess_item_list__search_results(&$variables) {
  //to use dpm() you nedd the devel module
  dpm($variables['items']);
}

Install your module and you will see the output in the search result
Answer: The method that builds the search results is SearchController::view(), which contains the following code.
  $results = array();
  if ($request->query->has('keys')) {
    if ($plugin->isSearchExecutable()) {
      // Log the search.
      if ($this->config('search.settings')->get('logging')) {
        $this->logger->notice('Searched %type for %keys.', array('%keys' => $keys, '%type' => $entity->label()));
      }

      // Collect the search results.
      $results = $plugin->buildResults();
    }
    else {
      // The search not being executable means that no keywords or other
      // conditions were entered.
      drupal_set_message($this->t('Please enter some keywords.'), 'error');
    }
  }

  if (count($results)) {
    $build['search_results_title'] = array(
      '#markup' => '
' . $this->t('Search results') . '
',
    );
  }

  $build['search_results'] = array(
    '#theme' => array('item_list__search_results__' . $plugin->getPluginId(), 'item_list__search_results'),
    '#items' => $results,
    '#empty' => array(
      '#markup' => '
' . $this->t('Your search yielded no results.') . '
',
    ),
    '#list_type' => 'ol',
    '#context' => array(
      'plugin' => $plugin->getPluginId(),
    ),
  );

So, you can use template_preprocess_item_list(&$variables), checking that $variables['#context']['plugin'] is set. (I am not sure about using template_preprocess_item_list__search_results(&$variables), since I have never tried using such preprocess function.)
The $plugin->buildResults() method called from SearchController::view() just builds the results as array of items themed with search_result.
  $results = $this->execute();

  $built = array();
  foreach ($results as $result) {
    $built[] = array(
      '#theme' => 'search_result',
      '#result' => $result,
      '#plugin_id' => $this->getPluginId(),
    );
  }

Comment: template_preprocess_item_list__search_results() should work now in Drupal 8 *if* you actually have such a template.
Comment: That would make things easier, since the template would surely be used for the search result page.
Comment: @Berdir I did not find the function in the core docs so I just presumed it was removed. Can you please elaborate on the "if you have such a template"? Thanks!
Comment: @Henkealg Berdir was replying to my _I am not sure about using `template_preprocess_item_list__search_results(&$variables)` since I have never tried using such preprocess function._ He means you can use `template_preprocess_item_list__search_results(&$variables)` as long as you have a item_list__search_results.html.twig template.
Comment: Thanks for the follow-up. I was able to use template_preprocess_item_list__search_results() in the way you suggested even though it is not included in the documentation anymore (strange). Kiam; I will mark your answer as accepted to close this thread. Thanks again.
Comment: @Henkealg You find [`template_preprocess_item_list()`](https://api.drupal.org/api/drupal/core%21includes%21theme.inc/function/template_preprocess_item_list/8.1.x); `template_preprocess_item_list__search_results()` is considered a variant of that preprocess function, and as such it is not documented.


Block walking and non-overlapping paths

Question: The problem reads (Martin: The art of enumerative combinatorics, problem 1.11.2):
How many shortest paths, consisting only of nonoverlapping (except at
endpoints) unit segments that are parallel to an axis, are there from the
origin in the plane to the point $(10, 6)$?
My question is for what is really asking the problem, not the answer of it.
If I want to go from the origin to the grid-point $(10,6)$ without overlapping I have to begin
either with a step to the right $R$, or up $U$, and end in a similar way.
Thus, I have $\frac{14!}{9! 5!}$ to travel starting from, say starting with $R$ and ending with $U$ (Notice that I cannot start, e.g. with $U$ and end with $U$, because any other path will have an intersection with this path).
Actually, I think that the only allowed combinations to start and end are the tuples $(R,U)$ and $(U,R)$, each one of them with $\frac{14!}{9! 5!}$ ways to travel from the origin to the destination point.
So at the end I'm confused of what to count, if pairs of allowed paths (possibly repeated) or what?
Comment: I think you're misreading, and getting hung up on, the word "nonoverlapping".  It's the unit steps in a path that are not allowed to overlap in this problem.  There is no condition that different paths be nonoverlapping. (I don't actually understand why the author felt it necessary to state that the steps in paths be nonoverlapping.  The only way I can see for steps to overlap is for either backtracking or a cycle to occur, and both of these are ruled out by the condition that the path be a shortest path.)
Comment: You can start with an $U$ and end with an $U$. You want to find all shortest paths $p$ such that: $p$ starts at $(0,0)$ and ends at $(10,6)$, $p$ can only move up or right with distance $1$ and $p$ does not cross itselfs.
Comment: @WillOrrick
So you say that the overlapping condition holds for the path itself, and not for two different paths? If this is the case, then the possible paths will just be $\frac{16!}{10! 6!}$
Comment: Yes, that's my reading of the problem.
Answer: You are on the right path, but off by $1$ a couple places.  You need $16$ steps, of which $10$ are $R$ and the other $6$ are $U$, so you just choose $10$ of the steps to be $U$, getting ${16 \choose 10}$.  There are no other restrictions.
Comment: It confuses me the non-overlapping condition. If I ignore it I know that the answer is $\frac{16!}{10!6!}$ for all possible ways to got from the origin to the destination taking always $10$ steps to the right and $6$ steps  up.
Comment: Once you specify the segments are axis aligned and allow the endpoints to be common, the non-overlapping does not matter.  If you had any overlap, you would have to be going down or left on one of the segments and the path would be longer.

Block walking and non-overlapping paths


Panel data visualization

Question: Does anyone know how to graph changes in a dependent variable over time, based on changes in several independent variables (i.e., graphs for panel data regressions)?
Comment: When there is no unobservable heterogeneity in panel data, we essentially have $n$ iid time series, where $n$ is the number of individuals in sample. One way is to graph all $n$ time series on one picture (you can also the changes of average dependent variable with respect to the average of independent variable(s)). It is hard to graph changes when there is unobservable heterogeneity. Imagine there is an unobservable variable $Z$, denoting fixed effect. When $Z$ takes $K$ possible values, the data then contains $K$ clusters. We need to graph changes for each cluster.
Answer: If you are using Stata you could use "margins" after the regression and then the "marginsplot" command.
So, your command can look like this:
<code> xtreg y x1 x2 x3... , fe
 margins, over (x1) at (x2 = (20 30 40 50))
 marginsplot
</code>

Panel data visualization