text:
Q: Function call stack overflow I get the error message below when I run my code. The code below add the elements that are not nil.
(summit2 '(0 nil 1 2))

Error: Received signal number -3 (function call stack overflow (delayed response))
[condition type: ASYNCHRONOUS-OPERATING-SYSTEM-SIGNAL]

I have tried changing null with nil. I also tried using eq as opposed to eql.
(defun summit2 (lst)
    (if (eql (car lst) null)
        (summit2 (cdr lst))
      (+ (car lst) (summit2 (cdr lst)))))

the expected output should be 3, the sum of the elements in the list that are not nil

A: First of all, the check for nil should be done by using the NULL function, so (null (car lst)) in your case. Secondly, your recursion lacks the base case (the error you're getting indicates a stack overflow due to infinite recursion). Now you only distinguish between whether the next element is nil or non-nil. You need a third case to handle the empty list. This suggests the use of COND. You could, for example do something like:
(defun summit2 (lst)
  (cond
    ((null lst)
     0)
    ((null (car lst))
     (summit2 (cdr lst)))
    (t
     (+ (car lst) (summit2 (cdr lst))))))

A: Some remarks

*

*You can spell your list list, there is no need to abbreviate it to lst.

*All branches in your code leads to a recursive call to summit, there is no case where you stop computing the result. This infinite computation takes up stack space, which is why it eventually stops with a stack overflow.

*Please indent your code in a conventional way (read for example this style guide)

Notice that the case where an element is nil is not much different than the case where the input list is empty. With the following code, both are handled the same way:
(defun sum (val)
  (if (consp val)
      (+ (sum (car val))
         (sum (cdr val)))
      (or val 0)))

This also means the code is able to do more than expected, i.e. you can sum numbers in a tree:
(sum '(0 1 2 nil 4 5 7 (1 2)))
=> 22

And it also works when the input is just an number:
(sum 5)
=> 5


text:
Q: How can I auto map the Z drive How can I auto map the Z: on my client PC that's running Windows 7, to my server that running Windows Server 2012 R2?  Path to the Server: \\Server2\IT tools

A: Open GPEdit.msc and open User Configuration, Windows Settings, Scripts so that you can see the Logon, Logoff Scripts.
Put your mapping script in a batch file  (logon.bat)  and put this in
C:\Windows\System32\GroupPolicy\User\Scripts\logon
That will run this script at startup / log on.
You might wish to put the disconnect script in a batch file in the Logoff folder.

A: This will map the Z: drive on the Windows 7 machine.
net use  z: "\\Server2\IT tools"

It would be good to save this in a batch file and put it in the Startup folder (e.g C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp) so it runs at startup of the user login process to remap the drive at each logon.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Insert with select giving duplicate key violation I have a stored procedure that is in effect trying to do an upsert into a table. Consider the following:
create table dbo.myTable (
   id int not null constraint PK_myTable primary key (id),
   payload varchar(100)
);

In the stored procedure, I'm populating a temp table that has the same structure as the table with user input and then attempting the following:
insert into dbo.myTable
   (id, payload)
select source.id, source.payload
from #temp as source
left join dbo.myTable as target
   on source.id = target.id
where target.id is null;

When I test this in isolation (i.e. just the above statement, wrapped in an explicit transaction; test harness below), running a second instance will wait on a key lock. This is what I expect. However, what I'm seeing is that occasionally under load I'm getting a duplicate key error. How is that possible?
I understand that I have a couple of ways around it. I could put IGNORE_DUP_KEY on the primary key constraint. I could also wrap the insert statement in a try and swallow the error. And, in all honesty, I'm going to explore those options. But I'd like to understand how the second transaction gets the green light to do the insert.

Test Harness
insert into #temp
   (id, payload)
values
   (1, 'test');

begin transaction
go
    insert into dbo.myTable
    (id, payload)
    select source.id, source.id
    from #temp as source
    left join dbo.myTable as target
        on source.id = target.id
    where target.id is null

A: If you wish to understand, then you can easily get this error manually. Open SSMS. Create simple table there, for example:
CREATE TABLE test
(
 id int not null primary key
)

Now open the transaction and make an insert:
BEGIN TRANSACTION
insert into test values(1); -- do not commit

Then open new window in SSMS and repeat the same statement there:
insert into test values(1);

Now go back to your first window and commit the transaction. In the second window you'll get:

Msg 2627, Level 14, State 1, Line 1 Violation of PRIMARY KEY
  constraint 'PK__test__3213E83F2818DDD3'. Cannot insert duplicate key
  in object 'dbo.test'. The duplicate key value is (1).

I think that the most proper way to solve that issue is to use proper isolation levels.

A: Ben, an explicit transaction starts with a BEGIN and is followed by either a COMMIT or a ROLLBACK neither of which is present. Also it is inappropriate to include a GO in a stored procedure. Please tell us why you need to insert a single record in a #temp table and then move the same to  myTable? You might want to try something like the following after providing for parameters @Id and @payload in the procedure:
;MERGE dbo.myTable AS target
USING (SELECT @Id,@payload) AS source (Id,Payload)
ON (target.Id = source.Id)
WHEN NOT MATCHED THEN
 INSERT (Id,Payload)
 VALUES (source.Id,source.Payload);
Note that the MERGE statement requires the preceding " ; ".
An explicit transaction would not be required.

A: You can avoid the primary key issue by utilizing a SEQUENCE object.
I'm not sure where you're creating your id value now, but if you create a SEQUENCE, say sqPayload, then call NEXT VALUE FOR sqPayload wherever you're assigning that id number, the ids will stay sequential and unique, no matter how many transactions are writing simultaneously and you'll never violate the primary key.
You might want to make that a BIGINT SEQUENCE. If you're already running into concurrency issues, you might burn through all the INTs, and that's just never any fun.


text:
Q: Place Element on Top Left Corner of Page I'm using materialize css in my web application and I'm trying to make use of the Click Only Fab. The problem is that this always ends up on the bottom right corner of my page, when I want it on the top left.

          menu

insert_chart

format_quote

publish

attach_file

I tried everything including floating and aligning and nothing has worked. How can I get this on the top left corner of my page? So I can use it as a menu button.

A: Can't you make a custom css class with
position:absolute;
top:0;
right:0;

? Alternatively fixed instead of absolute if you want it in the corner of the display, not page. I would comment but bloody 50 rep required, will delete this answer if it turns out to be very wrong.


text:
Q: Is $f(x) = e^x$ one-to-one if $f:\mathbb{R} \rightarrow \mathbb{R}$? My book says that $f(x) = e^x$ is not invertible from the set of real numbers to the set of real numbers. But I disagree since $f(x) = e^x$ is injective with this given domain and codomain and therefore invertible.

A: $f(x)=e^x$, with $f:\mathbb R \to \mathbb R$, is injective but not surjective since $e^x>0$ for all $x \in \mathbb R$.
To turn an injective function into a bijective (hence invertible) function, it suffices to replace its codomain by its actual range. In this particular case that means defining the function as $f:\mathbb R \to \mathbb R_{++}.$

A: $f: \mathbb R\to (0,\infty)$, defined as $f(x)=e^x$ is bijective. there exists an inverse function $f^{-1}:(0,\infty)\to\mathbb R$ for which we have $$f^{-1}(f(x)) = x$$ for all $x\in\mathbb R$ and $f(f^{-1}(x))=x$ for all $x\in(0,\infty)
However, $g:\mathbb R\to\mathbb R$, defined as $g(x)=e^x$ is not bijective, because there is no $x\in\mathbb R$ such that $g(x)=-1$.

A: Perhaps the author has in mind that $\exp : \mathbb R \to (0,\infty)$ is invertible but $\exp : \mathbb R \to \mathbb R$ is not, since not every member of $\mathbb R$ has an image under the inverse function.  You might want to look with a fairly high-resolution microscope at how this particular author defines things.


text:
Q: Installing Firebase package in Python When I try to install the firebase package in python using:
python -m pip install firebase
I get the output:
Could not find a version that satisfies the requirement firebase (from versions: )
No matching distribution found for firebase
Can't seem to find a solution for windows devices.

A: Try python -m pip install python-firebase
Additional info: https://pypi.org/project/python-firebase/


text:
Q: How can I find what search terms (if any) brought a user to my site? I want to create dynamic content based on this. I know it's somewhere, as web analytics engines can get this data to determine how people got to your site (referrer, search terms used, etc.), but I don't know how to get at it myself.

A: You can use the "referer" part of the request that the user sent to figure out what he searched for. Example from Google:

http://www.google.no/search?q=stack%20overflow

So you must search the string (in ASP(.NET) this can be found be looking in Request.Referer) for "q=" and then URLDecode the contents.
Also, you should take a look at this article that talks more about referrers and also other methods to track your visitors:
http://www.15seconds.com/issue/021119.htm

A: This is some code to backup the idea of using a querystring method and if that's not available using the UrlReferrer property of the Request object. This can then be stashed in a session object (or somewhere else if that works better for you) so that you can track the source between pages. (Page_Load doesn't seem to be formatted correctly inside the code sample here)
public void Page_Load(Object Sender, EventArgs E) {
            if (null == Session["source"] || Session["source"].ToString().Equals(string.Empty)) {
                if (Request.QueryString["src"] != null) {
                    Session["source"] = Server.UrlDecode(Request.QueryString["src"].ToString());
                } else {
                    if (Request.UrlReferrer != null) {
                        Session["source"] = Request.UrlReferrer.ToString();
                    } else {
                        Session["source"] = string.Empty;
                    }
                }
            }}


text:
Q: Meaning of the general matrix element $\langle x'|O|x\rangle $ In a recent lecture we were told that  $\langle x'|\hat{O}|x \rangle = O(x,x') = O(x)\delta(x-x')$ "due to the locality of quantum mechanical observables".
I have no idea what this is supposed to mean any comments or references to a book from which this, or something similar, originates would be much appreciated

A: Okay, $\delta$ is the Dirac $\delta$-function; it is an infinitely thin infinitely tall spike at $0$ where the limit is taken such that the area of the spike remains a constant $1.$ In general there are lots of function families $f_k$ which satisfy the essential property $\lim\limits_{k\to0}\int dx~f_k(x) ~g(x) = g(0),$ and for some of these families every $f_k$ is a smooth function, so you can always essentially pretend that $\delta(x)$ is smooth. One such choice is $k = \sigma$ in the Gaussians of unit integral, $(2\pi\sigma^2)^{-1/2} \exp\big[-x^2/(2\sigma^2)\big].$ That is valid if $x$ is defined in the position-space $\mathbb R$, but there are certainly other Dirac-$\delta$ functions for higher-dimensional spaces, where generally $\int dx_1\int dx_2\dots \int dx_n~\delta_n(\vec x) ~g(\vec x) = g(\vec 0).$
The basis vectors $|x\rangle$ and $|x'\rangle$ are being written in the "position basis", which is not actually 100% well-defined. The general idea is that $\int dx~|x\rangle\langle x|$ is the identity operator $\hat 1$ (when integrated over $(-\infty, \infty)$), with the "orthonormality" relation $\langle m|n\rangle = \delta_{mn}$ using the Kronecker $\delta$ being replaced by the Dirac $\delta$ as $\langle x' | x\rangle = \delta(x - x').$
The fact that you cannot really find a set of wavefunctions which do this perfectly is viewed as a side-note to a valid way of managing the algebra involved. Yes, basically $|x_0\rangle$ is essentially supposed to be a square-root-of-$\delta$ function, so that in 1D we're supposed to consider $\psi_{x_0}(x)$ as the limit of $(2\pi\sigma^2)^{-1/4} \exp\big[-(x - x_0)^2/(4\sigma^2)\big]$ in the limit (after the integrals have been all performed) as $\sigma\to 0.$  But more importantly: the math works at the bra- and ket- levels, so why not use it?
The claim being offered here is that a quantum mechanical observable must be local, presumably in the sense that it must not connect two different positions at the same time. Therefore probably $\vec x$ lives in Minkowski space and the $\delta$ functions we're meant to use are 4D ones, though you could also retrieve the 1D case if you are making the statement that $\hat O$ is a measurement that is performed instantaneously rather than by evolving the system with some Hamiltonian first and then performing your instantaneous projective measurement.
The claim probably requires that $O(x)$ remain a differential operator, because locality should really only demand that an observable depend on a wavefunction and its derivatives at some point. In particular I'd very much struggle to see how the momentum operator in 1D would look if not $O(x) = -i\hbar \partial_x.$

A: Since having asked this question I know feel I understand the meaning:
Firstly the matrix element can only really be understood within a corresponding matrix equation such as:
$$\langle \psi  |\hat{O}|\psi\rangle=\int \mathrm dx \int \mathrm dx' \langle \psi |\,x'\rangle \langle x' |\hat{O}|\,x\rangle  \langle x\, |\,\psi\rangle $$
Now in non relativistic QM $\hat{O}=f(\hat{p},\hat{x})$ i.e. the operator can be written as some function of momentum and position operators. Firstly the simplest case is if  $\hat{O}=f(\hat{x})$ then we have
\begin{align}&=\int \mathrm dx \int \mathrm dx' \langle \psi |\,x'\rangle \langle x' |\,f(\hat{x})|\,x\rangle  \langle x\, |\,\psi\rangle \\&= \int \mathrm dx \int \mathrm dx' \langle \psi |\,x'\rangle f(x)\langle x' |\,x\rangle  \langle x\, |\,\psi\rangle \\ &= \int \mathrm dx \int\mathrm dx' \langle \psi |\,x'\rangle f(x)\delta(x-x')  \langle x\, |\,\psi\rangle \end{align}
Next we can consider the case when $\hat{O}=f(\hat{p})$:
\begin{align}&=\int\mathrm  dx \int \mathrm dx' \langle \psi |\,x'\rangle \langle x' |\,f(\hat{p})|\,x\rangle  \langle x\, |\,\psi\rangle\\ & = \int\mathrm dp \int\mathrm dx \int\mathrm dx' \langle \psi |\,x'\rangle f(p)\langle x' |\,p\rangle\langle p\, |x\rangle  \langle x\, |\,\psi\rangle \\& = \int \mathrm dp \int\mathrm dx \int\mathrm dx' \langle \psi |\,x'\rangle f(p)e^{-ip(x'-x)/\hbar} \langle x\, |\,\psi\rangle \\& = \int \mathrm dp \int \mathrm dx \int \mathrm dx' \langle \psi |\,x'\rangle f\left(-i\hbar\frac{\partial}{\partial x'}\right)e^{-ip(x'-x)/\hbar} \langle x\, |\,\psi\rangle \\ &=  \int \mathrm dx \int \mathrm dx' \langle \psi |\,x'\rangle f\left(-i\hbar\frac{\partial}{\partial x'}\right)\delta(x-x') \langle x\, |\,\psi\rangle \\&=   \int \mathrm dx' \langle \psi |\,x'\rangle f\left(-i\hbar\frac{\partial}{\partial x'}\right) \langle x'\, |\,\psi\rangle \end{align}
Hence we have again related the matrix form of the operator to its corresponding differential operator in the position representation. This process can be generalised for any product of operators $\hat{p}$ and $\hat{x}$ and so in general we see that:
$$\langle x' |\hat{O}|\,x\rangle=\langle x' |f(\hat{x},\hat{p})|\,x\rangle=f\left(x',-i\hbar\frac{\partial}{\partial x'}\right)\delta(x-x')\,.$$


text:
Q: Django - Object of type User is not JSON serializable I am facing an issue with POSTing data (which has a User object) to a ModelViewSet.
Error: "Object of type User is not JSON serializable"
data_params = {
        "log_user_id": user,
        "device_name": "sampledevice",
        "log_user_email": "svc.netadc@ads.aexp.com",
        "feature_name": 'Subnet Automation',
    }

    print(data_params, "data_params")
    response = requests.post("<url>/netadc3/arista/ImplementationLogsAristaViewSet/implementationlogsarista/",
    auth=(<username>, <password>), headers={"content-type": "application/json"}, data=json.dumps(data_params), verify=False)

serializers.py:
class ImplementationLogsAristaSerializer(serializers.HyperlinkedModelSerializer):

    log_user_id = UserSerializer(read_only=True)

    class Meta:
        model = ImplementationLogsArista
        fields = ('log_id','device_name', 'log_user_id','log_user_email','feature_name')

views.py:
class ImplementationLogsAristaViewSet(viewsets.ModelViewSet):
    queryset = ImplementationLogsArista.objects.all()
    serializer_class = ImplementationLogsAristaSerializer
    permission_classes = (IsAuthenticated,)
    pagination_class = None

models.py:
class ImplementationLogsArista(models.Model):

log_id = models.AutoField(primary_key=True)
device_name = models.CharField(max_length=800, verbose_name='Device Name',default='sampledevice')
log_user_id = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL, verbose_name='User ID')
log_user_email = models.CharField(max_length=500, verbose_name='User Email',default='admin')
feature_name = models.CharField(max_length=100, verbose_name='Feature Name',default='default_feature')

class Meta:
    verbose_name = 'Implementation/Backout Logs'
    verbose_name_plural = 'Implementation/Backout Logs'

def __unicode__(self):

    return '%s %s %s %s %s' % (self.log_id,self.device_name,self.log_user_id,self.log_user_email,self.feature_name)

Not sure how to successfully POST the data with User into the ModelViewSet.

A: Probably, your user is Django User model instance, which is not JSON serializable:
data_params = {
        "log_user_id": user, # <-- here

data=json.dumps(data_params) # <-- here

You should put user.pk in data_params:
data_params = {
        "log_user_id": user.pk, # <-- here


text:
Q: C null terminator's throught char* correct handelling This question is aimed at improving my understanding of
what I can and cannot do with pointers when allocating and freeing:
The bellow code is not meant to run, but just set up a situation for the questions bellow.
char *var1  = calloc(8,sizeof(char));
char **var2 = calloc(3,sizeof(char*));

var1 = "01234567";

var1[2] = '\0';
var1[5] = '\0';

//var1 = [0][1][\0][3][4][\0][6][7]

var2[0] = var1[0];
var2[1] = var1[3];
var2[2] = var1[6];

free(var1);
free(var2);

given the following snippet
1: is it ok to write to a location after the \0 if you know the size you allocated.
2: Can I do what I did with var2 , if it points to a block that another pointer is pointing at?
3: are the calls to free ok? or will free die due to the \0 located throughout var1.
I printed out all the variables after free, and only the ones up to the first null got freed (changed to null or other weird and normal looking characters). Is that ok?
4: Any other stuff you wish to point out that is completely wrong and should be avoided.

Thank you very much.

A: Question 4 - what's wrong
You 'calloc' some memory and store a pointer to it in var1.  Then later you execute var1 = "01234567" which stores a pointer to a literal string in var1, thus losing the calloc'd memory. I imagine you thought you were copying a string. Use strcpy or similar.
Then you write zero values into what var1 points to. Since that's a literal string, it may fail if the literal is in read-only memory. The result is undefined.
free(var1) is not going to go well with a pointer to a literal. Your code may fail or you may get heap corruption.

A: Pointers don't work this way.
If someone wrote
int a = 6*9;
a = 42;

you would wonder why they ever bothered to initialise a to 6*9 in the first place — and you would be right. There's no reason to. The value returned by * is simply forgotten without being used. It could be never calculated in the first place and no one would know the difference. This is exactly equivalent to
int a = 42;

Now when pointers are involved, there's some kind of evil neural pathway in our brain that tries to tell us that a sequence of statements that is exactly like the one shown above is somehow working differently. Don't trust your brain. It isn't.
char *var1  = calloc(8,sizeof(char));
var1 = "01234567";

You would wonder why they ever bothered to initialise var1 to calloc(8,sizeof(char)); in the first place — and you would be right. There's no reason to. The value returned by calloc is simply forgotten without being used. It could be never calculated in the first place and no one would know the difference. This is exactly equivalent to
char* var1 = "01234567";

... which is a problem, because you cannot modify string literals.
What you probably want is
char *var1  = calloc(8, 1);     // note sizeof(char)==1, always
strncpy (var1, "01234567", 8);  // note not strcpy — you would need 9 bytes for it

or some variation of that.

A: Ok, let's just just recap what you have done here:
char *var1  = calloc(8,sizeof(char));
char **var2 = calloc(3,sizeof(char*));

So var1 is (a pointer to) a block of 8 chars, all set to zero \0.
And var2 is (a pointer to) a block of 3 pointers, all set to NULL.
So now it's the program's memory, it can do whatever it wants with it.
To answer your questions specifically ~
It's quite normal to write characters around inside your char block.  It's a common programming pattern to parse string buffers by writing a \0 after a section of text to use everyday C string operations on it, but then point to the next character after the added \0 and continue parsing.
var2 is simply a bunch of char-pointers, it can point to whatever char is necessary,  it doesn't necessarily have to be at the beginning of the string.
The calls to free() are somewhat OK (except for the bug - see below).  It's normal for the content of free()d blocks to be overwritten when they are returned to the stack, so they often seem to have "rubbish" characters in them if printed out afterwards.
There is some issues with the assignment of var1 ~
var1 = "01234567";

Here you are saying "var1 now points to this constant string".  Your compiler may have generated a warning about about this.  Firstly the code assigns a const char* to a char* (hard-coded strings are const, but C compilers will only warn about this [EDIT: this is true for C++, not C, see comment from n.m.]).  And secondly, the code lost all references to the block of memory that var1 used to point to.  You can now never free() this memory - it has leaked.   However, at the end of the program, the free() is trying to operate on a pointer-to a block of memory (the "01234567") which was not allocated on the heap.  This is BAD.  Since you're exiting immediately, there's no ill-effects, but if this was in the middle of execution, the next allocation (or next 1000th!) could crash weirdly.  These sorts of problems are hard to debug.
Probably what you should have done here (I'm guessing your intention though) is used a string copy:
strncpy(var1, "01234567", 8);

With that operation instead of the assignment, everything is OK.  This is because the digits are stored in the memory allocated on line1.

A: var1 = "01234567"; is not correct because you assign a value of pointer to const char to a pointer to mutable char and causes a memory leak because the value of pointer to a calloc allocated buffer of 8 char stored in variable var1 is lost. It seems like you actually intended to initialize allocated array with the value of the string literal instead (though that would require allocation of an array of 9 items). Assignment var1[2] = '\0'; causes undefined behavior because the location var1 points to is not mutable. var2[0] = var1[0]; is wrong as well because you assign a value of char to pointer to char. Finally free(var1); will try to deallocate a pointer to buffer baking string literal, not something you allocated.


text:
Q: Does using more packages increase the size of the .tex file and pdf? I'm curious about this question, since I've seen people using tens of packages in the preamble. Does including many packages increase file size? If not, then why not?

A: Most packages do not directly affect the PDF at all, they just define additional commands.
Some do, eg if you add \usepackage{color} then colour support is enabled in the resulting PDF, and the document is initialised (usually to black) and the default document colour is automatically inserted in page headings etc. This has an effect on the PDF even if \color is not used.
But it does affect the run time.
\documentclass{article}
\begin{document}
aaa bbb
\end{document}

takes an average 0m 1.321s according to time command on this machine.
\documentclass{article}
\usepackage{tikz}
\begin{document}
aaa bbb
\end{document}

takes an average 0m 2.328s  so a second longer, almost twice the time. And that is just adding one package (admittedly one of the slowest to load).
But the real reason for not loading multiple packages is that it makes debugging massively more complicated.  A large proportion of questions on this site are of the form "Why does LaTeX do some strange thing" and eventually the answer comes down to "Because you loaded hundreds of conflicting definitions for no reason and were running latex in a mode that had never been tested or intended".
Don't start a new document by copying the preamble used last time and just adding more stuff; otherwise after a few years your documents will be totally unmaintainable. Start with an empty preamble and just add packages that are needed.


text:
Q: Is guaranteed that class members are disposed at the time that the class is disposed I have the following situation:
I have class A that contains a stack member object from class B:
Class A{
    B b;
}

I am using B object to redefine the behavior of the initialization and destruction of A.
Class B{
    B(){cout<<"taken care of some specific context initialization"<<endl;}
    ~B(){cout<<"cleaning the context initialization done before"<<endl;}
}

This is working so far because ~B() is being called when b is destroyed (I guess it is done after A destructor).
This is the behavior I am looking for, but I am scared about the possibility of the compiler saying: "Hey, you are not using the object, I am going to reclaim the memory before". I guess it should to happen, but is it possible in any compiler? I mean, is it set on the standard that you have to wait for A to be destroyed?
Thanks in advance

A: C++ follows an as-if behavior, meaning it is theoretically possible for b to be destroyed before as long as the behavior of the program isn't affected. And if it isn't affected, it doesn't really matter when it is destroyed.
In practice though, b will be destroyed right after the destructor of its owner A instance will be destroyed.
It is guaranteed by:
12.4 Destructors [class.dtor]

8) After executing the body of the destructor and destroying any
  automatic objects allocated within the body, a destructor for class X
  calls the destructors for X's direct non-variant non-static data
  members, the destructors for X's direct base classes and, if X is the
  type of the most derived class (12.6.2), its destructor calls the
  destructors for X's virtual base classes. [...] (emphasis mine)

Note that an implementation whose observable behavior acts as-if this was happening is still standard-compliant. In your particular case, since the destructor has IO operations, it's guaranteed that this behavior actually takes place.


text:
Q: Android Google Map - how to display all address of matching location? I have a form in which user will type his address but i want to create such widget for address so that whenever user types his address, then all similiar location will be listed in the suggestion box and user can select his location.
Similiar functionality i have seen in google map navigation application.
Can you please tell me how create such feature?

A: If you are talking about matching places for a street address, this should work:

*

*use reverse geocoding to convert it into (latitude, longitude) pair, both Android itself and Google API provides this service;

*use Google Places API to obtain nearby places using the pair of coordinates
I have a project which actually does the similar job, while due to some reasons it is not public, but I can assure you this way could work.
Hope it helps.


text:
Q: Expected length of a sequence The following problem has kept me pondering for a while now and since I can't get through, I'm posting it here.
Say that you can draw a number $x_i$ uniformly from the set $\mathcal{X} \sim \{0,0,1,2,3,4,5,6\}$. The sum of those numbers we call $X$. We stop drawing numbers when $X$ is at least $5$, the amount of numbers drawn we will call $N$. I would write the stopping condition as:
$$X = \sum_{i=0}^{N}x_i \geq 5 $$
What is the expected value of numbers we need to draw, $E[N]$?
I'll attempt some visualisations based on empirical outcomes.

A: Define the function $h(x)=\mathbb{E}_x(N)$ to be the expected number of steps needed, if we start with a sum of $x$. First step analysis gives
\begin{eqnarray*}
h(4)&=&1+h(4)/4 \\
h(3)&=&1+h(3)/4+h(4)/8\\
h(2)&=&1+h(2)/4+h(3)/8+h(4)/8\\
h(1)&=&1+h(1)/4+h(2)/8+h(3)/8+h(4)/8\\
h(0)&=&1+h(0)/4+h(1)/8+h(2)/8+h(3)/8+h(4)/8.
\end{eqnarray*}
Solving this system we get  $E(N)=h(0)={2401\over 972}\approx 2.47.$

A: It is possible to solve a more general problem. We are looking for $$N(t)=\min \left\{ n : \sum_{i=1}^n x_i >t\right\}.$$
Now set $$m(t)=\mathbb{E}[N(t)]$$
We can condition on $x_1$ to obtain
$$m(t)=\cases{ 1 & if $\quad x_1\ge t$\cr
        m(t-x_1) & if $\quad x_1<t$\cr}$$
We know also that $$\begin{align}m(t)=\mathbb{E}[\mathbb{E}[N(t)|x_1]]&=\sum_{i=0}^{t-1} m(t-i)\mathbb{P}(x_1=i)+\sum_{i=t}^6\mathbb{P}(x_1=i)\\ &=p\sum_{j=1}^{t} m(j)+(6-t)p\end{align}$$
Where, for brevity and because $x_i$ is uniform, we have written $p$ for $\mathbb{P}(x_1=i)$
Assume we know the expressions for all $m(j)$ with $j=1,...,k$, then
$$\begin{align}m(k+1)&=p\sum_{j=1}^{k+1} m(j)+(6-k-1)p\\ &= pm(k+1)+p\sum_{j=1}^{k} m(j)+(6-k-1)p \\ &\Rightarrow m(k+1)=\frac{p}{1-p}\sum_{j=1}^{k} m(j)+(6-k-1)\frac{p}{1-p}\end{align}$$
We can calculate $m(1)$ from the recursion, namely
$$m(1)=p m(1)+5p\Rightarrow m(1)=\frac{5p}{1-p}$$
Now
$$m(2)=\frac{p}{1-p}\frac{5p}{1-p}+(6-1-1)\frac{p}{1-p}=5\left(\frac{p}{1-p}\right)^2+4\frac{p}{1-p}$$
$$m(3)=5\left(\frac{p}{1-p}\right)^3+9\left(\frac{p}{1-p}\right)^2+3\frac{p}{1-p}$$
$$m(4)=5\left(\frac{p}{1-p}\right)^4+14\left(\frac{p}{1-p}\right)^3+12\left(\frac{p}{1-p}\right)^2+2\left(\frac{p}{1-p}\right)$$
And finally
$$m(5)=5\left(\frac{p}{1-p}\right)^5+19\left(\frac{p}{1-p}\right)^4+26\left(\frac{p}{1-p}\right)^3+14\left(\frac{p}{1-p}\right)^2+\frac{p}{1-p}$$


text:
Q: Target an Element whose Width Wasn't Defined Explicitly in CSS
Possible Duplicate:
Detecting width: auto in jQuery

Using jQuery, how do we find out
s whose width had not been explicitly set up in CSS, regardless inline  or non-inline. For example:
#outer-box {
  width: 100px;
}
#inside-box {
  /* width isn't set explicitly. */
  background-color: #000;
}

...

I'd like to get a hold of only the div#inside-box based on the fact its width wasn't explicitly defined via the CSS.


text:
Q: Extend query to include Parent Ids I have the following SQL statement -
SELECT
    gen_id, gen_name, COUNT(*)
FROM
    table
WHERE
  parent_id in (1,2,3,4)
GROUP BY
    gen_id, gen_name
HAVING
    COUNT(*) > 1

This works a treat and brings back the following result -
+--------+----------+------------------+
| gen_id | gen_name | (No column name) |
+--------+----------+------------------+
|      1 | test1    |                2 |
|      2 | test2    |                4 |
|      6 | test6    |                2 |
|      9 | test9    |                2 |
+--------+----------+------------------+

My question being is, the only one of the above results I can determine which parents it has is test2 as it has a count for all four parent_id's. How can I modify my SQL to bring back a result set whereby I can see which parent ids belong to which gen_ids.
Results something like -
+--------+----------+-----------+
| gen_id | gen_name | parent_id |
+--------+----------+-----------+
|      1 | test1    |         1 |
|      1 | test1    |         2 |
|      2 | test2    |         1 |
|      2 | test2    |         2 |
|      2 | test2    |         3 |
|      2 | test2    |         4 |
|      6 | test6    |         3 |
|      6 | test6    |         4 |
|      9 | test9    |         2 |
|      9 | test9    |         4 |
+--------+----------+-----------+

A: One way to do it is using exists:
SELECT
    gen_id, gen_name, parent_id
FROM
    table AS t0
WHERE
  parent_id in (1,2,3,4)
AND EXISTS
(
    SELECT 1
    FROM table AS t1
    WHERE t0.gen_Id = t1.gen_id
    AND t0.parent_id != t1.parent_Id
)

Another option would be to use a cte:
WITH CTE AS
(
    SELECT
        gen_id, gen_name, parent_id, COUNT(*) OVER(PARTITION BY gen_id) As cnt
    FROM
        table
    WHERE
      parent_id in (1,2,3,4)
)

SELECT gen_id, gen_name, parent_id
FROM CTE
WHERE cnt > 1

A: simple remove count and group by
SELECT
   gen_id, gen_name, parent_id
FROM
   table
WHERE
   parent_id in (1,2,3,4)


text:
Q: How to give unique SESSION id to each  in PHP Ok, I want to know how to generate unique $_SESSION name or ID and set it to each table row in members.php file, so when I click to any row in this file it will redirected to another file named details.php that reads the details from MySQL according to that row( in my code the details of 'member') and prints out it.
members.php:
<?php session_start();?>

<?php
  include 'connect.php';/*make connection to MySQL*/
  $stmt=$mysqlConnect->query('SELECT name, phone FROM members');
  foreach($stmt as $row)
  {
    $name = $row['name'];
    $_SESSION['name'] = $name;/*HELP: this is where I am strugling*/
    /*the value of $_SESSION['name'] is changes each time in loop.*/
    /*So, it works only for last row of table named 'members' */
    /*in MySQL database.*/
?>

    <?php echo $row['name']?>
    <?php echo $row['phone']?>
    <?php
      }/*end of froeach function*/
      mysqlConnect=null;/*disconnect mysql*/
    ?>

details.php
<?php
  session_start();
  include "connect.php";
  $name = $_SESSION['name']/*HELP: */
  $stmt = $mysqlConnect->query("SELECT * FROM members WHERE name = Sname");

  foreach($stmt as $row)
  {
    echo $row['name'];
    echo $row['adress'];
    echo $row['mail'];
    echo $row['phone'];
    echo $row['car'];
    echo $row['credit'];
    echo $row['workDay'];
  }
?>

A: You could make an array out of $_SESSION['name'], but it will not solve your problem. There is only one set of session information per session (per browser, not per tab), so when opening the details, you would still need to know which one was clicked by passing some information in the request (get/querystring or post information).
Using that information, you could set the right name again in the session, but that could cause a side effect: When you open member A in a new tab, the session name is set to A. Then you open member B in other new tab and the session name is set to B. Because the session is shared between all tabs in the browser, refreshing the details of member A would now suddenly result in the details of member B.
So it's better to just pass the name in the url, and show the details based on that. Alternatively, you could post the information, but for that you need more javascript and/or an html form, both of which will make things more complex than needed.
So, instead of setting the session information or posting data, you can simply pass the name (or an id) into the url when you click it. Notice the addition of urlencode to make the url valid even if there are special characters in the name.

<?php
  include 'connect.php';/*make connection to MySQL*/
  $stmt=$mysqlConnect->query('SELECT name, phone FROM members');
  foreach($stmt as $row)
  {
?>
 <tr onclick="window.document.location='details.php?name=<?php echo urlencode($row['name'])?>';">
    <?php echo $row['name']?>
    <?php echo $row['phone']?>
<?php
  }/*end of foreach function*/
  mysqlConnect = null;/*disconnect mysql*/
?>

In the other page, you can read the value from the $_GET superglobal. With some additional checks, your page may look like this. I've made some additions to make reading from the database safer. I assumed you are using MySQLi. If not (PDO or a custom class), you may need to make some changes.
<?php
  include "connect.php";

  // Check, if no name was given, someone visited the page directly.
  // Redirect to the member list in that case.
  if (!isset($_GET['name'])) {
    header('Location: members.php');
    exit;
  }

  $name = $_GET['name'];

  // Use a prepared statement. This is safer, otherwise people could secretly
  // enter pieces of malicious SQL into the 'name' querystring.
  $stmt = $mysqlConnect->prepare(
    "SELECT
      name, address, mail, phone, car, credit, workDay
    FROM members WHERE name = ?");
  $stmt->bind_param('s', Sname);

  $result = $stmt->execute();

  // You can bind result parameters too. This will fetch each row directly
  // into these variables.
  $stmt->bind_result($name, $address, $mail, $phone, $car, $credit, $workDay);

  while ($stmt->fetch()) {
    echo $name;
    echo $address;
    echo $mail;
    echo $phone;
    echo $car;
    echo $credit;
    echo $workDay;
  }
?>

A: I understand your problem and better solution is avoid using session and use GET to pass value to details.php

<?php
    foreach($stmt as $row)
    {
    $name = $row['name'];
    ?>
    <tr onclick="window.document.location='details.php?name=<?php echo $name;  ?>';">
    <?php echo $row['name']?>
    <?php echo $row['phone']?>
    <?php
    }/*end of froeach function*/
    mysqlConnect=null;/*disconnect mysql*/
    ?>

then for details.php

$name = $_GET['name']  /* Use $_GET instead of session */


text:
Q: Bitmap myBitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length); gives dimension 0 Am trying to decode the bitmap using BitmapFactory,but it gives me height and width of output bitmap equal to 0.Could some help me out.My code is as follows.
 Bitmap myBitmap = BitmapFactory.decodeByteArray(bFile, 0, bFile.length);
 System.out.println("heigth => "myBitmap.getHeight() + "  width  => " + myBitmap.getWidth());

where bFile is the byte array generated from .ico file.
Thanks in advance!!!

A: try to do as follows
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile("/sdcard/image.png", options);
int width = options.outWidth;
int height = options.outHeight;


text:
Q: Linux software raid 1 - can more than two devices be used? I have a batch of linux servers using software raid 1 that need to have both disks swapped.  While this can be done one disk at a time, I'd like to know if it is possible to do both at once with a process like the following, to reduce the outages needed:
1) connect new drives via USB
2) Add both new drives to the array, rebuilding data to them
3) install grub on new drives
4) shutdown and swap drives
This plan requires the ability to mirror the information in the aray across 4 devices, and a quick test shows that mdadm makes all devices after the first two in a RAID 1 aray spare disks.  Is there anyway to override this,  or do I need to go with two outages to swap disks over one-by-one?

A: Yes, you can grow a RAID-1 set to include as many drives as you like.  What you need to do is add the new drives as spares, and then run mdadm /dev/mdX --grow -n 4 (or however many devices you want to have in the set).  They'll then be synced to, and you can go play swapsies at your leisure once that's done.

A: As it has been told, you can - my answer is an extension for this fact.
I usually keep a low-profile root filesystem with low writing rate, then I spread this filesystem across all disks in the system using raid1 (typically 4 or more devices). Basically I make a 512M partition in the beginning of each disk, which serves a part for the raid1 containing the root. In this case, I can lose any disk without risking to boot the system.
You should consider this.


text:
Q: BOOST TLS connection establishment using the boost after exchange of data between server and client I want to initiate the TLS connection only if the server supports the secure connection, to achieve this i have introduced the two message type between the server and client.
Client will send SECURECONNREQ msg to server after tcp connection establishment, if the server is configured to support the TLS it send SECURECONNRESP.
On receiving SECURECONNRESP the client will initiate the the TLS handshake by calling  boost asynhandshake API but this API is not sending the correct packet(client hello). In the wireshark i could see it is sending the protocol version as TLS1.1 even if it configured for TLS1.2.
Note: SSL context object is prepared with TLS1.2, ciphers and related certs.
It looks like the asynhandshake will not work properly if there is some data exchange happens on the TCP link.
Is there extra step we need take on BOOST asio to make it work?
The secure connection establishment works perfectly fine with below implementation:
Initiating the TLS connection without sending any data on the TCP link.
The client will initiate the TLS after connection is established(no data transfered on this link) by calling asynhandshake, the server will call boost asynhandshake immediately after the connnection accept.

A: It's hard, or even impossible, to tell without seeing your actual code. But I thought it a nice challenge to write the quintessential PLAIN/TLS server/client in Asio, just to see whether there were any problems I might not have anticipated.
Sadly, it works. You may compare these and decide what you're doing differently.
If anything, this should help you create a MCVE/SSCCE to repro your issue.
Short Intro

The server accepts connections.
The client initiates a ConnectionRequest. Depending on a runtime flag
_support_tls the server responds with the SECURE capability response (or not).
The client and server upgrade to TLS accordingly.
The client and server execute a very simple protocol session that's
templated on the Stream type, because the implementations are independent of
the transport layer security.

Note, for the example I've used the server.pem from the Asio SSL examples.

The demo then executes servers both with and without SECURE capability, and
verifies that the same simple_client implementation works correctly
against both.
Listing
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/endian/arithmetic.hpp>
#include <boost/beast.hpp>
#include <boost/beast/http.hpp>
#include <iostream>
namespace http = boost::beast::http;
namespace net  = boost::asio;
namespace ssl  = net::ssl;
using boost::system::error_code;
using net::ip::tcp;

struct ConnectionRequest {
    enum { MAGIC = 0x64fc };
    boost::endian::big_uint16_t magic = MAGIC;
};
struct ConnectionResponse {
    enum Capabilities {
        NONE,
        SECURE,
    };

    boost::endian::big_uint16_t capabilities = NONE;
};

using TLSStream = ssl::stream<tcp::socket>;

template <typename> static inline char const* stream_type = "(plain)";
template <> inline char const*                stream_type<TLSStream> = "(TLS)";

static void do_shutdown(tcp::socket& s) {
    error_code ignored;
    s.shutdown(tcp::socket::shutdown_both, ignored);
}

static void do_shutdown(TLSStream& s) {
    error_code ignored;
    s.shutdown(ignored);
}

template <typename Stream>
struct Session : std::enable_shared_from_this<Session<Stream> > {
    Session(Stream&& s) : _stream(std::move(s)) {}

    void start() {
        std::cout << "start" << type() << ": " << _stream.lowest_layer().remote_endpoint() << std::endl;
        http::async_read(_stream, _buf, _req, self_bind(&Session::on_request));
    }

  private:
    Stream _stream;

    http::request<http::string_body> _req;
    http::response<http::empty_body> _res;
    net::streambuf                   _buf;

    void on_request(error_code ec, size_t) {
        std::cout << "on_request" << type() << ": " << ec.message() << std::endl;
        http::async_write(_stream, _res, self_bind(&Session::on_response));
    }

    void on_response(error_code ec, size_t) {
        std::cout << "on_reponse" << type() << ": " << ec.message() << std::endl;
        do_shutdown(_stream);
    }

    auto type() const { return stream_type<Stream>; }

    auto self_bind(auto member) {
        return [self=this->shared_from_this(), member](auto&&... args) {
            return (*self.*member)(std::forward<decltype(args)>(args)...);
        };
    }
};

struct Server {
    using Ctx = ssl::context;

    Server(auto executor, uint16_t port, bool support_tls)
        : _acceptor(executor, {{}, port}),
          _support_tls(support_tls)
    {
        if (_support_tls) {
            _ctx.set_password_callback(
                 [](size_t, Ctx::password_purpose) { return "test"; });
            _ctx.use_certificate_file("server.pem", Ctx::file_format::pem);
            _ctx.use_private_key_file("server.pem", Ctx::file_format::pem);
        }
        _acceptor.listen();
        accept_loop();
    }

    ~Server() {
        _acceptor.cancel();
    }

  private:
    void accept_loop() {
        _acceptor.async_accept(
            make_strand(_acceptor.get_executor()),
            [=, this](error_code ec, tcp::socket&& sock) {
                if (!ec)
                    accept_loop();
                else
                    return;

                // TODO not async for brevity of sample here
                ConnectionRequest req[1];
                read(sock, net::buffer(req));

                if (req->magic != ConnectionRequest::MAGIC) {
                    std::cerr << "Invalid ConnectionRequest" << std::endl;
                    return;
                }
                ConnectionResponse res[1]{{ConnectionResponse::NONE}};

                if (not _support_tls) {
                    write(sock, net::buffer(res));

                    std::make_shared<Session<tcp::socket>>(std::move(sock))
                        ->start();
                } else {
                    res->capabilities = ConnectionResponse::SECURE;
                    write(sock, net::buffer(res));

                    // and then do the handshake
                    TLSStream stream(std::move(sock), _ctx);
                    stream.handshake(TLSStream::handshake_type::server);

                    std::make_shared<Session<TLSStream>>(std::move(stream))
                        ->start();
                }
            });
    }

    tcp::acceptor _acceptor;
    Ctx           _ctx{Ctx::method::sslv23};
    bool          _support_tls;
};

// simplistic one-time request/response convo
template <typename Stream> void simple_conversation(Stream& stream) {
    http::write(stream, http::request<http::string_body>(
                http::verb::get, "/demo/api/v1/ping", 11,
                "hello world"));

    {
        http::response<http::string_body> res;
        net::streambuf                    buf;

        http::read(stream, buf, res);
        std::cout << "Received: " << res << std::endl;
    }
}

void simple_client(auto executor, uint16_t port) {
    // client also not async for brevity
    tcp::socket sock(executor);
    sock.connect({{}, port});

    ConnectionRequest req[1];
    write(sock, net::buffer(req));

    ConnectionResponse res[1];
    read(sock, net::buffer(res));

    std::cout << "ConnectionResponse: " << res->capabilities << std::endl;
    if (res->capabilities != ConnectionResponse::SECURE) {
        simple_conversation(sock);
    } else {
        std::cout << "Server supports TLS, upgrading" << std::endl;

        ssl::context ctx{ssl::context::method::sslv23};

        TLSStream    stream(std::move(sock), ctx);
        stream.handshake(TLSStream::handshake_type::client);
        simple_conversation(stream);
    }
}

int main() {
    net::thread_pool ctx;
    {
        Server plain(ctx.get_executor(), 7878, false);
        simple_client(ctx.get_executor(), 7878);
    }

    {
        Server tls(ctx.get_executor(), 7879, true);
        simple_client(ctx.get_executor(), 7879);
    }
    ctx.join();
}

Prints
ConnectionResponse: start(plain): 0
127.0.0.1:37924
on_request(plain): Success
on_reponse(plain): Success
Received: HTTP/1.1 200 OK

ConnectionResponse: 1
Server supports TLS, upgrading
start(TLS): 127.0.0.1:36562
on_request(TLS): Success
on_reponse(TLS): Success
Received: HTTP/1.1 200 OK


text:
Q: Delete .pdf files only if .xlsx files in directory have same filename? I have folders with hundreds of pdf and xls(x) files that were mass exported from legal e-discovery systems. The filenames in these exports correspond to bates # such as ABCD_00000001.pdf, ABCD_00000002.pdf, ... , ABCD_00002000.pdf. These mass exports include a blank pdf file for every single xls(x) file - with both having the exact same filename. E.g., ABCD_00000005.xlsx is the xlsx file that was produced in the ediscovery system and ABCD_00000005.pdf is an extraneous blank pdf file that was created in the mass export.
These extraneous .pdf files probably result from a user error on the part of the people running these mass exports, but I don't usually have control over that side of the process. So I wanted to know if any relatively straightforward way to delete these extraneous .pdf without forcing someone to go through them manually.

A: Loop over the pdf files, use parameter expansion to extract the basename:
#!/bin/bash
for pdf in *.pdf ; do
    basename=${pdf%.pdf}
    if [[ -f $basename.xls || -f $basename.xlsx ]] ; then
        rm "$pdf"
    fi
done

Update: I got the logic backwards, should be fixed now.

A: Loop over the .xls(x) files and remove matching pdf files.
for xls in *.xls* ; do
    /bin/rm -f "${xls%.xls*}"".pdf"
done

If there's no matching pdf it won't hurt anything.


text:
Q: how to add a new column having the value of the following line with scala dataframe I have a DATAFRAME
+----------+----------+
| longitude|  latitude|
+----------+----------+
|-7.1732833|32.0414966|
|-7.1732844|32.0414406|
|-7.1732833|32.0414966|
|-7.1732833|32.0414966|
|-7.1732833|32.0414966|
|-7.1732833|32.0414966|

expected result
 +----------+----------+-----------------+----------------------+----------------+-------------+
| longitude|  latitude| origin_longitude |destination_longitude|origine_latitude|destination_latitude
+----------+----------+ -----------------+---------------------+----------------+
|-7.1732833|32.0414966|-7.1732833        |-7.1732844           |32.0414966      |32.0414406
|-7.1732844|32.0414406|-7.1732844        |-7.1732833           |32.0414406      |32.0414966
|-7.1732833|32.0414966|-7.1732833        |-7.1732833           |32.0414966      |32.0414966
|-7.1732833|32.0414966|-7.1732833        |-7.1732833           |32.0414966      |32.0414966
|-7.1732833|32.0414966|-7.1732833        |-7.1732833           |32.0414966      |32.0414966
|-7.1732833|32.0414966|

how can i do that with scala , I'm new in scala , please help .
Thank you  .

A: You can use window function to get the next(lead) row and make a new column with, however, lead requires us to use an orderBy, and your dataframe order will not be preserved if I were to orderBy on latitude/longitude, therefore, I created a seq column manually, to preserve your order. In your real data you should have a column with helps you order.
%scala
val df=Seq(
       (1,-7.1732833,32.0414966),
       (2,-7.1732844,32.0414406),
       (3,-7.1732833,32.0414966),
       (4,-7.1732833,32.0414966),
       (5,-7.1732833,32.0414966),
       (6,-7.1732833,32.0414966)
        ).toDF("seq","longitude","latitude")

df.show()

+---+----------+----------+
|seq| longitude|  latitude|
+---+----------+----------+
|  1|-7.1732833|32.0414966|
|  2|-7.1732844|32.0414406|
|  3|-7.1732833|32.0414966|
|  4|-7.1732833|32.0414966|
|  5|-7.1732833|32.0414966|
|  6|-7.1732833|32.0414966|
+---+----------+----------+

import org.apache.spark.sql.functions.lead
import org.apache.spark.sql.functions.col

val w = org.apache.spark.sql.expressions.Window.orderBy("date").orderBy("seq")

df.withColumn("destination_longitude", lead("longitude",1,0).over(w)).withColumn("destination_latitude", lead("latitude",1,0).over(w)).select(col("longitude").alias("origin_longitude"),col("destination_longitude"),col("latitude").alias("origin_latitude"),col("destination_latitude")).filter(col("destination_longitude")!==0.0).show()

+----------------+---------------------+---------------+--------------------+
|origin_longitude|destination_longitude|origin_latitude|destination_latitude|
+----------------+---------------------+---------------+--------------------+
|      -7.1732833|           -7.1732844|     32.0414966|          32.0414406|
|      -7.1732844|           -7.1732833|     32.0414406|          32.0414966|
|      -7.1732833|           -7.1732833|     32.0414966|          32.0414966|
|      -7.1732833|           -7.1732833|     32.0414966|          32.0414966|
|      -7.1732833|           -7.1732833|     32.0414966|          32.0414966|
+----------------+---------------------+---------------+--------------------+

A: You could use df.withColumn("origin_longitude",lit(-7.1732833)) you can chain as many withColumn function as needed.


text:
Q: 2 functions that should be the same give different results I'm reading a file into a vector, to read bytes off of it. The standalone function works fine, but I don't want to open and close a file and create a vector every time i access, since im going to be grabbing lots of bytes. So I opted to put it in a file class. However, this has lead to me getting entirely different results when I use the file class.
This is a working standalone function:
template<class T>
T readFromNewFile(std::string path, size_t size = 0, uint offset = 0)
{
    std::ifstream in(path.c_str(), std::ios::binary | std::ios::ate);
    if (in.is_open())
    {
        std::streamoff max = in.tellg();
        size_t _size = size == 0 ? (size_t)max : size;
        in.seekg(offset, std::ios::beg);
        std::vector<uint> v(_size);
        in.read((char*)v.data(), _size);

        uint temp = 0;
        std::stringstream ss;
        for (uint it = 0; it < v.size(); it++)
        {
            std::cout << "readFromNewFile: Adding offset: " << offset + it << ", with value: " << v[it] << "\n";
            temp += v[it];
        }
        ss << temp;
        T myVar;
        ss >> myVar;
        return myVar;
    }
    return T();
}

The file class in question:
class File
{
public:
    File() {}
    File(std::string path)
    {
        LOAD(path);
    }
    ~File() {}
    void LOAD(std::string path)
    {
        std::ifstream in(path.c_str(), std::ios::binary | std::ios::ate);
        if (in.is_open())
        {
            std::streamoff max = in.tellg();
            size_t _size = (size_t)max;
            in.seekg(0, std::ios::beg);
            data.clear();

            data.resize(_size);
            in.read((char*)data.data(), _size);
        }
    }
    template<class T>
    T readFromVector(size_t size = 0, uint offset = 0)
    {
        uint temp = 0;
        std::stringstream ss;
        for (uint it = offset; it < (offset + size) && it < data.size(); it++)
        {
            std::cout << "readFromVector: reading offset: " << it << ", with value: " << data[it] << "\n";
            temp += data[it];
        }
        ss << temp;
        T myVar;
        ss >> myVar;
        return myVar;
    }
private:
    std::vector<uint> data;
};

The code is all called in this block:
bool ArmourManager::init()
{
    std::string armourFile = "resources\\armor.am_dat";
    Offsets::ArmourOffsets offsets;
    data.LOAD(armourFile); // data is a File object in ArmourManager class
    uint armourOffset = 0x0A;
    uint textOffset = 0x41C06;
    // armours start at offset 0x0A, increase by 0x3C for every armour in file
    // appears to end at 187390 ? 0x2DBFE
    //std::cout << "[OFFSET]\t[IDX]\t[RAR]\t[SLOT]\t[DEF]\t[SLOTS]\n";
    while (armourOffset < 0x2DBFE)
    {
        uint ind = SetMaker::readFromNewFile<uint>(armourFile, 4, armourOffset + offsets.Index);
        uint x = data.readFromVector<uint>(4, armourOffset + offsets.Index);
        std::cout << ind << " / " << x << "\n";

Console Output Here
From what i can tell with debugging, the data vector isn't being populated correctly, it's being filled with weird data.
Checking first index of both vectors
Even when I tried something like this,
std::vector<uint> x(_size);
in.read((char*)x.data(), _size);
std::cout << "x byte 0: " << x[0] << "\n";

the result is still the exact same.


text:
Q: DateTimePicker Azure Implemetation Error Hey there I' after publishing my project to azure I have used data comparison to transfer my database to the online server database but now My DateTimePicker does not work it now displayes in the top left corner and does not input data at all. When i ran the project again on the localversion it worked fine?
I found the followig errors in the console.

This has me fairly stumped. Has anyone seen anything like this before.
Azure View

Localhost View

Bundles file

file structure

A: As from the comments, the issue seemed to be originating from the scripts being included in an incorrect manner by the Bundle.
Trying with individual <Script src=""> tags explicitly will give you more control on the order of the scripts. And in this case seems to be solving the problem.
You can additionally also try splitting the js bundle into multiple bundles and try to add in order. Then check in the browser source if the ordering and result are appropriate even with the bundles. You can check the <script> tags generated by bundles and compare with your manual script tags, which work, and then alter the bundles.


text:
Q: jetty exception and failed startup I upgrade gwt version from 2.3 to 2.7 and some other modules.
maven build end successfully, but when I run in superDevMode get an exception
java.lang.IllegalArgumentException: Object of class 'com.google.gwt.dev.shell.jetty.JettyLauncher.WebAppContextWithReload' is not of type 'org.eclipse.jetty.webapp.WebAppContext'. Object Class and type Class are from different loaders.

I haven't any idea.
Using:

*

*Intellij 14

*Jetty 9.3.12.v20160915

*Spring 4.3.3.RELEASE

*Servlet API 3.1.0

[WARN] Failed startup of context c.g.g.d.s.j.WebAppContextWithReload{/,file:/home/.../modules/core-war/target/x12/},/home/.../modules/core-war/target/x12
java.lang.IllegalArgumentException: Object of class 'com.google.gwt.dev.shell.jetty.JettyLauncher.WebAppContextWithReload' is not of type 'org.eclipse.jetty.webapp.WebAppContext'. Object Class and type Class are from different loaders.
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.configure(XmlConfiguration.java:323)
at org.eclipse.jetty.xml.XmlConfiguration.configure(XmlConfiguration.java:281)
at org.eclipse.jetty.webapp.JettyWebXmlConfiguration.configure(JettyWebXmlConfiguration.java:103)
at org.eclipse.jetty.webapp.WebAppContext.configure(WebAppContext.java:468)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1237)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:717)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:494)
at com.google.gwt.dev.shell.jetty.JettyLauncher$WebAppContextWithReload.doStart(JettyLauncher.java:541)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:95)
at org.eclipse.jetty.server.handler.RequestLogHandler.doStart(RequestLogHandler.java:162)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:95)
at org.eclipse.jetty.server.Server.doStart(Server.java:282)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
at com.google.gwt.dev.shell.jetty.JettyLauncher.start(JettyLauncher.java:740)
at com.google.gwt.dev.DevMode.doStartUpServer(DevMode.java:632)
at com.google.gwt.dev.DevModeBase.startUp(DevModeBase.java:1054)
at com.google.gwt.dev.DevModeBase.run(DevModeBase.java:836)
at com.google.gwt.dev.DevMode.main(DevMode.java:413)

A: The gwt-dev.jar is on the web server classpath and it should not be. Remove the gwt-dev.jar. If it's maven, provide the scope as <scope>provided</scope> and it will not get put into the WEB-INF/libs folder. Check the WEB-INF/libs folder for gwt-dev.jar and remove it if need be.

A: I removed gwt-dev.jar from my WEB-INF/lib and add a dependency to this jar file by add a path inside classpath of my ant
        <java classname="com.google.gwt.dev.DevMode" dir="core-war/target/" failonerror="false" fork="true">
        <classpath>
            <path refid="project.source.path"/>
            <path refid="project.class.path"/>
            <path location="${basedir}/build-conf/lib/ojdbc-11g-1.6.jar" />
            <path location="${mvn.repo.dir}org/netezza/nzjdbc/4.6/nzjdbc-4.6.jar" />
            <path location="${mvn.repo.dir}/com/google/gwt/gwt-dev/${gwt.version}/gwt-dev-2.7.0.jar" />
        </classpath>


text:
Q: intentService to activity using LocalBroadcastManager I have been trying to use LocalBroadcastManager but it does not seem to work. Basically I want my intentService to broadcast an intent whenever it's running.
I then want my activity to receive the broadcast whenever the user is actively using the activity.
I tried to follow the instructions here:
how to use LocalBroadcastManager?
but it does not work for some reason. I don't get any log entry for the receiver being called.
Here is the relevant part of my code:
public class MainActivity extends Activity {
  // Debug log tag
  private static final String tag = "PhoneControlMainActivity";

  // Broadcast receiver
  PhoneControlBroadcastReceiver receiver;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // Register the receiver with the local broadcast manager
    receiver = new PhoneControlBroadcastReceiver();
    LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter(PhoneControlBroadcastReceiver.SERVICE_OUTPUT));

    // Start IntentService
    try {
      serviceName = startService(new Intent(this, PhoneControlIntentService.class));
    }
    catch(SecurityException e)
    {
      Log.d(tag,"SecurityException occured when starting IntentService: "+ e.getMessage());
      return;
    }

    if(serviceName != null) {
      Log.d(tag,"serviceName NOT NULL");
    }
    else {
      Log.d(tag,"serviceName NULL");
    }
  }
}

public class PhoneControlIntentService extends IntentService  {
  public PhoneControlIntentService() {
    super("PhoneControlIntentService");
  }

  @Override
  protected void onHandleIntent(Intent intent) {
    Intent msgIntent = new Intent(PhoneControlBroadcastReceiver.SERVICE_OUTPUT);
    msgIntent.putExtra("message", "This is my message!");
    LocalBroadcastManager.getInstance(this).sendBroadcast(msgIntent);
  }
}

public class PhoneControlBroadcastReceiver extends BroadcastReceiver{
  // Action
  public static final String SERVICE_OUTPUT = "com.axr0284.phonecontrol.SERVICE_OUTPUT";

  @Override
  public void onReceive(Context context, Intent intent) {
    Log.d(tag,"onReceive called");
  }
}

Any help would be highly appreciated?
Thanks
Amish

A: A LocalBroadcastManager can't broadcast outside of it's own process.

A: Here is what I did wrong, my service declaraion in the AndroidManifest.xml had this line
android:process=":PhoneControlIntentService_process"
<service
    android:name=".PhoneControlIntentService"
    android:label="@string/IntentService_name"
    android:process=":PhoneControlIntentService_process"**
    android:exported="false"/>

This is supposed to start the service as a separate process. I guess somehow it prevented the localBroadcastManager to send the intent correctly. I don't quite understand it but when I removed that line, it started working.


text:
Q: Using MockFor, how to verify that a method was invoked at least n times? When using MockFor, how can I get it to verify that a method was invoked at least n times? I've tried ignoring the method call after setting up a demand, like this:
import groovy.mock.interceptor.MockFor;
import org.junit.Test

class FilterTest {

    interface Filter {
        boolean isEnabled()
    }

    @Test
    public void test() {
        MockFor mockContext = new MockFor(Filter)

        // Expect at least one call
        mockContext.demand.isEnabled {true}
        mockContext.ignore.isEnabled {false}

        // Obtaining a usuable mock instance
        def filter = mockContext.proxyInstance()

        // Fake calling the method
        filter.isEnabled()
        filter.isEnabled()

        // Verify invoked at least once?
        mockContext.verify(filter)
    }
}

However, I get an assertion failure:
junit.framework.AssertionFailedError: verify[0]: expected 1..1 call(s) to
'isEnabled' but was called 0 time(s).

A: You can't combine "demand" and "ignore" in that way, since the "ignore" statement overrides the "demand" statement.
Instead, you can specify the valid range like this:
mockContext.demand.isEnabled(1..10) {true}

which will accept 1 to 10 number of invokations (but not zero or eleven or more).
I'm not aware of any way to specify an open ended upper bound in ranges, though, which you imply that you need when you say "at least n times".
In most practical situations, I believe you can get away with specifying a sufficiently large upper bound (like 100).
EDIT: Removed the "hack" suggestion (it didn't work as I expected)


text:
Q: How to Label the "Outliers" in the box plot when there are many values which equals the outlier?
Please refer the box plot picture above .I Want to label only the outliers.
I use the below code to make a label column to label the outlier.
outliers_price = boxplot(Ready_to_work_data$median_price ~
Ready_to_work_data$Regionname,plot=FALSE)$out
Ready_to_work_data$lable_price <- ifelse(Ready_to_work_data$median_price %in%
outliers_price, Ready_to_work_data$median_price, "")

Now when I use the code geom_text(aes(label= lable_price)), I see the below plot (plot2) where all the matching values are highlighted many of which aren't outliers. How do I resolve this ?

A: Since there is no data provided in the question, it's hard to reproduce the needed plot. But here is one solution for tagging the overlapping outliers with non-overlapping labels. The labels will not overlap when the points overlap because ggstatsplot uses ggrepel in the backdrop.
library(ggstatsplot)

ggbetweenstats(
  data = movies_long,
  x = genre,
  y = rating,
  plot.type = "box",
  outlier.tagging = TRUE,
  outlier.label = title,
  outlier.coef = 2,
  messages = FALSE
)

Created on 2018-10-17 by the reprex package (v0.2.1.9000)


text:
Q: Foor loop prints all elements, but when result is saved in pandas dataframe it returns NaN I have the following scraping script, I need to get elements inside a "items2" foor loop.
The script is printing all elements, but later on dataframe returns "name" and "tPlan" as NaN. Any idea why?
import requests
import json
import csv
import sys

from bs4 import BeautifulSoup

base_url = "xxxx"
username = "xxxx"
password = "xxxx"
toget = data

allowed_results = 50
max_results = "maxResults=" + str(allowed_results)
tc = "/testcycles?"

result_count = -1
start_index = 0

df = pd.DataFrame(
  columns=['id', 'name', 'gId', 'dKey', 'tPlan'])

for eachId in toget['TPlan_ID']:
   while result_count != 0:
      start_at = "startAt=" + str(start_index)
      url = url = f'{base_url}{eachId}{tc}&{start_at}&{max_results}'
      response = requests.get(url, auth=(username, password))
      json_response = json.loads(response.text)
      print(json_response)
      page_info = json_response["meta"]["pageInfo"]
      start_index = page_info["startIndex"] + allowed_results
      result_count = page_info["resultCount"]
      items2 = json_response["data"]
      print(items2)

      for item in items2:
          print (item["id"])
          print (item["fields"]["name"])
          print (item["fields"]["gId"])
          print (item["fields"]["dKey"])
          print (item["fields"]["tPlan"])

          temporary_df = pd.DataFrame([item], columns=['id', 'name', 'gId', 'dKey', 'tPlan'])
          df = df.append(temporary_df, ignore_index=True)

A: TLDR
Use this for loop.
for item in items2:
    df = df.append({'id': item['id'], **item['fields']}, ignore_index=True)

Explanation
I am making this assumption that the items2 would look something like this.
items2 = [
    { 'id': 0, 'fields': {'name': 'prop1', 'gId': 100, 'dKey': 'key1', 'tPlan': 'plan1'}},
    { 'id': 1, 'fields': {'name': 'prop2', 'gId': 200, 'dKey': 'key2', 'tPlan': 'plan2'}},
    { 'id': 2, 'fields': {'name': 'prop3', 'gId': 300, 'dKey': 'key3', 'tPlan': 'plan3'}},
]

You can't create your intended data frame since the structure of item is like this.
{'id': 2, 'fields': {'name': 'prop3', 'gId': 300, 'dKey': 'key3', 'tPlan': 'plan3'}}

which results in temporary_df filled with NaN.
   id name  gId dKey tPlan fields
0   0  NaN  NaN  NaN   NaN   key1
1   0  NaN  NaN  NaN   NaN    100
2   0  NaN  NaN  NaN   NaN  prop1
3   0  NaN  NaN  NaN   NaN  plan1
4   1  NaN  NaN  NaN   NaN   key2
5   1  NaN  NaN  NaN   NaN    200
6   1  NaN  NaN  NaN   NaN  prop2
7   1  NaN  NaN  NaN   NaN  plan2
8   2  NaN  NaN  NaN   NaN   key3
9   2  NaN  NaN  NaN   NaN    300
10  2  NaN  NaN  NaN   NaN  prop3
11  2  NaN  NaN  NaN   NaN  plan3

What you would need to pass as argument to pd.DataFrame is a dict structure like
{'id': 2, 'name': 'prop3', 'gId': 300, 'dKey': 'key3', 'tPlan': 'plan3'}

Notic the missing fields dict here, all the key value pair from fields are added to item. Using this altered dict would result in  temporary_df like
  id   name  gId  dKey  tPlan
0  0  prop1  100  key1  plan1
1  1  prop2  200  key2  plan2
2  2  prop3  300  key3  plan3

To make this change in item structure you should do this
new_item = {'id': item['id']}
for key, value in item['fields'].items():
    new_item[key] = value

But you can write this concisely by using the unpacking operator **
new_item = {'id': item['id'], **item['fields']}

Now we can use pass new_item as argument to pd.DataFrame.
temp_df = pd.DataFrame({ 'id': item['id'], **item['fields']}, index=(i,)) # i here is the row index of the DataFrame

After making these changes your for loop should look something like this
for i, item in enumerate(items2):
    new_item = {'id': item['id'], **item['fields']}
    temp_df = pd.DataFrame(new_item, index=(i,))
    df = df.append(temp_df, ignore_index=True)

We can make this a bit more concise by directly passing the new_item to pd.DataFrame.append
Thus in the end this code should work.
for item in items2:
    new_item = {'id': item['id'], **item['fields']}
    df = df.append(new_item, ignore_index=True)


text:
Q: Symfony 4.2.3 - Set ManyToOne Id when user register with email domain My page
User entity :
<?php
s
namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use App\Validator\Constraints as AssertPerso;

/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 * @ORM\Table(name="app_user")
 */
class User implements UserInterface
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\ManyToOne (targetEntity="Formation")
     */
    private $customerName;

    public function getId(): ?int
    {
        return $this->id;
    }

    /**
     * @return CustomerName
     */
    public function getCustomerName()
    {
        return $this->customerName;
    }

    public function setCustomerName($customerName): self
    {
        $this->customerName = $customerName;
        return $this;
    }

}

Formation entity :
<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\FormationRepository")
 */
class Formation
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=180, unique=true)
     */
    private $customerName;

    public function getId(): ?int
    {
        return $this->id;
    }

    /**
     * @return CustomerName
     */
    public function getCustomerName()
    {
        return $this->customerName;
    }

    public function setCustomerName($customerName): self
    {
        $this->customerName = $customerName;

        return $this;
    }

    public function __toString()
    {
        return $this->customerName;
    }

}

and my form UserType :
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('customerName', null, array(
                'label'    => 'Client ',
                'required' => true)
        )
        ->add('submit', SubmitType::class, ['label_format' => "Register", 'attr'=>['class'=>'btn-primary btn-block']]);

    $builder->addEventListener(
        FormEvents::PRE_SET_DATA,
        array($this, 'preSetData')
    );
}

public function preSetData(FormEvent $event)
{

    $form = $event->getForm();
    $user = $event->getData();

         // $form->remove('customerName');

    $user->setEnabled(true);
}

In my database "formation", I have customer_name "xxx".
I want, when the user register, set the customer_name_id in my table "user" with the domain of the email if this email is like "xxxx" and if the domain of this email does not correspond with the customer_name, display error
Can you help me please ? Thank you

edit with Rebru response :
I succeeded to make the custom validator to check if the domain is an existing domain in "formation"
public function validate($value, Constraint $constraint)
{
    $mailParts = explode('@', $value);
    $mailParts = explode('.', $mailParts[1]);
    $domain = $mailParts[0];

            if(!$this->entityManager->getRepository(Formation::class)->findBy(array('customerName' => $domain))){
                $this->context->buildViolation($constraint->messageWrongDomain)
                    ->setParameter('{{ value }}', $this->formatValue($value))
                    ->setCode(Email::INVALID_FORMAT_ERROR)
                    ->addViolation();
                return;
            }
}

But now I do not know how to set the customer_name_id automatically when the user registers ?
Thank you
Edit 2 :
I just tried that for set the customer_name_id in user table.
In my UserController :
$mailParts = explode('@', $user->getEmail());
            $mailParts = explode('.', $mailParts[1]);
            $domain = $mailParts[0];

            $customerNameId = $entityManager->getRepository(Formation::class)->findBy(array('customerName' => $domain));

            $customerNameId = $customerNameId[0]->getId();

I get the following error:
Expected value of type "App\Entity\Formation" for association field "App\Entity\User#$customerName", got "integer" instead.

A: Ok, then your design is wrong - btw. i would suggest never use of manytomany over strings.
The right path to achieve this is to use custom validators ... like described here: https://symfony.com/doc/current/validation/custom_constraint.html
Short:

*

*table with all customers ( id, name, formation_id)

*table with all formations ( id, name, domain )

In the custom validator, you can split the customers email ( explode("@", $email) ) and check this against the domains in the formation table. If it match, the validator should return true otherwise false. If the validator is true, you can save the customer.
With this approach the form will never be valid, until it matches the custom validator.


text:
Q: Get page that displays all children of taxonomy parent I created a Taxonomy called articleTopics. The taxonomy has two parent terms, and the same six children terms for each. I have to link to a page which shows all children of either parent term.
For clarification:
navigating to bla.com/articletopics/testchild works.
navigating to bla.com/articletopics only renders index.php (neither page-articletopics, nor taxonomy-articletopics, nor archive-articletopics seems to work).
Of course I could create a page template and assign it to a page that I can render to achieve this. But before I do, I wanted to find out if there is a Wordpress-native way to do this, or whether I am appproaching this incorrectly.


text:
Q: Haskell, how to initialize type list, where you define the contents, and also add some initial contents Sorry if this is a dumb question, I'm just a bit confused on what syntax to use.
Say I have a type list defined as the following:

type myList = [(String, Int)]

But say I want to initialize some contents in the list for example ("test", 2), would that be possible to do on the same line that I initialized myList?
One thing I tried was just initializing it like how you'd normally do so with an ordinary list:
type myList = [(String, Int)] = [("test", 2)]
but this gave me a parse on =, but I don't know any other way to do it.

A: Define variables of a type on an extra line:
type MyList = [(String, Int)]

myList :: MyList -- optional type declaration
myList = [("test", 2)]


text:
Q: Drive SDK: locating files in directories I am using the Google Drive SDK to implement cloud storage for my iOS app.  One thing I'm unclear on from the docs is how to query for files deep in the Drive directory structure.
I can make a query like:
title = 'TheFileTitle' and '1234567' in parents
But how to I find the fileID '1234567'?  I am creating a directory structure to store my data in the cloud but I only know the subdirectory's name.  How do I get the fileID that is needed for this query?
I could query for that directory and look for the fileID in the metadata but that just raises the question again.  That directory name may not be unique so I would have to know its parent's fileID to locate the correct one.
Any help clarifying this would be appreciated.

A: Drive offers very little in the way of folder tree navigation. This is for the very good reason that folders are simply labels attached to files, rather than a strict hierarchy. So for example a file can have two or more parent folders. Although I've never tried it (I'm frightened it would create a black hole and universe would end) it's possible to create a loop where folder-A has child folder-B has child folder-C has child folder-A. Please don't try this at home, kids.
So the answer to your question, is start by querying for all folders and follow their parent arrays to build up an in-memory hierarchy. Then use that to navigate to a given file.
I would also suggest that you ask yourself the question whether deeply nested folders is a good idea. The answer may well  be 'yes', but you should at least consider alternatives. Remember, folders were an afterthought in Drive, so might not be all they seem.


text:
Q: restkit - having trouble mapping relationships... or something Setup - using RestKit, along with it's abilities to store data in a CoreData store.
I'm trying to perform two separate GET operations:
issue/:issueId  ==> this returns an Issue object, assuming one with that ID exists.
issue/:issueId/comment   ==> this returns Comment objects, belonging to the issue matching issueId.
So, for the first call, that just gets an issue back. It will only return comments back if I pass in an extra parameter on the URL. Otherwise, it won't. Of course, if I do ask for it, then the objects get created just fine, and all the objects are connected correctly in my core-data store.
The objects that I'm mapping look like this:
@interface Issue : NSManagedObject
@property (nonatomic) int32_t issueId;
@property (nonatomic, retain) NSSet* comments;
// many other fields not shown.
@end

@interface Comment: NSManagedObject
@property (nonatomic) int32_t commentId;
// many other fields not shown.
@end

Issue has a collection of Comments. Comments don't know about their owning Issue.
So, all I'm trying to do is make it possible for both of these calls to exist.
For example, in our URLs, say "issueId" is 12345. So, if I make one call to http://example.com/issue/12345, I'd like the data to be written to my CoreData store. (This works great, btw). What I would like to happen next is to call "http://example.com/issue/12345/comments", and then have those comments write to the CoreData store, and also be connected to issue-12345, that's already there. That's the part that I'm having trouble with.
If anyone could offer guidance on this, I'd really appreciate it.

A: After reading this issue on the official repo, I would proceed like follows.
In you Core Data model add the inverse relationship Comment -> Issue, so that your Comment interface looks like
@interface Comment: NSManagedObject
@property (nonatomic, retain) Issue * issue;
@property (nonatomic) int32_t commentId;
// many other fields not shown.
@end

and make that relationship mandatory.
Now you have to setup your mapping adding that relationship, for instance
[issueMapping addRelationshipMappingWithSourceKeyPath:@"comments"
                                              mapping:[self commentMapping]];

If my understanding is correct, RestKit should populate both relationships (the one-to-many Issue -> Comment and its inverse) for you.


text:
Q: SharePoint Claims-Authentication, Cookies, C#, and Excel-DLL/tld The basic concept of the project is it accesses SharePoint, verifies a certain file exists, verifies the file is NOT locked by another user, and then, if those two conditions are met, excel opens the file up and does some stuff with it, then saves the file and closes it again.
The issue is at the point where the program accesses SharePoint and runs through the verification steps.  Initially, my first crack at this was directly from VBA using SOAP, and, until Microsoft decided to downgrade SharePoint to 2013 from 2010, it worked quite well, meaning now, I'm into using Visual Studio and C# to accomplish the same thing that SOAP was doing in SP2010.
I've attempted implementing the code found here: http://www.vrdmn.com/2013/01/authenticating-net-client-object-model.html, however I can't get it to work.  What I did manage to get working was the 2010 authentication model which pops up a browser window, checks for valid cookies, and, if it finds them, reads the cookies, otherwise prompts the user to log into SharePoint and then closes the browser and continues on.
public CookieCollection Show()
    {
        if (string.IsNullOrEmpty(this.LoginPageUrl)) throw new ApplicationException(Constants.MSG_NOT_CLAIM_SITE);

        // navigate to the login page url.
        this.webBrowser.Navigate(this.LoginPageUrl);

        DisplayLoginForm = new Form();
        DisplayLoginForm.SuspendLayout();

        // size the login form
        int dialogWidth = Constants.DEFAULT_POP_UP_WIDTH;
        int dialogHeight = Constants.DEFAULT_POP_UP_HEIGHT;

        if (PopUpHeight != 0 && PopUpWidth != 0)
        {
            dialogWidth = Convert.ToInt32(PopUpWidth);
            dialogHeight = Convert.ToInt32(PopUpHeight);
        }

        DisplayLoginForm.Width = dialogWidth;
        DisplayLoginForm.Height = dialogHeight;
        DisplayLoginForm.Text = this.fldTargetSiteUrl;

        DisplayLoginForm.Controls.Add(this.webBrowser);
        DisplayLoginForm.ResumeLayout(false);

        //DisplayLoginForm.Show();

        Application.Run(DisplayLoginForm);

        // see ClaimsWebBrowser_Navigated event
        //DisplayLoginForm.Dispose();
        return this.fldCookies;
    }

The problem comes about with the Application.Run(DisplayLoginForm).  If I step through the code line-by-line, everything works fine, and I get the results I need within my VBA code.  However, if I run the program with F5 (either by building it in Debug mode or in Release mode), Application.Run(DisplayLoginForm) kills the application (and Excel along with it) once the cookie jar (my term, and most likely not a computer term) has been examined for valid cookies.
You can see in the code, I attempted to use DisplayLoginForm.Show(); rather than Application.Run, however I kept getting null references to the file I'm trying to find, so that approach does not work either.
So here's the question:
How do I go about popping up a web browser (which is obviously set up as a windows form), look for the cookies, prompt the user if needed, close the web browser and remain alive long enough to return the appropriate values (file.exists and file.islockedbyuser.email, both of which are in functions called by the VBA and both of which work just fine) to excel, and then finish up the program without shutting Excel down in the process?

A: The answer to this question is to set up a new and separate thread on which to operate the browser and login sequence, returning to the main thread (and the thread Excel is running on) the context with the credentials, with which the file can be queried.


text:
Q: Teradata SQL Assistance to discern if Previous Row is a specific location and within a set time frame to give me a 1-count (Flag) I am using Teradata. The query below runs, but somehow, I cannot get it to calculate at each hospital admission looking back to previous row if the admission is to an ED and if so is it within 1 day. It works if I limit my data to a single MEMBER_NO and there is one Hospital admission, but when there are several over a few years, it will not give me "1" in "ED Visit within 1 Day of this Hospital Admit" column. Also, I am not able to get it Null at each start of MEMBER_NO for the "Previous LOCATION" and Null at the end for the "Next LOCATION."
SELECT js.*
  ,CASE
     WHEN LOCATION = 'Hospital'
     THEN Count(CASE WHEN LOCATION = 'Hospital' AND "Days Since ED Discharge"  <= 1 THEN 1 END)
          Over (PARTITION BY TRIM(MEMBER_NO)
                ORDER BY DISCHARGE_DATE, ADMIT_DATE
                RESET WHEN LOCATION = 'HOSPITAL')
   END AS "ED Visit within 1 Day of this Hospital Admit"

  ,CASE
     WHEN LOCATION = 'Hospital'
     THEN Count(CASE WHEN LOCATION = 'Nursing Facility' AND "Days Since Last Hospital Discharge"  <= 7 THEN 1 END)
          Over (PARTITION BY TRIM(MEMBER_NO)
                ORDER BY DISCHARGE_DATE, ADMIT_DATE
                RESET WHEN LOCATION = 'HOSPITAL')
   END AS "Nursing Facility Admit within 7 Days after this Hospital Discharge"

FROM
(
  SELECT CLIENT, TRIM(MEMBER_NO) "MEMBER ID", AGE, ADMIT_NO, LOCATION, ADMIT_DATE, DISCHARGE_DATE
, COALESCE(MIN(LOCATION) over (order by ADMIT_NO rows between 1 preceding and 1 preceding), LOCATION) "Previous LOCATION"
, COALESCE(MIN(LOCATION) over (order by ADMIT_NO rows between 1 following and 1 following), LOCATION) "Next LOCATION"

,CASE
  WHEN LOCATION = 'Hospital'
        THEN ADMIT_DATE -
             MIN(CASE WHEN LOCATION = 'ED' THEN DISCHARGE_DATE END)
             Over (PARTITION BY TRIM(MEMBER_NO)
                   ORDER BY DISCHARGE_DATE, ADMIT_DATE
                   ROWS Unbounded Preceding)
      END AS "Days Since ED Discharge"

,CASE
  WHEN LOCATION <> 'Hospital'
        THEN ADMIT_DATE -
             Max(CASE WHEN LOCATION = 'Hospital' THEN DISCHARGE_DATE END)
             Over (PARTITION BY TRIM(MEMBER_NO)
                   ORDER BY DISCHARGE_DATE, ADMIT_DATE
                   ROWS Unbounded Preceding)
      END AS "Days Since Last Hospital Discharge"

   FROM CLAIMS_DB.FACILITY_CLAIMS
   WHERE ADMIT_DATE BETWEEN DATE '2017-01-01' AND DATE '2020-12-31'
 ) AS js;

Here is the display of the result of the query now. The cells shaded in red are incorrect. J6 should be "0" and L6 should be "1". As stated earlier, if I change the date range to only have one Hospital location reported then J6 works. Also, F2 and G8 should be Null.

A: Solution for properly calculating the "Days since ED Visit" at each Hospital Admit date is:
,CASE
  WHEN LOCATION = 'Hospital'
        THEN ADMIT_DATE -
             MAX(CASE WHEN LOCATION = 'ED' THEN DISCHARGE_DATE END)
             Over (PARTITION BY TRIM(MEMBER_NO)
                   ORDER BY DISCHARGE_DATE, ADMIT_DATE
                   ROWS Unbounded Preceding)
      END AS "Days Since ED Discharge"

And the solution to getting Previous and Next Locations correct even for NULLs is not to use COALESCE, but instead do this:
, MIN(LOCATION) OVER (PARTITION BY MEMBER_NO ORDER BY ADMIT_NO ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) "Previous LOCATION"
, MIN(LOCATION) OVER (PARTITION BY MEMBER_NO ORDER BY ADMIT_NO ROWS BETWEEN 1 FOLLOWING AND 1 FOLLOWING) "Next LOCATION"


text:
Q: How to remove group in Empathy? I have created a new group in Empathy IM by right-clicking on a contact, then Edit and Add Group.
How do I remove a group?
UPDATE:
OK, obviously Murat Gunes answer is correct, but that's not exactly what I meant. When I right click on the group name and select Remove it removes the group from the main window.
However, the group is not purged from the system. When I right-click on a contact again and select Edit, I can still see the group in the list and I can even put a contact into that group, which then makes it appear again in the main window.

A: Right-click the group title and hit "Remove".

A: You may need to remove them for Windows Live (possibly from the web client, or the Windows client itself) in order to have them permanently gone...

A: Do what Murat says and then restart Empathy (not just closing the window, but really quit it, then start Empathy again).


text:
Q: How do i can add master code to development branch I got some git-flow issue. I have a master and a dev branch. My dev branch has updated code and I made a feature branch from it. Now I got a situation that I need same master code in my existing dev branch.
I have few solutions but I don't know which is best practice:

*

*Make another dev branch and delete the existing one.

*Delete existing code from dev and make it the same as master.

A: You could do one of the followings:

*

*Make a Pull Request from the master branch to the dev branch, this way you could pick what changes from master you want in the dev branch (Probably would result in a merge conflict).

*Open a new dev (You should delete the old dev first) branch from master, this way both of them will be sync.

If you don't care about the content of dev and you need EXACTLY the same code that is already on master I'll recommend the second, it's faster, but it's a better practice to do this kind of things with a Pull Request.

A: If you're working alone on the repo, consider simply moving the ref of dev with
git branch -f dev master

That being said, your feature branch, having been branched off dev, might still reference commits from the old dev you wanted to forget, and they'll be brought back in when you merge into master. Be sure to anticipate it if that's the case.
Comment if my assumption is false (if you're sharing the repo), I'll update my answer.


text:
Q: Display an excel file, which user can accept or not I need to display an Excel file that I created. What I need now is to display the .xls file to the user to see it, along with an "Accept" button and a "Cancel" button. I know I can create an Intent for the phone to open the file, but it will open in another app, and I will not be able to create that buttons.
Is there any way I can achieve this?
PS: im doing it via startActivityForResult.


text:
Q: rails associations with plural, possible, foreign keys For example I have 2 players game, with future to have more than one game in the same time.
I need to create associations that will give me the opportunity to simply call user.games and it will return all games where that user is involved, as first_user_id or second_user_id.
table games
desk
first_user_id
second_user_id
table users
id
Model User
has_namy ??

A: What I think you are asking for:
class Game < ActiveRecord::Base
  has_one :first_user, foreign_key: :first_user_id, class_name: 'User'
  has_one :second_user, foreign_key: :second_user_id, class_name: 'User'
end

class User < ActiveRecord::Base
  has_many :first_user_games, foreign_key: :first_user_id, class_name: 'Game'
  has_many :second_user_games, foreign_key: :second_user_id, class_name: 'Game'

  def games
    first_user_games + second_user_games
  end
end

I think it is probably a bad sign that you need this though, and it will be a pain. Instead you could just add a UserGames table and UserGame join model, put a column called "player_number" on UserGame, and do has_many :games, through: :user_games on User to get all games, regardless of player number, and then use queries, filtering, scoping, etc. as needed to find only the games where the player was a certain number. Here are a few questions related to scoping/conditions for has_many ..., through: ... on columns in the join model, in case you want to be able to access lists of games in User where the player is a specific player #:

*

*Rails complex has_many and has_many through

*Scope with join on :has_many :through association


text:
Q: Android Linear Acceleration Can the accelerometer detect the movement of the device (e.g. if I drag the device up, down, left, or right)? Please provide a sample implementation.

A: Accelerometers and gyroscopes can detect device's angle and acceleration on the 3 axes.
Since the acceleration itself does not tell you the speed nor distance, you can know them.
BUT if you know the device's speed is currently 0, and it begins to accelerate, you can know its speed and distance by basic physics equations:
You track the device acceleration. lets make the tracking resolution to be milliseconds. So each millisecond, speed += Acceleration * 0.001 and distance += (speed * 0.001) + (Acceleration * 0.001 * 0.001 /2). This tracks movement in a single direction.
Notice that you have to decide what is the direction of the acceleration, speed and distance, which will be a Vector3. Then use some maths transformations to transform the current acceleration vector to your direction. I suggest that the direction will be flat comparing to the earth. Makes stuff easier later.
This can be used to tell if the device is moving (speed!=0, although if the movement is exactly perpendicular to your vector, the device might be moving but speed==0 is true) and which direction is the movement

A: Accelerometers detect acceleration, not constant motion. So your accelerometer will detect motion as it starts and stops, but can't tell you how far your device moved.

A: please, look at this thread: Android TYPE_LINEAR_ACCELERATION sensor - what does it show?
I detect speed, movement of device using accelerometer. But i have trouble when using LINEAR_ACCELEROMETER sensor.
Anyway, it's impossible to calculate movement without calibration at start point.

A: There's a good example of how to calculate linear acceleration from a regular Sensor.TYPE_ACCELEROMETER on the Android Developer site:
http://developer.android.com/reference/android/hardware/SensorEvent.html#values


text:
Q: Disable IPv6 before launching Citrix Workspace I am unable to establish a Citrix session if I have an IPv6 address. After spending a few hours going down the certificates rabbit-hole, as guided by other threads that also related to the unable to connect to 0.0.0.2 issue. I finally stumbled upon this thread.
Citrix not connecting in ubuntu 20.04
Disabling IPv6 made things start working again. I'm not sure what has changed that all of a sudden made this problem occur. But disabling IPv6 has sorted it out.
I created a script to disable IPv6, which I manually run prior to opening a Citrix connection.  Does anyone know of a way to make that script automatically run when I launch a Citrix session?