text:
Q: To solve Heat equation problem
Let $u(x,t)$ be a solution to the heat equation problem $u_{t}=u_{xx}$ in $[0,π]×[0,L]$ subject to $u(0,t)=u(π,t)=0$ on $ [0,L] $ and $ u(x,0)= \phi (x)$ on $[0,π]$. If $u(x,L)=f(x)$ then which of the following is true for a suitable kernel $k(x,y)$
1) $\int_{0}^{π} k(x,y) \phi (y) dy = f(x)$ for $0 \leq x \leq π$
2)  $\phi (x)+ \int_{0}^{π} k(x,y) \phi (y) dy = f(x)$ for $0 \leq x \leq π$
3)  $\int_{0}^{x} k(x,y) \phi (y) dy = f(x)$ for $0 \leq x \leq π$
4)  $\phi (x) + \int_{0}^{x} k(x,y) \phi (y) dy = f(x)$ for $0 \leq x \leq π$.

My approach
Let $u(x,y)= X(x)T(t)$ then the pde is $\dfrac{X''}{X}= \dfrac{T'}{T}= \lambda$ with boundary conditions $X(0)=X(π)=0$ and $T(0)=c_{1}$ and $T(L)=c_{2}$.
Let $\lambda <0$ say $\lambda = -k, k>0$
$X(x)=a\cos(\sqrt{k} x) + b\sin(\sqrt{k }x)$ and $T=e^{\lambda t}$.
Using boundary conditions for $X$, $a=0$ and $b$ is arbitrary with $\sqrt{k} =n$ implies $\lambda = -n^{2}$ where $n \in \mathbb{Z}$.
Thus $u(x,t) = b \sin (nx) c_{1}c_{2} e^{-n^{2}t}$
Here the differential equations are boundary value problems which give fredholm integral equations upon integration therefore option 3 and 4 are not true. Can anyone help me with 1 and 2?


text:
Q: Unable to re-install an instance using the original instance name We are trying to uninstall and re-install a 2008R2 instance.  We have uninstalled the database engine but when we tried to re-install it we got the error "Original instance id\name in use".
The instance is on a VM machine (no cluster).  Unfortunately there is another (production) instance on the same machine.
The steps taken were as follows:

*

*Back up the databases

*Uninstall the instance

*Reboot

*Attempt re-install failed

*Review registry for any possible references to the database engine and that instance name and remove them.

*Attempt re-install - same error.

We did discover that there is a reporting server instance with the old instance name already installed but I wouldn't have thought that the instance name on a reporting server instance would affect the install of a database engine instance.
Any suggestions on what we are missing?

A: The cleanest solution IMHO will be to remove reporting services, too, as part of cleaning the old instance off the machine. Until you've cleaned off everything service-related, that instance name still "exists" - and it can be a really thorny and frustrating experience trying to remove all the registry entries, GUID by agonizing GUID.
I suspect that SQL Server must keep some things around e.g. for connectivity to SSRS from external sources via the instance name. This is why you can't just pave a new instance over top of it.
The other alternative would be to leave your SSRS instance intact, but install the new instance with a different name, and just update application connection strings, aliases, DNS etc. so that they will connect to the new instance name (hopefully this change will be as transparent as possible).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using .to_numpy() to copy specific columns from one row of Pandas Dataframe to another I have a Dataframe like this:
     UniqueID  CST  WEIGHT  VOLUME  PRODUCTIVITY
0  413-20012    3     123      12          1113
1  413-45365    1     889      75          6748
2  413-21165    8     554      13          4536
3  413-24354    1     387      35          7649
4  413-34658    2     121      88          2468
5  413-36889    4     105      76          3336
6  413-23457    5     355      42          7894
7  413-30089    5     146      10          9112
8  413-41158    5     453      91          4545
9  413-51015    9     654      66          2232

And I have a dictionary of parent:child mappings for the UniqueID's:
parent_child_dict = {
    '413-51015': '413-41158',
    '413-21165': '413-23457',
    '413-45365': '413-41158',
    '413-20012': '413-23457'
}

What I need to do is loop through the Dataframe, and replace the WEIGHT, VOLUME, and PRODUCTIVITY values of the 'child' UniqueID row with the values from the 'parent' UniqueID row, where resulting Dataframe would look like this:
     UniqueID  CST  WEIGHT  VOLUME  PRODUCTIVITY
0  413-20012    3     355      42          7894
1  413-45365    1     453      91          4545
2  413-21165    8     355      42          7894
3  413-24354    1     387      35          7649
4  413-34658    2     121      88          2468
5  413-36889    4     105      76          3336
6  413-23457    5     355      42          7894
7  413-30089    5     146      10          9112
8  413-41158    5     453      91          4545
9  413-51015    9     453      91          4545

I've experimented with several possible solutions, and the trouble I'm having is limiting the copy in such a way that the UniqueID and the CST values of the 'child' row are preserved, but the other values are copied over.
The closest I've gotten is a loop through the dictionary where each pairing gets fed into this:
df.loc[df['UniqueID'] == '413-51015'] = df.loc[df['UniqueID'] == '413-41158'].to_numpy()

This seems to nicely replace all values from one row to another.
Any help on the exceptions or a better solution overall would be extremely helpful.  Thank you.

EDIT
I've looped the first solution into the columns that I want changed in the dataset like this:
columns = []
for col in df.columns:
    columns.append(col)
remove_perm = columns.remove('UniqueID')
remove_perm = columns.remove('CST')
print(columns)

OUTPUT
['WEIGHT', 'VOLUME', 'PRODUCTIVITY']

Then
for col in columns:
    s = df[['UniqueID', col]].set_index('UniqueID')
    df[col] = s.loc[df['UniqueID'].replace(parent_child_dict)].to_numpy()

This has resulted in the desired dataset.

A: replace and loc access:
s = df[['UniqueID','PRODUCTIVITY']].set_index('UniqueID')

# using to_numpy here :-)
df['PRODUCTIVITY'] = s.loc[df['UniqueID'].replace(parent_child_dict)].to_numpy()

Output:
    UniqueID  CST  WEIGHT  VOLUME  PRODUCTIVITY
0  413-20012    3     123      12          7894
1  413-45365    1     889      75          4545
2  413-21165    8     554      13          7894
3  413-24354    1     387      35          7649
4  413-34658    2     121      88          2468
5  413-36889    4     105      76          3336
6  413-23457    5     355      42          7894
7  413-30089    5     146      10          9112
8  413-41158    5     453      91          4545
9  413-51015    9     654      66          4545

A: First create a mapping out of your UniqueID and PRODUCTIVITY.
Then use your parent child to map your ids:
mapping = df.set_index('UniqueID')['PRODUCTIVITY'].to_dict()
df['PRODUCTIVITY'] = (
    df['UniqueID'].map(parent_child_dict).map(mapping).fillna(df['PRODUCTIVITY']).astype(int)
)
print(df)
    UniqueID  CST  WEIGHT  VOLUME  PRODUCTIVITY
0  413-20012    3     123      12          7894
1  413-45365    1     889      75          4545
2  413-21165    8     554      13          7894
3  413-24354    1     387      35          7649
4  413-34658    2     121      88          2468
5  413-36889    4     105      76          3336
6  413-23457    5     355      42          7894
7  413-30089    5     146      10          9112
8  413-41158    5     453      91          4545
9  413-51015    9     654      66          4545


text:
Q: sending mail with attachment but the attachment is not send only the body is sent I'm sending a mail with pdf attached in my application but at the receiver end can receive only the body not the attachment
This is the error I received while running the script but the mail is sent
Traceback (most recent call last):
  File "C:\Users\vineet\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 138, in run
    self.finish_response()
  File "C:\Users\vineet\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 180, in finish_response
    self.write(data)
  File "C:\Users\vineet\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 274, in write
    self.send_headers()
  File "C:\Users\vineet\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 332, in send_headers
    self.send_preamble()
  File "C:\Users\vineet\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 255, in send_preamble
    ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1')
  File "C:\Users\vineet\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 453, in _write
    result = self.stdout.write(data)
  File "C:\Users\vineet\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 799, in write
    self._sock.sendall(b)
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\vineet\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 141, in run
    self.handle_error()
  File "C:\Result Creater\virtual\lib\site-packages\django\core\servers\basehttp.py", line 116, in handle_error
    super().handle_error()
  File "C:\Users\vineet\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 368, in handle_error
    self.finish_response()
  File "C:\Users\vineet\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 180, in finish_response
    self.write(data)
  File "C:\Users\vineet\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 274, in write
    self.send_headers()
  File "C:\Users\vineet\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 331, in send_headers
    if not self.origin_server or self.client_is_modern():
  File "C:\Users\vineet\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 344, in client_is_modern
    return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9'
TypeError: 'NoneType' object is not subscriptable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\vineet\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 650, in process_request_thread
    self.finish_request(request, client_address)
  File "C:\Users\vineet\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 360, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "C:\Users\vineet\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 720, in __init__
    self.handle()
  File "C:\Result Creater\virtual\lib\site-packages\django\core\servers\basehttp.py", line 171, in handle
    self.handle_one_request()
  File "C:\Result Creater\virtual\lib\site-packages\django\core\servers\basehttp.py", line 194, in handle_one_request
    handler.run(self.server.get_app())
  File "C:\Users\vineet\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 144, in run
    self.close()
  File "C:\Result Creater\virtual\lib\site-packages\django\core\servers\basehttp.py", line 111, in close
    super().close()
  File "C:\Users\vineet\AppData\Local\Programs\Python\Python37\lib\wsgiref\simple_server.py", line 35, in close
    self.status.split(' ',1)[0], self.bytes_sent
AttributeError: 'NoneType' object has no attribute 'split'

My send email function-
def send_email(request):
    subject='Mark Sheet'
    message='You requested for your Marksheet'
    email_from=settings.EMAIL_HOST_USER
    recipient_list=[request.user.email]
    email=EmailMessage(subject,message,email_from,recipient_list,
        headers={'Reply- To':settings.EMAIL_HOST_USER})
    file=str(request.user)+'.pdf'
    email.attach_file=(f"/store/{file}")
    email.send()
    return redirect('home')

My Pdf class for creating pdf
class Pdf(View):

def get(self,request):
    marks=Marks.objects.filter(user_name=request.user).first()
    today=timezone.now()
    params={
        'today':today,
        'marks':marks,
        'request':request
    }
    file=Render.render_to_file('user/pdf.html',params)
    return redirect('send_email')

A: You have bad syntax here:
email.attach_file=(f"/store/{file}")

attach_file() is a method, and you're assigning to it with = which means the method gets replaced on the object instead of being called. Change it to:
email.attach_file(f"/store/{file}")


text:
Q: Cuda + OpenGL : How to display elements of an array Lets say that an array of data
int data[256][256][256];

contains values of 0 and 1.
This data will be copied to device memory (flattened) and processed by cuda kernel changing some values from 0 to 1 and vice versa.
How can i display the data in such a way so
if data[x]][y][z]==1
{
//a point of size 1 will be displayed in (x,y,z) coords
}

without having to copy that array back to host memory. I want to do it directly from device(gpu) memory.
A simple example would be very helpfull.

A: The first approach that comes to mind would be to first use a simple stream compaction technique, eliminating all 0 values from the stream. Since you already have your data in a comceptually boolean format, this amounts to a scan/prefix-sum of those values, so that afterwards each array element stores the number of its preceding elements. Then you use these computed offsets to relocate the array elements into a new buffer (effectively storing all 1-items consecutively), but instead of just copying the (now irrelevant) offset, you store the 3D position (easily computable from the old array index).
What you then have is a simple list of 3D points in a buffer, that you can easily draw with OpenGL, without any copy to host. If you write the final number of 1-points (a by-product of the scan) into an additional buffer you can even use indirect rendering and don't even need to query the number of points from the host and thus can just draw the whole thing without any readback.
These are just some general thoughts on how this might work, feel free to google for individual keywords if you don't know what I'm talking about. And if you don't know how to draw anything with OpenGL, you will need to get acquainted with OpenGL or Direct3D first, before you can draw anything from GPU (CUDA won't do it for you).

EDIT: Well, there is a way to draw this whole thing in CUDA. If it's really just a bunch of points and you don't need any sophisiticated rasterization, you can simply transform those points from 3D to 2D like OpenGL does, too (OpenGL isn't magic either, just a bunch of CUDA kernels with some small bits of dedicated hardware in between). So you have a thread for each data item and if this item is 1, you just transform the point's 3D coordinate (as given by the thread ID) using the usual modelview and projection transformations on homogeneous 4D coordinates (but don't forget to do the perspective divide and viewport transform yourself, because now there's no fixed-function hardware to do that for you). And use this final 2D coordinate to just set a single pixel in an output image.
Of course this won't let you profit (not that easily or straight-forward at least) from OpenGL's other sophisticated things, like rasterization and what not effects you could think about. But it avoids the stream compaction step and you could at least render those points on top of an already existing OpenGL-rendered image (containing the rest of your visualization scene, like a coordinate system or text or whatever), maybe even using your own depth test implementation.

EDIT: Another way to avoid the stream compaction would be to draw the whole buffer of 0s and 1s directly with OpenGL, using the geometry shader to do the coordinate computation and 0-removal. So what you do is draw all points, using the whole integer array to feed a single int attribute and put it through the following shaders. First a simple pass-thru vertex shader:
layout(location=0) in int flag;    //single integer attribute
out int vFlag;                     //just passed through

void main()
{
    vFlag = flag;        //GS does the real work
}

The geometry shader decides if the point is valid (has a value of 1) and if yes emits an actual point for it (if not just does nothing, i.e. no point rendered), computing its 3D coordinate from the primitive ID, which is effectively the array index, since we're just drawing points:
layout(points) in;
layout(points,max_vertices=1) out;

uniform mat4 modelViewProj;

in int vFlag[];

void main()
{
    if(vFlag[0] == 1)
    {
        vec3 position = simpleIndexMagic(gl_PrimitiveID);
        gl_Position = modelViewProj * vec4(position, 1.0);
        EmitVertex();
    }
}

The fragment shader is then just a usual one. Of course those shaders can be customized like you see fit. But the general approach is clear, draw the integer values directly, transforming the array index into a point for only the values that are 1 in the geometry shader. But in how far this gives an improvement over a previous stream compaction needs to be evaluated.


text:
Q: How to use Pandas split for retaining both parts of column? I have a file with columns such as:
 A    B                 C
f>g f=313/g=6535    1:123456
r>t r=2/t=7020      1:56789
g>f g=2/f=6764      1:65555
t>r t=5337/r=677    1:115675

and I am struggling with splitting them. I need not only to split them, but also save both parts of splitted column.
For third column, I tried this syntax
df['name_1'] = df['C'].str.split(':')[0]
df['name_2'] = df['C'].str.split(':')[1]

But still get ValueError
I have no more ideas left, what is wrong?
I checked previous questions, but no  thread seems to be answering this problem
Thank you!

A: You can try something like
df[['name_1', 'name_2']] = df['C'].str.split(':', expand=True)

Which results in what you want
     A             B         C name_1  name_2
0  f>g  f=313/g=6535  1:123456      1  123456
1  r>t    r=2/t=7020   1:56789      1   56789
2  g>f    g=2/f=6764   1:65555      1   65555
3  t>r  t=5337/r=677  1:115678      1  115678


text:
Q: How to use icon fonts properly? I have downloaded the icon font "Font Awesome" to use unicode icons to illustrate my documents.
Using XeTeX, I was able to declare a new font family like this:
\newfontfamily\fontawesome[
    Path=fonts/iconic/FontAwesome/
]{FontAwesome.otf}

This works. Now, if I want to use an icon from the font, for example the floppy disk icon, I do the following:
\fontawesome{}\normalfont

I would however like to have a shorter way to use this icon. I would much prefer something like ... Some text \floppy more text... to avoid to manually have to reset the font after using the icon. I came across \DeclareUnicodeCharacter{f0c7}{\floppy}, but it seems like this wouldn't work with XeTeX.
Any ideas on how to "shortcut" this icon in a similar way?

A: You don't want a Unicode char here, you want a new command that inserts jsut the appropriate symbol.
\newcommand*\floppy{{\fontawesome{}}}

I've used an extra pair of braces to group the font change so there is no need for \normalfont. Note that in the usual TeX way you will need to allow for the space-skipping which occurs after the command, e.g. \floppy{} more text not \floppy more text.

A: \documentclass[border=10pt]{standalone}
\usepackage{fontawesome}
\setmainfont{Linux Libertine O}
\def\floppyA{{\FA}}
\let\floppyB\faSave
\let\\floppyB

\begin{document}
Some awesome icons:
\faSave\   %%% loads automatically  the awesome icons
\floppyA\
\floppyB\
\

\end{document}


text:
Q: angular auth0 json web token strategy for the reload I've followed this very good tutorial
https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/
Client side I'm using https://github.com/auth0/angular-jwt
storing the token in session storage.
What type of strategy do you use if you
want the user to be logged at the next
visit the site ?
By now I've thought to store the token
in local storage and than check if token is expired
if not using to get ie the username.
Of course if the token is expired do login.
Any thoughts ?


text:
Q: Convert Date strored as number(32,0) in oracle I have an issue importing date from a Tririga database into a SQL database. Mainly I cant convert the date properly and it looks like is not the commont format I have seen around.
Eg date value incomming 775724400000
Running something like select to_date('765187200000', 'DDMMYYYYHH24MISS') my_date FROM dual;
give me an error
ORA-01847: day of month must be between 1 and last day of month
01847. 00000 -  "day of month must be between 1 and last day of month"
I found the following info from this link seems to be also from tririga
link_help
And the size of the number are about 10 digits meanwhile this one is 12 and I know for fact this dates should be from the past 10 years (most of them)
I can't seem to find anything that gives me an answer how to convert this into proper dates.
Any suggestions?

A: The input number appears to be "epoch", a count of milliseconds elapsed since 1 January 1970 GMT (UTC).
To convert to date is not difficult:
select date '1970-01-01' + (775724400000 / 86400000) as dt from dual;

DT
--------------------
1994-Aug-01 07:00:00

Note the hard-coded literals: date '1970-01-01' (epoch is by definition measured from midnight on this date) and 86400000. By one of the definitions (in the previous version of the International System of Units and Weights), a second is 1/86400 of a median day. In Oracle, date arithmetic is based on the number 1 representing one day, so to convert your milliseconds to days you must divide your input by 86400 * 1000.
The most delicate question has to do with time zones (and possibly daylight saving time, also related to time zone). In most cases, epoch is measured from midnight on 1 January 1970 GMT, not from midnight on 1 January 1970 in local time. Do you need to adjust for that? Only you and your business users can answer that question.
(As an aside, the number you provided does NOT represent a date in the past 10 years - not even close.)


text:
Q: Why does the Python runtime coerce the return of "in" to bool, but not the result of comparison operators (==, >, <, etc)? Consider the following class definition:
class Symbolic(object):
    def __eq__(self, rhs):
        return Symbolic()
    def __le__(self, rhs):
        return Symbolic()
    def __gt__(self, rhs):
        return Symbolic()
    def __contains__(self, other):
        return Symbolic()

The operations defined on the class behave like so:
x = Symbolic()
y = Symbolic()

x == y    -->   <Symbolic object at ...>
x <= y    -->   <Symbolic object at ...>
x > y     -->   <Symbolic object at ...>
y in x    -->   True  # huh?

As per the title, my question is: why does the Python runtime explicitly coerce the output of the in operator to a boolean type, but not the output of other comparison operators which are expected to return a boolean value (==, <=, >, etc)?
EDIT: The docs say the following about the in operator and rich comparisons respectively:

*

*
For user-defined classes which define the __contains__() method, x in y is true if and only if y.__contains__(x) is true.

*
By convention, False and True are returned for a successful comparison. However, these methods can return any value, so if the comparison operator is used in a Boolean context (e.g., in the condition of an if statement), Python will call bool() on the value to determine if the result is true or false.

The question still stands: why is the distinction necessary?


text:
Q: How to use template for implementing STACK using LINKEDLIST in cpp So i am trying to create a c++ file which implements stack and all its functions(push,pop,getTop,etc). I want to use Template so that i can make this Stack class for multiple datatypes. I am using linked list to store the data. Here is some example of stack i have implemented using linked list.
#include<iostream>
using namespace std;

template <class T>

class Node{
public:
      T data;
      Node *next;
      Node()
      {
            next = NULL;
      }
};

class Stack
{
      Node *top;
public:
      Stack();
      int isEmpty();
      int isFull();
      void push(T data);
      T pop();
      void display();
};

Stack :: Stack()
{
      top = NULL;
}

int Stack :: isEmpty()
{
      if(top == NULL)
      {
            return 1;
      }
      else
      {
            return 0;
      }
}

int Stack :: isFull()
{
      int temp;
      Node *t = new Node;

      if(t==NULL)
      {
            temp = 1;
      }
      else
      {
            temp = 0;
      }

      delete t;
      return temp;
}

void Stack :: push(T data)
{
      Node *n;

      if(isFull())
      {
            cout<<"\nStack overflow";
      }
      else
      {
            n = new Node;
            n->data = data;
            n->next = top;
            top = n;
      }

}

int Stack :: pop()
{
      Node *t;
      T temp;

      if(isEmpty())
      {
            return temp;
      }
      else
      {
            t = top;
            top = top->next;
            temp = t->data;
            delete t;
            return temp;
      }
}

void Stack :: display()
{
      Node *p = top;
      while(p != NULL)
      {
            cout<<"\n"<<p->data;
            p = p->next;
      }
}

So this is a preview of what i am trying to do, but i don't want to create different node and stack class for different data types. How can i achieve that using Templates. I tried it myself but i am getting lots of error and cant seem to understand why.
Thanks.

A: I suggest making the Node into an inner class of Stack. There's no need for users to be able to see it.
#include<iostream>
#include<utility>

template<class T>
class Stack {
    struct Node {  // inner class
        T data;
        Node *next;
    };

    Node* top = nullptr;
    size_t m_size = 0;

public:
    Stack() = default;

    // rule of five - no copying, only moving allowed
    Stack(const Stack&) = delete;
    Stack(Stack&& rhs) noexcept :
        top(std::exchange(rhs.top, nullptr)), m_size(rhs.m_size)
    {}
    Stack& operator=(const Stack&) = delete;
    Stack& operator=(Stack&& rhs) noexcept {
        std::swap(top, rhs.top);
        m_size = rhs.m_size;
        return *this;
    }
    ~Stack() {
        while(top) {
            delete std::exchange(top, top->next);
        }
    }

    bool empty() const { return m_size == 0; }
    size_t size() const { return m_size; }

    void push(const T& data) {
        top = new Node{data, top};
        ++m_size;
    }

    T pop() {
        T rv = std::move(top->data);
        delete std::exchange(top, top->next);
        --m_size;
        return rv;
    }
};

Demo

A: You can implement like bellow:
#include<iostream>
using namespace std;

template <typename Type>
class Node
{
public:
    Type data;
    Node<Type> *next;
};

template <typename Type>
class Stack
{
public:
    Node<Type> *top;
    void push(Type data);
    Type pop();
};

int main()
{

}

A: Implementing a stack with a linked list requires simply storing a linked list privately, and constraining it with the stack's interface. The constraining is the key. The template parameter is the type you are storing in your stack.
The simplest* way is to take the time implement a linked list well, so that you only have to worry about constraining it in your stack class and not writing a linked list to behave like a stack in your stack class. The principle at play here is called Separation of Concerns.
Here's a quick example using std::list for simplicity's sake:
template <typename T>
class Stack {
 public:
  Stack() = default;
  Stack(T val) : m_stack(val) {}
  void push(T val) { m_stack.push_front(val); }
  T& top() { return m_stack.front(); }
  void pop() {
    if (!m_stack.empty()) m_stack.pop_front();
  }
  bool empty() const { return m_stack.empty(); }

 private:
  std::list<T> m_stack{};
};

The if statement might not be necessary in the pop() function if you want the exception to be thrown in your stack.
Here's a main() that tests the stack:
int main() {
  Stack<int> s1;
  for (int i = 1; i < 11; ++i) s1.push(i);
  while (!s1.empty()) {
    std::cout << s1.top() << ' ';
    s1.pop();
  }
  std::cout << '\n';

  Stack<char> s2('A');
  for (char l = 'B'; l != 'K'; ++l) s2.push(l);
  while (!s2.empty()) {
    std::cout << s2.top() << ' ';
    s2.pop();
  }
  std::cout << '\n';
}

My only includes are <iostream> and <list>. The output:
10 9 8 7 6 5 4 3 2 1
J I H G F E D C B

I am able to avoid a lot of unnecessary work like the Rule of 5 because std::list handles it all for me. So I am fine with compiler-provided copy and move constructors and the destructor.
* This is much easier said than done. I keep a simple linked list around for those specific questions, and it is still ~130 lines of code, and does not have all the functionality necessary to be properly constrained to behave like a stack like I demonstrate with std::list.
If you've written a linked list already, the stack should be very simple as successfully writing a linked list requires demonstrating an extremely wide range of C++ knowledge and programming principles.


text:
Q: javascript execution failing in java with XPathResult undefined I'm trying to execute the javascript function with java, and I'm getting an error message that it is not able to find some of the classes. can someone please help me to clear this issue?
My Java class
public class TestException {

    public static void main(String[] args) throws IOException, ScriptException {
        ScriptEngineManager engineMgr=new ScriptEngineManager();
        ScriptEngine engine=engineMgr.getEngineByName("JavaScript");
        Document doc=HtmlPage.getHTML("", "C:\\Users\\DELL\\Desktop\\PHPTRAVELS.html", "https://phptravels.com");
        String xpath="//input";

        //for single value
    /*  String jscript="return document.evaluate('"+xpath+"',document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;";
        WebElement element=(WebElement)jse.executeScript(jscript);
        System.out.println(element.getAttribute("name"));*/

        String multiCode="var test=function(document){"
                + "var results=document.evaluate('//input', document,null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);"+
                "var tagNames = [];\r\n"
                + "var count=0;" +
                "while(node = results.iterateNext()) {\r\n" +
                "  count=count+1;" +
                "}"
                + "\r\n return count}";
        /*FileWriter fileWrite=new FileWriter(new File(System.getProperty("user.dir")+"\\jScript.js"));
        fileWrite.write(multiCode);
        fileWrite.flush();
        fileWrite.close();*/

        try{
            engine.eval(multiCode);
            Invocable invc=(Invocable) engine;
            Long count=(Long)invc.invokeFunction("test", doc);
        //Long count=(Long) jse.executeScript(multiCode);
        System.out.println(count);
        }catch(Exception e){
            e.printStackTrace();
        }
        }

Exception
javax.script.ScriptException: ReferenceError: "XPathResult" is not defined in <eval> at line number 1
    at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:470)
    at jdk.nashorn.api.scripting.NashornScriptEngine.invokeImpl(NashornScriptEngine.java:392)
    at jdk.nashorn.api.scripting.NashornScriptEngine.invokeFunction(NashornScriptEngine.java:190)
    at demo.TestException.main(TestException.java:58)
Caused by: <eval>:1 ReferenceError: "XPathResult" is not defined
    at jdk.nashorn.internal.runtime.ECMAErrors.error(ECMAErrors.java:57)
    at jdk.nashorn.internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:319)
    at jdk.nashorn.internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:291)
    at jdk.nashorn.internal.objects.Global.__noSuchProperty__(Global.java:1441)
    at jdk.nashorn.internal.scripts.Script$Recompilation$1$27A$\^eval\_.test(<eval>:1)
    at jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:639)
    at jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:494)
    at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:393)
    at jdk.nashorn.api.scripting.ScriptObjectMirror.callMember(ScriptObjectMirror.java:199)
    at jdk.nashorn.api.scripting.NashornScriptEngine.invokeImpl(NashornScriptEngine.java:386)

please let me know if data required from my side.

A: The problem with your code is, you are using XPathResult which present under window object, window object implementation is provided by the web browser. Nashorn (ScriptEngine) doesn't provide window implementation.
From Java Docs:

While Oracle Nashorn runs ECMA-compliant JavaScript, it is important to note that objects normally accessible in a web browser are not available, for example, console, window, and so on.

You can execute and verify your js code with Nashorn using jjs option:
> jjs test.js
abc.js:2 ReferenceError: "XPathResult" is not defined

As you want to parse the HTML file, you can achieve it by using HTML parser such as https://jsoup.org/ , if are using this code for testing you can use Selenium's API JavascriptExecutor#executeScript(...)


text:
Q: Join with table in another database I need to join with table in another database but do not know its name, I only get it from procedure parameter. So I want to do something like this:
select * from [DB1].dbo.[Table1] t1
inner join [@DBName].dbo.[Table2] t2 on t1.ID = t2.ID and t1.status = @status;

Or even
select * from [DB1].dbo.[Table1] t1
inner join [@DBNameAndTableName] t2 on t1.ID = t2.ID and t1.status = @status;

Is it at all possible? Or do I have to use string script and  EXECUTE(@SQL_SCRIPT)?

A: Try this one -
Query:
DECLARE
      @db_name NVARCHAR(150) = 'DB2'
    , @status INT = 0

DECLARE @SQL NVARCHAR(MAX) = '
SELECT *
FROM [DB1].[dbo].[table1] t1
JOIN [' + @db_name +'].[dbo].[table1] t2 ON t1.ID = t2.ID
WHERE t1.status = ' + CAST(@status AS VARCHAR(5))

PRINT @SQL
EXEC sys.sp_executesql @SQL

Output:
SELECT *
FROM [DB1].[dbo].[table1] t1
JOIN [DB2].[dbo].[table1] t2 ON t1.ID = t2.ID
WHERE t1.status = 0


text:
Q: Banach Spaces: Totally Bounded Subsets As an easy consequence of Riesz' lemma it is known that infinite dimensional Banach spaces possess bounded subsets that fail to be totally bounded. On the other hand in finite dimensional Banach spaces any bounded subset happens to be totally bounded as well. So the question arises wether totally bounded subsets always sit within finite dimensional spaces, or put in equivalent form:
Is there an infinite dimensional space which possesses a totally bounded subset not lying entirely in a finite dimensional subspace?

A: In fact, any infinite-dimensional Banach space $X$ has a compact subset that does not lie in any finite-dimensional linear subspace.
Namely, define a sequence $x_n$ inductively such that $x_{n+1}$ is not in the linear span of $\{x_1, \ldots, x_n\}$ but $\|x_{n+1}\| < 1/n$. Then $\{0\} \cup \{x_1, x_2, \ldots\}$ is your set.

A: Sure: the image of the unit ball in $\ell^2$ under the map that sends the standard basis element $e_n$ to $e_n/n$ (with $\ge 1$) is Hilbert-Schmidt, so a compact operator, etc. Indeed, any sequence going to $0$ replacing $1/n$ produces (pre-) compact image.


text:
Q: My MIPS program thinks every user input is the number 4 This assembly code was created to multiply two numbers together.
I've been programming .s programs and executing them in QTSpim for all of 3 days now, though I've been learning about how to do so for over 2 months.  I learned that you can take an integer as user input and store it to a temporary register for use; however, when I attempted this simple task I found that my user input would always become the same number: 4.  The code will be shown below.
NOTES WHEN LOOKING FOR THE PROBLEM:

*

*I wouldn't worry about the part of the program that prevents negative inputs when searching for the problem in this code, but I've left it in just in case that is where the problem arises from.

*Just from what I've learned from trying to fix this program I think there might be a problem with how I define and utilize arg1 and arg2.  If you're looking for them, they're created near the top of the code and are integral in retrieving, storing, and loading the user's input into the temporary registers ($t2 and $t3) in nearly every step of the code.

*The answer is always stored in $t1 and $t1 always starts as 0.  After doing a line by line evaluation of the code, I can conclude that there's nothing wrong with the register $t1 so I wouldn't bother looking at that.

*Anything following a pound symbol (#) will be my thought process at every step of the code.  This could be very useful in figuring out where I went wrong.

*The indentation looks a bit different on Stack Overflow, but if you think that the problem could arise from indentation, please feel free to point that out, I have no clue if improper indentation could lead to errors

Code:
.data

request_input:
.asciiz "Please enter the numbers you would like to multiply: \n"
give_output:
.asciiz "The numbers multiply to give: "
neg_input:
.asciiz "Sorry, this program doesn't work with negative inputs. \n"
arg1: .word 4
arg2: .word 4

.text
.globl main

main:
#Output the request for user input
la  $a0, request_input
li  $v0, 4
syscall

#Takes the user's input and stores it to temp registers
la  $a0, arg1
la  $a1, arg1
li  $v0, 5 #op code for getting an integer input
syscall
lw  $t2, arg1 #store the input to temp register 2

la  $a0, arg2
la  $a1, arg2
li  $v0, 5 #op code for getting an integer input
syscall
lw  $t3, arg2 #store the input to temp register 3

#sets t1 to zero so we can reliably store the answer into it
addi    $t1, $zero, 0

#checks if the arguments are less than zero, if so goes to output zero
blez    $t2, negzero
blez    $t3, negzero
bgtz    $t3, fori

negzero:
#what happens if an argument is negative
la  $a0, neg_input
li  $v0, 4
syscall

la  $a0, 0($t1)
li  $v0, 1
syscall

li  $v0, 10
syscall

fori:
#Does the math
add $t1, $t1, $t2
addi    $t3, $t3, -1
bnez    $t3, fori

fin:
#Outputs the answer
la  $a0, give_output
li  $v0, 4
syscall

la  $a0, 0($t1)
li  $v0, 1
syscall

li  $v0, 10
syscall}


text:
Q: How to encrypt data using the password from User I have a flask site. It's specifically a note app. At the moment I am storing the user notes as plaintext. That means that anyone with access to the server which is me has access to the notes. I want to encrypt the data with the user password, so that only the user can access it using their password, but that would require the user to input his/her password each time they save their notes, retrive the notes or even updates them. I am hashing the password obviously.
Anyone has any idea how this could be done?

A: So using @Chase suggestion I found a really helpful thread on stackexchange security Here. Anyone wondering about encryption.

A: Use session to store user information, the Flask-Login extension would be a good choice for you.


text:
Q: Bluetooth wireless earbuds disconnecting frequently on Windows 10 I'm using truly wireless earbuds with my Android and Windows 10 PC.
The earbuds are working absolutely fine with the Android device, but when connected with Windows 10 PC, they disconnect and reconnect frequently and it becomes very annoying.
It wasn't like this before, but after updating my Windows 10, the problem surfaced.
The earbuds are working absolutely fine with Android devices.
What is the problem with Windows 10 here?

A: If it's working on the Andriod device but not on Windows then I would modify the Power setting for Bluetooth on Windows:
If it is set to allow your computer to turn off the Bluetooth device
to save power, your Bluetooth can keep disconnecting when in a
low-power state. To solve the issue, you need to modify the Bluetooth
Power setting.

*

*Use Windows Search to search for device manager and then select the
first search result to open it.

*Unfold the Bluetooth option and then right-click the Bluetooth device
you want to fix its Bluetooth disconnect issue. Next, select
Properties.

*Switch to the Power Management Then, uncheck the Allow the computer
to turn off this device to save power option.

*Click OK to save the change.


text:
Q: Ember CLI tests on Sauce Labs How can I get ember-cli tests running on Sauce Labs?  Testem has an example configuration, but I don't know how to translate that into the ember-cli compiled tests since the testem.json gets packed into the build when tests run.
I tried doing an ember build --env=test and then putting "test_page": "dist/tests/index.html" in my testem.js and just running testem ci --port=8080 as it is in the example, but that gives me 0 tests run.

A: I believe I have this mostly solved (some issues remain with individual browsers).  For posterity you can view my solution here*:
The things that seem to be necessary:

*

*Use NVM to manage node on OSX, things only started to work when I stopped having to sudo random junk.

*Don't use localhost, I used localtest here for the hostname, but you can use anything - sauce and localhost don't get along very well.

*The command is ember test --port=8080 --host=localtest

*I put my sauce stuff in a different testem config file so I can still run ember test on my dev machine.
Hopefully having a starting place saves someone else from doing all of the wrong things I did originally.
*You probably don't need all of that, as we're currently using ember-cli api stubs to mock our API during development so we need to run a separate instance of ember serve.


text:
Q: Firebase.Functions.FunctionsException: UNAUTHENTICATED, Can't Call cloud function even after user is authenticated Unity editor version: 2021.3.9f
Firebase Unity SDK version: 9.6.0
Source you installed the SDK: FirebaseFunctions(.unitypackage or Unity Package Manager)
Problematic Firebase Component: FirebaseFunctions
Other Firebase Components in use: FirebaseFunctions ,Auth
Additional SDKs you are using:
Platform you are using the Unity editor on: Windows
Platform you are targeting:Android
Scripting Runtime: IL2CPP
[REQUIRED] Please describe the issue here:
Firebase.Functions.FunctionsException: UNAUTHENTICATED
at Firebase.Functions.HttpsCallableReference.b__9_0 (System.Threading.Tasks.Task`1[TResult] task) [0x00000] in <00000000000000000000000000000000>:0
I m trying to user firebase functions with unity. I have added firebase auth that is working perfectly. After auth I am calling my firebase function using this code below
`void FirebaseFucntionTest()
{
var data = new Dictionary<string, object>();
Debug.Log("Calling");
FirebaseFunctions functions = FirebaseFunctions.DefaultInstance;
Debug.Log(FirebaseAuth.DefaultInstance.CurrentUser.DisplayName);

var function = functions.GetHttpsCallable("testunity");
function.CallAsync(data).ContinueWith((task) =>
{
   if (task.IsFaulted)
   {
       foreach (var inner in task.Exception.InnerExceptions)
       {
           if (inner is FunctionsException)
           {
               var e = (FunctionsException)inner;
               var code = e.ErrorCode;
               var message = e.ToString();
               Debug.Log(message);
               Debug.Log(code);
           }
       }
   }
   else
   if (task.IsCompleted)
   {
       Debug.Log((string)task.Result.Data);
   }
});

}`
I am holding a reference to auth using: auth = FirebaseAuth.DefaultInstance; and after this I am calling my function that runs the cloud function, as you can see in the debug statement at the start of the method I getting the currentusername successfully, but after code moves to cloud function call it is giving me exception of unauthenticated:


text:
Q: Deprecated CSVWriter constructor I am using OpenCSV to create CSV files filled with records from database. I am using this:
        CSVWriter writer = new CSVWriter(
            new OutputStreamWriter(new FileOutputStream("example.csv"),
                    StandardCharsets.UTF_8), ';');

The problem is, this constructor is @Deprecated.
The library has several constructors, but only one is not deprecated. I am using this constructor:
/** @deprecated */
@Deprecated
public CSVWriter(Writer writer, char separator) {
    this(writer, separator, '"');
}

while I should be using this:
public CSVWriter(Writer writer, char separator, char quotechar, char escapechar, String lineEnd) {
    super(writer, lineEnd);
    this.escapechar = escapechar;
    this.quotechar = quotechar;
    this.separator = separator;
}

But I am not exactly sure what to put in there as I do not want my files to end up different.

A: This is the same constructor with default values:
CSVWriter writer = new CSVWriter(
            new OutputStreamWriter(new FileOutputStream(SAZKOVA_UDALOST),
                    StandardCharsets.UTF_8), ';', '"', '"', "\n");

Default value for separator is ;. Default value for quotechar is
  ". Default value for escapechar is ". Default value for
  lineEnd is "\n".

A: The class already has static fields which represent the defaults, so you can simply do:
CSVWriter writer = new CSVWriter(
    new OutputStreamWriter(new FileOutputStream("example.csv"), StandardCharsets.UTF_8),
    ';',
    CSVWriter.DEFAULT_QUOTE_CHARACTER,
    CSVWriter.DEFAULT_ESCAPE_CHARACTER,
    CSVWriter.DEFAULT_LINE_END
);


text:
Q: Remove text and only leave icon under @media(min-width: 768px) I have a tab menu that I am presenting on my web page. However, when resizing I am being met with an unexpected behavior, hence my goal is to remove the text and leave only the fa icon when the device is a phone basically @media(min-width:768px).
Here is how the menu is:

               Home

               Resume

               Portfolio

               Contact

I would like to remove those names Home, Contact, Resume, Portfolio when the device is @media@media(min-width:768px).
This is how my @media query currently looks like:
   @media (max-width: 768px) {
  #main-header .port-item {
    width: 25%;
  }

  #main-header .port-item .fa {
    font-size: 1em;
  }

  .map-responsive {
    margin-top: 15px;
  }
}

Here's a picture of what I am referring to:

A: Add a span tag around your text, and make it display: none in a media query, such as @media (max-width: 768px).
HTML:

       Home

       Resume

       Portfolio

        Contact

CSS:
@media (max-width: 768px) {
  #main-header .port-item {
    width: 25%;
  }
  #main-header .port-item .fa {
    font-size: 1em;
  }
  .map-responsive {
    margin-top: 15px;
  }
  #main-header .port-item .item-label {
    display: none;
  }
}


text:
Q: How to increase a variable after every JButton click? I am working on a program that simulates a soccer match. I have a button, which randomly one of the two teams will give a point when I click on it. So, after one click, the score could be 1-0 or 0-1, and after two cliks 2-0, 0-2 or 1-1.
The problem is that, every time I click, it is 0-1 or 1-0. So the score does not count on.
I know that the reason is that I said int homescore = 0 and int awayscore = 0 in the 'action performed' code. And after this 0-0 it gives randomly one of the teams 1 point. So when I click for the second time on the button, the score will start at 0-0 again, not on the new score.
Does someone know how I can solve this problem? Maybe it's very easy, but I haven't programmed often.
This is the part of the code I'm talking about:
private void resultbuttonActionPerformed(java.awt.event.ActionEvent evt) {
    Random dice = new Random();
    int number;
    int homescore = 0;
    int awayscore = 0;
    for (int counter =1; counter<=1; counter++){
        number = dice.nextInt(2);                   // Creates a 0 or a 1
        if (number == 1){                           // If 1: Point to home team
            homescore = ++homescore;}
        else {                                      // If 0: Point to away team
            awayscore = ++awayscore;
                    }
        }

    homescorelabel.setText(String.valueOf(homescore));
    awayscorelabel.setText(String.valueOf(awayscore));

A: just put the scores into your main method/class.
Also, there's no need for the for loop, as it only runs through once.

A:
int homescore = 0;
int awayscore = 0;

You redefine it each time -> try to set out of h method.

A: As you have explained, having
int homescore = 0;
int awayscore = 0;

in your action performed will always increment one value starting from zero. What you need to do is get the existing value and increment one to it. There are two simple ways of doing it.

*

*Set a field variable to store the homescore and awayscore and increment from it.
class GameClass {
    private int homescore = 0;
    private int awayscore = 0;

    private void resultbuttonActionPerformed(java.awt.event.ActionEvent evt) {
        Random dice = new Random();
        int number;
        for (int counter =1; counter<=1; counter++){
            number = dice.nextInt(2);                   // Creates a 0 or a 1
            if (number == 1){                           // If 1: Point to home team
                homescore = ++homescore;
            } else {                                      // If 0: Point to away team
                awayscore = ++awayscore;
            }
        }
    homescorelabel.setText(String.valueOf(homescore));
    awayscorelabel.setText(String.valueOf(awayscore));
 }
}

Note that I have just shown the class here (GameClass). When you increment one of the scores you are incrementing the field so that it will be preserved for each button click.

*Get the current score from the Label.
private void resultbuttonActionPerformed(java.awt.event.ActionEvent evt) {
    Random dice = new Random();
    int number;
    int homescore = Integer.parseInt(homescorelabel.getText());
    int awayscore = Integer.parseInt(awayscorelabel.getText());
    for (int counter =1; counter<=1; counter++){
        number = dice.nextInt(2);                   // Creates a 0 or a 1
        if (number == 1){                           // If 1: Point to home team
            homescore = ++homescore;
        } else {                                      // If 0: Point to away team
            awayscore = ++awayscore;
        }
    }
    homescorelabel.setText(String.valueOf(homescore));
    awayscorelabel.setText(String.valueOf(awayscore));
}


text:
Q: HAVI undefined error when creating AVI files I'm trying to create an AVI file from a series of BMP images and am using Lucian Wischik's source code from http://www.wischik.com/lu/programmer/avi_utils.html however when I
#include "avi_utils.h"

I get a bunch of errors when compiling that include things like HAVI: undeclared identifier.  Has anyone worked with this code before and know what I am doing wrong?
I'm using Visual Studios 2010 and creating it as a Win32 console visual c++ application and I have a link to the vfw32.lib external library in preferences already.
Thanks


text:
Q: For all values in a row, if a certain word is duplicated more than once, we want to remove it from the list I have the following dataframe

en
ko

Tuberculosis of heart
심장의 결핵

Tuberculosis of myocardium
심근의 결핵

Tuberculosis of endocardium
심내막의 결핵

Tuberculosis of oesophagus
식도의 결핵

Zoster keratoconjunctivitis
대상포진 각막결막염

Zoster blepharitis
대상포진 안검염

Zoster iritis
대상포진 홍채염

I want a result like this.

en
ko

heart
심장의

myocardium
심근의

endocardium
심내막의

oesophagus
식도의

keratoconjunctivitis
각막결막염

blepharitis
안검염

iritis
홍채염

This is just an example, I have about 50,000 word pairs. Been doing this for 1 week now.

A: You can use:
import re

# identify duplicates
s = df.stack().str.split().explode()
dups = s[s.duplicated()].groupby(level=1).unique().to_dict()
# {'en': array(['Tuberculosis', 'of', 'Zoster'], dtype=object),
#  'ko': array(['결핵', '대상포진'], dtype=object)}

# remove them
df.apply(lambda s: s.str.replace('|'.join(dups[s.name]), '', regex=True))

Output:
                     en     ko
0                 heart    심장의
1            myocardium    심근의
2           endocardium   심내막의
3            oesophagus    식도의
4  keratoconjunctivitis  각막결막염
5           blepharitis    안검염
6                iritis    홍채염

A: I don't know how extensible this will be to a larger dataset, given tat I don't know the structure of korean re:whitespace between entities, but it works on the given data.
We split the data into two columns, as the preposition "of" doesn't appear to exist in the 'ko' column and that impacts following steps. Then for each column, we split on whitespace to make list columns, we explode those to individual rows, then we get the value counts to determine which elements appear more than once
ko=df['ko'].str.split().explode().value_counts()
en=df['en'].str.split().explode().value_counts()

ko
결핵       4
대상포진     3
심장의      1
심근의      1
심내막의     1
식도의      1
각막결막염    1
안검염      1
홍채염      1
Name: ko, dtype: int64

After that, we use boolean indexing to select only those elements that appear only once for each series
ko_col=ko[ko==1]
en_col=en[en==1]

en_col
heart                   1
myocardium              1
endocardium             1
oesophagus              1
keratoconjunctivitis    1
blepharitis             1
iritis                  1
Name: en, dtype: int64

We rely on the fact that order should be preserved in the above steps, but worth spot checking in your larger dataset, and we recombine to create your output dataframe
new_df=pd.DataFrame({'en':en_col.index,'ko':ko_col.index})
new_df
    en                      ko
0   heart                   심장의
1   myocardium              심근의
2   endocardium             심내막의
3   oesophagus              식도의
4   keratoconjunctivitis    각막결막염
5   blepharitis             안검염
6   iritis                  홍채염


text:
Q: jQuery to change hover state of a link using background image position I have an existing site, and like most of my cases I have to use a jQuery override to change some css. I can resize the element and give it a background image, but I can't get the hover state to work.
You can see my working JSfiddle here: http://jsfiddle.net/wdNF6/
The big that seems to not work is
$('.slideshow-screen .slide-item-current .play-button').hover( function(){
        $(this).css('background-position', 'something something');
}

I used the .hover() from examples I found throughout stackoverflow. When you go to the example, the button should be blue with an image in it. Hovering over it should reposition the bg image. But when you go to the example, the default css pre-jQuery shows. If you remove the second bit of jquery, the first part works.
Any suggestions?

A: Missing the closing brace for the function
$('.slideshow-screen .slide-item-current .play-button').hover( function(){
            $(this).css('background-position', 'bottom center');
    }); <--- Missing this

Also this can be simply be written as
$('.play-button').css({
    width: '90px',
    height: '90px',
    'background-color': '#0000ff',
    'background-position': 'top center',
    'background-image': 'url(http://www.lessardstephens.com/layout/images/slideshow_big.png)'
});

$('.play-button').hover(function() {
    $(this).css('background-position', 'bottom center');
});

Check Fiddle

A: Did you check? Your code had a typo.
You missed an ending ); at the end.
$(document).ready(function () {
    $('.slideshow-screen .slide-item-current .play-button').css({
        width: '90px',
        height: '90px',
            'background-color': '#0000ff',
            'background-image': 'url(http://www.lessardstephens.com/layout/images/slideshow_big.png)',
            'background-position': 'top center'
    });

    $('.slideshow-screen .slide-item-current .play-button').hover(function () {
        $(this).css('background-position', 'bottom center');
    },
    // Also you need to reset
    function () {
        $(this).css('background-position', 'top center');
    });
});

Fixed: http://jsfiddle.net/Vc84h/


text:
Q: Use of str.length()-1 in case of swapping a letter of a word with each other What is the difference between str.length() and str.length()-1???
I can't really understand what is the use of -1 while using Str.length().
I am using it for  exchanging the first letter of a word with the last letter.

A: Well, str.length() returns the length of the string, and str.length() - 1 one less than that.
Since you can also view a string as an array of characters, and the index of the first character in a string is 0, then str.length() - 1 is index of the final character in the string.
So in loops iterating over a string, you'll often see <= str.length() - 1 as the condition check. Personally though I always use < str.length() as that doesn't get you in hot water in languages that use an unsigned type for the length.

A: String is an object that allows you to manipulate every charon its content, those are zero index based, so lets say:
This string "HelloWorld!" has a length of 11(because it has 11 chars)
where char 0 is 'H' you normally use str.length() - 1 to manipulate the object considering the last element in the String
e.g. get the last element in "HelloWorld!" will be  much more easier by doing:
charAt(str.length() - 1)

A: string.length()-1 would typically be used to calculate the position of the last character in a string. Since arrays in java are 0-index, the position of each nth character is at n-1.


text:
Q: Android Play Sound even if Media Volume is 0 I want to play music with AudioTrack even if the media volume of the device is 0.
In my app, I want to have a SeekBar for the media volume (maybe if other music runs in the background) and one other SeekBar for the music of my app.
Until now, I can change the media volume. But then the music of my app is also silent..
How can I do that?

A: I think there is Six Different Streams of Sound in Android for Playing Different Types of Sounds
The first step to creating a predictable audio experience is understanding which audio stream your app will use.
Android maintains a separate audio stream for playing
music,
alarms,
notifications,
the incoming call ringer,
system sounds,
in-call volume,
and DTMF tones.
 This is done primarily to allow users to control the volume of each stream independently.

Use Hardware Volume Keys to Control Your App's Audio Volume

By default, pressing the volume controls modify the volume of the active audio stream. If your app isn't currently playing anything, hitting the volume keys adjusts the ringer volume.
If you've got a game or music app, then chances are good that when the user hits the volume keys they want to control the volume of the game or music, even if they're currently between songs or there's no music in the current game location.
You may be tempted to try and listen for volume key presses and modify the volume of your audio stream that way. Resist the urge. Android provides the handy setVolumeControlStream() method to direct volume key presses to the audio stream you specify.
Having identified the audio stream your application will be using, you should set it as the volume stream target. You should make this call early in your app's lifecycle—because you only need to call it once during the activity lifecycle, you should typically call it within the onCreate() method (of the Activity or Fragment that controls your media). This ensures that whenever your app is visible, the volume controls function as the user expects.
setVolumeControlStream(AudioManager.STREAM_MUSIC);

From this point onwards, pressing the volume keys on the device affect the audio stream you specify (in this case "music") whenever the target activity or fragment is visible.

A: Thanks for your answers.
Now I use "AudioTrack(AudioManager.STREAM_SYSTEM, (...))" and it's working good.
Maybe it's not the best method but by now, it's working.


text:
Q: Adding a multiple choice ques with goToPage I am trying to add a multiple choice question with a goToPage setting.  I have followed the documentation and I cannot figure out if I found a bug or doing something wrong.
I get an error at this line, and I don't know why:
var choice1 = ques.createChoice(name1, page1Item);  //Error:  InternalError: Cannot find method createChoice(string,Item).
function testCreateChoice(){
  // documentation: https://developers.google.com/apps-script/reference/forms/multiple-choice-item#createchoicevalue-navigationitem

  // define variables
  var mcId = 1310873270;  //Id of multiple choice queston
  var pageId1 = 1255540175; //Id of page 2
  var pageId2 = 1103976777; //Id of page 3
  var name1 = "Go To Page 2";
  var name2 = "Go To Page 3";

  // open question and itmes
  var form = FormApp.openByUrl(SpreadsheetApp.getActiveSpreadsheet().getFormUrl());
  var ques = form.getItemById(mcId).asMultipleChoiceItem();
  var page1Item = form.getItemById(pageId1);
  var page2Item = form.getItemById(pageId2);

  //verify
  Logger.log(ques.getTitle());  // correctly itentified
  Logger.log(page1Item.getTitle()); // correctly itentified
  Logger.log(page2Item.getTitle()); // correctly itentified

  //add Choices  ~ This is where I get the error
  var choice1 = ques.createChoice(name1, page1Item);  //Error:  InternalError: Cannot find method createChoice(string,Item).
  var choice2 = ques.createChoice(name2, page2Item);  //Error:  InternalError: Cannot find method createChoice(string,Item).
  var newChoices =[choice1,choice2];
  ques.setChoices(newChoices);
}

A: Funny, I found another post, that I helped someone answer a similar question.  After you write so much code, you forget your own answers.
The solution was to add .asPageBreakItem(); to the end of get item for page1Item and page1Item.
  var page1Item = form.getItemById(pageId1).asPageBreakItem();
  var page2Item = form.getItemById(pageId2).asPageBreakItem();


text:
Q: on facebook share image is not appearing for the first time though meta has og image height and width I have the below tags in my facebook share page but the image is not appearing for the first time in my share dialogue box.
<meta property="fb:app_id" content="xxxxx" />
<meta property="og:type" content="article" />
<meta property="og:site_name" content="xxxx" />
<meta property="og:url" content="http://web.dailyhunt.in/buzz/video/english/fresh/but-gabriel-boschilia-24-as-monaco-fc-lorient-4-0-2016-17-frsh-hi-139074" />
<meta property="og:title" content="But Gabriel BOSCHILIA (24') / AS Monaco - FC Lorient (4-0) -  / 2016-17" />
<meta property="og:image" content="http://tcdn.newshunt.com/images/items/1/3/9/0/74/139074_share.jpg" />
<meta property="og:image:width" content="400" />
<meta property="og:image:height" content="300" />

Search for solution and found Facebook ignoring OG image on first share.
But I have already added those tags. Please suggest where am I wrong.


text:
Q: Parsing a CSV File i am trying to convert my xls file into csv and parse it in php
Here is sampled converted cvs Windows conversion separated by commas
DFRWR2496W/BND*,,2.65 ,2.52 ,3.98 ,910,856,1126,
DFWR0006-RD.50W,,2.43 ,2.31 ,3.65 ,380,331,578,
DFWR0006-RD.75W,,3.50 ,3.33 ,5.25 ,490,419,775,
DFWR0006-RD1.0W,,4.44 ,4.22 ,6.66 ,610,520,972,

IN Php i am trying to pase the xxxx.csv file as
$file_handle = fopen("price.csv", 'r');
    while (!feof($file_handle) ) {
        $line_of_text[] = fgetcsv($file_handle, 1024,"\r");
    }
    fclose($file_handle);
        return $line_of_text[0];
However $line_of_text[0] is giving me
["DFRWR2496W\/BND*,,2.65,2.52,3.98,910,856,1126","DFWR0006-RD.50W,,2.43,2.31,3.65,380,331,578","DFWR0006-RD.75W,,3.5,3.33,5.25,490,419,775","DFWR0006-RD1.0W,,4.44,4.22,6.66,610,520,972","DFWR0006-RD1.0Y,,4.44,4.22,6.66,610,520,972","DFWR0006W\/BND,,2.47,2.35,3.71,385,335,586","DFWR0007-RD.50W,,4.54,4.31,6.81,575,483,945","DFWR0007-RD1.0W,,5.28,5.02,7.92,675,568,1105","DFWR0007-RD1.0Y,,5.28,5.02,7.92,675,568,1105","DFWR0007W\/BND,,2.55,2.42,3.83,385,333,593","DFWR0008BD-RD.50W,,4.96,4.71,7.44,825,725,1229","DFWR0008-CSH1.0W,,4.62,4.39,6.93,1075,982,1451","DFWR0008-RD.50W,,4.81,4.57,7.22,1075,978,1467","DFWR0008-RD.75W,,4.81,4.57,7.22,1075,978,1467","DFWR0008-RD1.0W,,4.59,4.36,6.89,1075,982,1449","DFWR0008-TRD7.0W,,5,4.75,7.5,1075,974,1482","DFWR0008W\/BND,,2.23,2.12,3.35,460,415,642","DFWR0012BD-RD.50W,,4.56,4.33,6.84,580,488,951","DFWR0012P-RD.50TTR***,,4.56,4.33,6.84,835,743,1206","DFWR0012-RD.50TTR,,4.31,4.09,6.47,725,638,1076","DFWR0012-RD.50TY,,5.29,5.03,7.94,725,618,1156","DFWR0016W,,2.1,2,3.15,575,533,746","DFWR0028-PRD10x6.5W,,4.05,3.85,6.08,1000,918,"

Now that is not one line
DFRWR2496W/BND*,,2.65 ,2.52 ,3.98 ,910,856,1126,

It seems its taking maybe 1024 characters? How am i suppose to parse it like it shows in excel

A: fgetcsv is not detecting line endings, add this before call to fopen:
ini_set('auto_detect_line_endings', true);
Processing CSV File in PHP that able to cater MS and UNIX Line Break


text:
Q: Getting maple to output graphs/charts in a vector graphics format I've drawn some histograms and time series graphs in Maple 13 that I'd like to output as vector graphics (ideally pdf, but eps or svg or whatever would be ok too). This is because I want to \include them in a LaTeX document, and the pngs I have so far look all bitmappy and ugly. How do I get Maple to do this?

A: You can actually just right click and select "export as eps". I'm not entirely sure how I missed this...


text:
Q: How can I solve fatal compiler errors when installing GLScene into RAD Studio 2010? I'm trying to install GLScene into RAD Studio 2010, with the aim of using it from a mostly C++ project. I downloaded the latest snapshot (5991, November 2011) and have been trying to compile and install the two main packages:  GLScene_DesignTime and GLScene_RunTime. I haven't even tried some of the other libraries (CUDA, etc), I just want to get the base packages running.
I've encountered a number of problems, one of which I can't solve, and I'm seeking the help of anyone on SO who has successfully installed GLScene, or might know how to solve these Delphi compiler errors.
First problem (solved?)
When compiling, a number of files gave the following error:
[DCC Warning] GLSelection.pas(297): W1025 Unsupported language feature: 'abstract class method'

This is caused by a method declaration something like:
TGLBaseSelectTechnique = class
  public
    class function IsSupported: Boolean; virtual; abstract;

It seems that a virtual abstract class method is not supported in Delphi 2010, and I have solved it by removing 'abstract' and providing a dummy implementation, e.g. just returning false.
The second problem (not solved) - Delphi compiler fatal errors
I am now encountering two more serious errors. When compiling, the compiler fails like so:
[DCC Fatal Error] Exception EAccessViolation: Access violation at address 05AE8ED9 in module 'dcc140.dll'. Read of address 00000003
[DCC Error] Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED))

It doesn't say what file caused this, but I think it's caused by Spline.pas. Occasionally and not as often, I get this:
[DCC Fatal Error] Spline.pas(1): F2084 Internal Error: AV062D8ED9-R00000003-0

This indicates Spline.pas, and I think the first error is probably related to the file too, because after getting the first one if I then clean the project, cleaning will fail saying it could not delete Spline.hpp. (I have to close and reopen the IDE.) Spline.hpp just contains the following:
// CodeGear C++Builder
// Copyright (c) 1995, 2009 by Embarcadero Technologies, Inc.
// All rights reserved

// (DO NOT EDIT: machine generated header) 'Spline.pas' rev: 21.00

#ifndef SplineHPP
#define SplineHPP

#pragma delphiheader begin
#pragma option push
#pragma option -w-      // All warnings off
#pragma option -Vx      // Zero-length empty class member functions
#pragma pack(push,8)
#include <System.hpp>   // Pascal unit
#include <Sysinit.hpp>  // Pascal unit

and there it stops.  It looks to me like it failed when trying to generate the HPP file.
I always get one of these two failures.  The second is the only one I can tie to a specific file; the first fails halfway through the project, but I can't see where it got up to when it failed.  I am compiling from inside the IDE.
I've looked in Spline.pas, and it seems pretty basic code - I can't see anything unusual at all. You can find it here, and apparently the file hasn't been touched for seven years... so I think it should compile :)
If I change the project settings so it does not generate headers, it compiles fine. (Generating just obj files, and any other of the settings that does not include "headers", all work fine.) But this isn't a good workaround for me - after all, I need to use it from C++ Builder, so my normal setting would be "Generate all C++ Builder files". At a bare minimum, I need HPP and OBJ files.
Has anyone here used GLScene in a recent version of C++ Builder? Have you encountered similar problems? Any idea how to solve this one?
I am using:

*

*RAD Studio 2010 (fully patched and up to date; DDevExtensions and IDEFixPack installed.)

*The November 2011 snapshot; I tried the March 2011 snapshot too, and got the same problems.  Link to snapshots here.

*The Delphi 2010 packages modified only by changing the linker output to generate C++ Builder files; and also the BCB 6 packages.  Both give the same errors.

A: Edit: GLScene now has compatibility with RAD Studio XE3 (including C++ Builder.)

Now there is full compatibility of GLScene with Embarcadero RAD Studio
  C++Builder XE3 as in design and runtime mode.
You can download it from http://yadi.sk/d/o1QGI2KA10MK1 (95Mb)

-- from Pal Wassail's post on the Embarcadero forum thread.

{quote:title=David M wrote:}{quote}
  Hi,
I'm trying to install GLScene into RAD Studio...
  David

And here is more simple Test for EMB developers of Delphi XE3 header generator -
1.Create a VCL Form Application
2.Add in Unit1.pas interface section
type
 TVector3f = array[0..2] of single;
 TVector4f = array[0..3] of single;

 function VectorAdd(const v : TVector3f; const f : Single) : TVector3f; overload;
 function VectorAdd(const v : TVector4f; const f : Single) : TVector4f; overload;

3.Add in implementation section
function VectorAdd(const v : TVector3f; const f : Single) : TVector3f;
begin
  Result[0]:=v[0]+f;
  Result[1]:=v[1]+f;
  Result[2]:=v[2]+f;
end;

function VectorAdd(const v : TVector4f; const f : Single) : TVector4f;
begin
   Result[0]:=v[0]+f;
   Result[1]:=v[1]+f;
   Result[2]:=v[2]+f;
   Result[3]:=v[3]+f;
end;

*

*Set Delphi Compiler option "Generate C++ .objs, headers, namespaces, export"

*Build the project

*Then Delphi XE3 compiler generates wrong header file Unit1.hpp with lines:
extern PACKAGE TVector3f __fastcall VectorAdd
  (float const v, const float f)/ overload   */;
extern PACKAGE TVector4f __fastcall VectorAdd
  (float const v, const float f)/ overload */;

*If now you are trying to use this header file Unit1.hpp in my.cbproj you get fatal error:
"E2238 Multiple declarations in …"
Yes, if you change vector array types to records:
 TVector3f = record
    case boolean of
      true  : (Coord: array[0..2] of single);
      false : (X,Y,Z: single);
end;

*

*then the problem could be solved, because in this case Delphi compiler generates
extern PACKAGE Vectortypes::TVector3f __fastcall VectorAdd
   (const Vectortypes::TVector3f &v, const float f)/* overload */;
extern PACKAGE Vectortypes::TVector4f __fastcall VectorAdd
   (const Vectortypes::TVector4f &v, const float f)/* overload */;
and you could build your C++Builder VCL application without "Multiple declaration " error. It was done for old GLScene version in 2007, but now you need to rewrite some part of code  in new library, starting from VectorGeometry.pas module.

*

*There are second way to fix such automatic header's errors - improvement of Delphi compiler in Generating C/C++ headers, namespaces and packages option. But it's in hands of EMB developers.

A: Here's how I do it:

*

*Download and extract this ZIP file (directly into the root folder of GLScene, allowing it to overwrite as necessary)

*Load up the appropriate RAD Studio version (2007 to XE2) and open the file *GLScene_Group.groupproj* (where  = your RAD Studio version)

*Build/Install each Package in group order

I have carefully assembled these fixed packages to ensure they all install and function properly from 2007 to XE2. Some packages (at the bottom of each group) require additional dependencies to function (such as the Python package) so be mindful of these.
I have tested and confirmed that these work on RAD Studio 2007 to XE2 only.
Don't forget to add the \Source folder (and all subfolders) to the Search Paths (either for the IDE itself or an individual Project, as you desire) otherwise the projects using GLScene components will fail to compile complaining of missing units.
Enjoy!

A: Not for RAD Studio 2009 but for old GLScene installation in BCB6 she was running well.  But current version after installation in RAD Studio XE/XE2/XE3 does not work at all. It seems that the main problem is hidden in overload mechanism of procedures in Vectorgeometry.pas, so  Delphi compiler (with using an option for Output of all C++ files and packages) creates coincident strings in Vectorgeometry.hpp and others. Thus you have visual components in C++Builder panel, but your application fails with errors during building. It must be repaired in .pas files by GLScene developers.
When you trying to build an application with GLScene under C++Builder XE3 you will get  over 50 BCC32 errors in glcrossplatform.hpp, vectorgeometry.hpp and so on. There is a way to repair the library on your own discretion. Make a new copy of GLScene directory. In GLCrossPlatform.pas rename the procedure RGB to GLRGB (it's work!). Then in  VectorGeometry.pas and in many others files of source codes change all overload procedures with slightly different parameter names, so you should't encounter coincident procedures in .hpp files after Delphi option output C++ (last option that includes packages). Then rebuild all GLScene packages. At the end of the process I hope it should work for C++Builder XE3.

A: I have exact he same errors.
@The second problem
Go to "spline.pas" and change
TCubicSplineMatrix = array of array[0..3] of Single;
to
TCubicSplineMatrixEx = array[0..3] of Single;
TCubicSplineMatrix = array of TCubicSplineMatrixEx;
Now "Rad Studio 2009" can compile and install GLScene for C++Builder. I can start a new C++Builder VCL Application and select GLScene components from the toolbox and drop in my VCL form.
I think, this is the solution for your basic problem, but unfortunately I can not compile my VCL project successful. I get over 50 BCC32 errors in glcrossplatform.hpp and vectorgeometry.hpp. If anyone can help here, that would be great.
@Your First problem
I get this warnings too, but I have nothing changed for it. Just ignore it?!


text:
Q: Returning IDs for which an entire session matches criteria My table, T, is like this
   id        event       category    request

    1        click           a          1
    2        click           b          2
    1        click           b          2
    1        cart_add                   3
    3        click           a          1
    3        card_add                   2
    3        purchase                   3
    2        click           c          1
    2        card_add                   3
    1        purchase                   4

and I want to return visitors who clicked category b products and added a category b product to their cart, as well as those who made a purchase after that. So, both people who added category b products and those who made category b product purchases.
My issue is basically querying the session. They're not generally in order, and the actual table I'm using is million of rows so ordering is very time consuming.
Is there a nice trick to find all ids which meet the above criteria, or is it easier to just do the analysis in R or Python? More specifically, from the table above, I'd return
purchased    added

    1          1
   null        2

A: Assuming that id identifies a session.  This finds sessions that do all three:
select id
from t
where (event = 'click' and category = 'b') and
      (event = 'cart_add') and
      (event = 'purchase')
group by id
having count(distinct event) = 3;

If you need for the purchase to be later than the other two, then add:
max(case when event = 'purchase' then request end) > greatest(min(case when event = 'click' then request end), min(case when event = 'card_add' then request end))


text:
Q: file is not empty however python outputs the file as empty in list form? I am trying to access the contents of a file in list form, I try that and the file returns empty, it wont recodnise breaklines and the file is definitly not empty can anyone explain this...
   with  open("scores.txt","a+") as filescores:

        scores=list(filescores)
        print(scores)

output:
[]
thanks!

A: Have a close look at the open function.
To read a file, you use open("scores.txt","r"). a is for appending.

A: Consider the open mode of a+ The file has been opened for appending and therefore, the file pointer is at the end of the file. The + allows the file also to be read, but read from where? From the end!
Easy to demonstrate.
First, create a file:
from pathlib import Path

p=Path('/tmp/file')

with open(p, 'w') as f:
    f.write('\n'.join([str(e) for e in range(10)]))
    # file will be '0\n1\n2\n'...

Now open that file with a+ mode:
with open(p, 'a+') as f:
    l=list(f)

>>> l
[]

l is empty because f is at the end of the file. Easy to change too:
with open(p, 'a+') as f:
    f.seek(0)        # reposition the file pointer to the start of file
    l=list(f)

>>> l
['0\n', '1\n', '2\n', '3\n', '4\n', '5\n', '6\n', '7\n', '8\n', '9']

Or, just use the r for read mode and the file pointer will be at the start of the file:
with open(p, 'r') as f:
    l=list(f)
# ['0\n', '1\n', '2\n', '3\n', '4\n', '5\n', '6\n', '7\n', '8\n', '9']


text:
Q: LaTeX3: Function scope If I get it right, a token list is declared globally but can be assigned locally. So all local variables with the same name are actually declared globally as the same one. Functions often need to use local variables, and it is difficult to ensure these local variables have no name clash. For example:
\documentclass{article}
\usepackage{expl3}
\begin{document}
\ExplSyntaxOn

\tl_new:N \l_module_my_tl

%%  Example 1: A function group is wanted.

\cs_new:Npn \module_outer:
{
    \tl_set:Nn \l_module_my_tl { outer }
    \tl_show:N \l_module_my_tl
    \module_inner:
    \tl_show:N \l_module_my_tl
}

\cs_new:Npn \module_inner:
{{  %%  If you change this to { you'd get wrong result.
    \tl_show:N \l_module_my_tl
    \tl_set:Nn \l_module_my_tl { inner }
    \tl_show:N \l_module_my_tl
}}  %%  If you change this to } you'd get wrong result.

\module_outer:

%%  Example 2: A function group is unwanted.

\cs_new:Npn \module_tokens:
{   %%  If you change this to {{ you'd get wrong result.
    { 1 } { 2 } { 3 }
}   %%  If you change this to }} you'd get wrong result.

\tl_set:Nx \l_module_my_tl { \module_tokens: }
\tl_show:N \l_module_my_tl

\ExplSyntaxOff
\end{document}

In the first example of this code, both outer and inner functions use the same token list \l_module_my_tl. Unfortunately, the change in the inner function propagates to the outer function, which is unwanted. An easy solution is to add a function-level group for the inner function.
But this function-level group can cause problems if the function has output, as can be seen in the second example. If a function-level group is added, it would output {{1}{2}{3}} but not {1}{2}{3}.
What would be a general solution (a universal convention that programmers can follow without case-by-case attention) that makes both examples work?

A: In many programming languages such as Lua, a function or a condition expression makes a block, and the values of local variables will
be reset after a block. For example
---- lua code ----
local tmp = "a"
print(tmp)          ---- tmp=a
function SomeFun()
  local tmp = "b"
  print(tmp)        ---- tmp=b
  if 1 > 0 then
    local tmp = "c"
    print(tmp)      ---- tmp=c
  end
  print(tmp)        ---- tmp=b
end
SomeFun()
print(tmp)          ---- tmp=a

Recently I wrote functional package based on expl3. In this package, you can make every function (also every conditional) become a group by setting \Functional{scoping=true}.
% --- latex code --- %
\documentclass{article}
\usepackage{functional}
\begin{document}
\Functional{scoping=true}
\IgnoreSpacesOn
\TlSet \lTmpaTl {a}
\TlVarLog \lTmpaTl          % ---- a
\PrgNewFunction \SomeFun { } {
  \TlSet \lTmpaTl {b}
  \TlVarLog \lTmpaTl        % ---- b
  \IntCompareTF {1} > {0} {
    \TlSet \lTmpaTl {c}
    \TlVarLog \lTmpaTl      % ---- c
  }{ }
  \TlVarLog \lTmpaTl        % ---- b
}
\SomeFun
\TlVarLog \lTmpaTl          % ---- a
\IgnoreSpacesOff
\end{document}

Although there are functions in expl3, the evaluation of them is from outside to inside. With this new functional package, the evaluation of functions is from inside to outside, which is the same as other programming languages such as Lua or JavaScript. Here is another example for calculating square of an integer:
---- lua code ----
function MathSquare (arg)
  local lTmpaInt = arg * arg
  return lTmpaInt
end
print(MathSquare(5))
print(MathSquare(MathSquare(5)))

% --- latex code --- %
\documentclass{article}
\usepackage{functional}
\begin{document}
\IgnoreSpacesOn
\PrgNewFunction \MathSquare { m } {
  \IntSet \lTmpaInt { \IntEval { #1 * #1 } }
  \Result { \Value \lTmpaInt }
}
\IgnoreSpacesOff
\MathSquare{5}
\MathSquare{\MathSquare{5}}
\end{document}

You will find that there is an almost one-to-one correspondence between Lua code and functional code. I think this package is what you want.


text:
Q: OpenCV: Searching for pixels along single-pixel branches I'm currently trying to find a neat way of storing separate "branches" in a binary image. This little animation explains it:

As I go along the branches I need to collect the pixel indices that makes up a single-pixel wide branch. When I hit a junction point it should split up and store the new branches.
One way of going about it is maybe to create a 3x3 subregion, find out if there are white pixels inside it, move it accordingly, create a junction point if there is more than two. Always store the previous subregion so one can use it for making sure that we don't move to regions we already scanned.
It's a bit tricky to figure out how I would go about it though.
I basically need to reorder the pixels based on a "line/curve" hierarchy. Another part of the application will then redraw the figures, which internally works by creating lines between points hence the need to have them "ordered".

A: I don't know if you could apply it in your case but you should take a look at cv::findContour.
you will get a vector of points ordered.
http://docs.opencv.org/doc/tutorials/imgproc/shapedescriptors/find_contours/find_contours.html


text:
Q: Angular FormControl Validator Min initialized with variable does not update with variable changes I'm using Angular 8 and Material Components and want to restrict a value b to be greater than or equal to value a in a form using the min validator. I use two material inputs with a shared form control and bind them to parameters of a shared object. In my controller, I define the validator for b's form control as min(shared.a), assuming that with changes to shared.a, also the validator should be updated. For example, after setting a to 4 via the input, b should be invalid unless >= 4. However, the validator does not update with changes made to a but seems to be static with the initial value of a. What am I missing?
example.component.html:
<form [formGroup]="exampleForm">
  <mat-form-field>
    <input matInput type=number formControlName="a" [(ngModel)]="shared.a">
  </mat-form-field>

  <mat-form-field class="example-full-width">
    <input matInput type=number formControlName="b" [(ngModel)]="shared.b">
  </mat-form-field>
</form>

and example.component.ts:
export class Example implements OnInit {
  shared = {'a': 0, 'b': 1}
  exampleForm: FormGroup;

  constructor(private formBuilder: FormBuilder){ }

  ngOnInit() {
    this.exampleForm = this.formBuilder.group({
      a: [this.shared.a, Validators.min(0)],
      b: [this.shared.b, Validators.min(this.shared.a)]
    })
  }
}

Minimal working example on Stackblitz


text:
Q: How to use local conda environment over ssh I'm trying to run a model made using the fastai library on my home machine, but have to use my university facilities to run it. I have made a conda environment on my local machine with the required packages:
conda env create -f environment.yml #creates conda env called convml_tt
conda activate convml_tt

then connected to my uni and then their computing facility by ssh:
ssh username@remote-access.leeds.ac.uk
ssh username@arc3.leeds.ac.uk

However, when I have connected I can no longer find the conda environment I created locally-in fact conda is no longer found:
conda activate convml_tt

But I get the error:
-bash: conda: command not found

(it is not installed on the university accounts). I am new to this, is there something I'm overlooking?
I have done all of this in the same terminal session, could that be part of the problem?
When I have connected to the facilities I should be able to activate the conda environment and run my model from there:
conda activate convml_tt


text:
Q: Adding SearchBar to CollectionView I've created a CollectionView (as a CollectionViewController in IB) and it occurred to me that I should have a search function.
I want to add a SearchBar above my CollectionView in Storyboard, however it physically will not allow me and keeps sliding below which obviously won't work.
Is there a way to get around this, or do I need to rebuild my CollectionViewController from scratch with SearchBar at the top?
Can I add the SearchBar programmatically to the existing CollectionViewController?
See picture for reference:

A: I think the easiest way is to copy your collectionview to UIViewController & setting it to be delegate & datasource.
This way will allow you to add a searchbar above collectionview.
you can further detect searchbar text change & apply changes to collection view data.


text:
Q: Are there special permissions needed to use the crypto class? I have a routine using crypto class to encrypt data and store is a custom field.
This routine is working fine as long as I am logged in as an administrator.
when I login in as another user the data is not saved.
Are there special permissions needed to use the crypto class?
The myStr is a 32 character hidden strign;
the enir routin is here:
        Blob key = Blob.valueOf(myStr);
        Blob cipherText = Crypto.encryptWithManagedIV('AES256', key, val);
        String encodedCipherText = EncodingUtil.base64Encode(cipherText);
        System.debug(encodedCipherText);
        ld.z_encodedFEIN__c = encodedCipherText;
        update ld;


text:
Q: Using AngularJS how to check a PDF file exist in a folder or not? I have a list of students.
For some students I have to show a link, and on clicking this link their progress card should load (it is a .pdf file). For others, the link should not be shown.
I have done this by giving the same student id to their progress card and if it is this particular student then show the link; otherwise, don't show the link. I can do it this way for only 5 or 6 students. I cant do this for 1000 students.
The following is my AngularJS code:

if (response.student_id == 'SD0001' || response.student_id == 'SD0002' || response.student_id == 'SD0004') {
    $scope.pdfData = true;
    $scope.StudentPDFFile =  response.student_id+'.pdf';
} else {
    $scope.pdfData = false;
}

            Download Performance Report
             click here

Here I haven't specified the controller, this is skeleton functionality is working for me.
For 1000 records how I can do this?

A: This is another way.
You can make a directive and verify an attrib with this directive and set anything you want in the element.
JS
angular.module('myApp')
.directive('imgCheck', ['$http', function($http){
        return {
            link: function(scope, element, attrs){
                $http.get('/img/'+attrs.imgCheck)
                     .success(function(data, status){
                        if(status==200){
                            attrs.$set('src','/img/'+attrs.imgCheck)
                        }else{
                            attrs.$set('src','/img/not-found.png')
                        }
                     })
                     .error(function(data,status){
                        if(status==200){
                            attrs.$set('src','/img/'+attrs.imgCheck)
                        }else{
                            attrs.$set('src','/img/not-found.png')
                        }
                     });
            }
        };

}]);
HTML

A: You can make a http request to determine if the file exists as long as you are on the same domain as the pdf file.
For a given student ID (which in your code appears to be response.student_id) it looks like this:
if(response.student_id) {
    var url = 'http://www.example.com/s-pdf/' + response.student_id + '.pdf';
    var request = new XMLHttpRequest();
    request.open('HEAD', url, false);
    request.send();
    if(request.status == 200) {
        $scope.pdfData = true;
        $scope.StudentPDFFile =  response.student_id+'.pdf';
    } else {
        $scope.pdfData = false;
    }
} else {
    $scope.pdfData = false;
}

The 'HEAD' is all that is necessary to ensure that the file exists; you could also use 'GET' but it doesn't seem like you need the whole file in this situation.

A: ng-show seems more appropriate:

     Download Performance Report
      click here

For 1000, put it in a ng-repeat then you should better, test all the PDFs in one request and keep it in a cached list.

A: Its very simple bro, you just have to use ng-reapeat and ng-show. Below is my code with fiddle example, I hope it works for you.
HTML:

List of Students

          Student Name :  {{student.name}}

Download PDF

JS:
angular.module('studentApp', [])
  .controller('studentController', ['$scope', function($scope) {
    $scope.students = [
        {name: 'John', url:'abc.com/files/1.pdf'},
        {name: 'Peter', url:''},
        {name: 'Kerry', url:'abc.com/files/1.pdf'},
        {name: 'Silly', url:'f'},
        ]

  }]);

Example: http://jsfiddle.net/asadalikanwal/3a2zvrht/3/
Just change the PDF path with you once. If you have any question shoot


text:
Q: InvalidSelectorException using CSS selector to locate "data-" attribute notated elements Motivation
To utilize Selenium's CSS selector mechanism alongside with CSS attribute selectors and the HTML5 data- custom attribute to address specific hooks for elements.
Issue
While using the above to locate an element assigned with a CSS classname and the data- attribute, the following exception is thrown:
Caused by: org.openqa.selenium.remote.ErrorHandler$UnknownServerException: The given selector .gs-a-btn["data-value"] is either invalid or does not result in a WebElement. The following error occurred:
[Exception... "An invalid or illegal string was specified"  code: "12" nsresult: "0x8053000c (NS_ERROR_DOM_SYNTAX_ERR)"  location: "file:///C:/DOCUME~1/eliranm/LOCALS~1/Temp/anonymous6109849275533680625webdriver-profile/extensions/fxdriver@googlecode.com/components/driver_component.js Line: 5956"]
Build info: version: '2.23.1', revision: '17143', time: '2012-06-08 18:59:28'
System info: os.name: 'Windows XP', os.arch: 'x86', os.version: '5.1', java.version: '1.6.0_31'
Driver info: driver.version: unknown
    at <anonymous class>.<anonymous method>(file:///C:/DOCUME~1/eliranm/LOCALS~1/Temp/anonymous6109849275533680625webdriver-profile/extensions/fxdriver@googlecode.com/components/driver_component.js:6537)

Relevant Code
public void previous(String type) {
    By cssSelector = By.cssSelector(".gs-a-btn[data-value='" + type + "']");
    driver.findElement(cssSelector).click();
}

What have I tried

*

*replacing single quotes with escaped double quotes inside the attribute selector query.

*specifying attribute selector instead of attribute-value selector, i.e. ".gs-a-btn[\"data-value\"]" rather ".gs-a-btn[data-value='" + type + "']".

*to look up information in references, such as the Selenium Reference, for any restrictions on CSS attribute selectors. the document specifically states that:

Currently the css selector locator supports all css1, css2 and css3
  selectors except namespace in css3, some pseudo classes(:nth-of-type,
  :nth-last-of-type, :first-of-type, :last-of-type, :only-of-type,
  :visited, :hover, :active, :focus, :indeterminate) and pseudo
  elements(::first-line, ::first-letter, ::selection, ::before,
  ::after).

A: The reference you linked is for Selenium IDE.
Selenium WebDriver documentation can be found mainly on the official site here (basic usage) and here (advanced usage), but also here (a.k.a "What didn't make it into the docs yet" - especially the FAQ, Advanced User Interactions and lots of info about Selenium internals). The main source of information are, of course, the JavaDocs.

Anyway. The CSS Selectors supported by Selenium are those supported by the browser beneath it (with the exception of Selenium RC which has a Sizzle CSS engine), so your example should definitely work. Using this simple testpage:
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
    </head>
    <body>
        <input type="text" id="myInput" class="field" data-test="testytest" />
    </body>
</html>

I was able to sucessfully run this in both IE 8 (!!) and Firefox 13:
WebDriver driver = new FirefoxDriver();
driver.get("path to the file");
By cssSelector = By.cssSelector(".field[data-test='testytest']");
        // or By.cssSelector(".field[data-test=testytest]")
        // or By.cssSelector(".field[data-test]")
driver.findElement(cssSelector).sendKeys("Hello");
driver.quit();

So I digged more. If you try to run any of this in FF13 Firebug console:
document.querySelector(".field[data-test]")
document.querySelector(".field[data-test=testytest]")
document.querySelector(".field[data-test='testytest']")

it returns the right element. However, any of this:
document.querySelector(".field['data-test']")
document.querySelector(".field[\"data-test\"]")

fails with "An invalid or illegal string was specified" error (both in Firefox and IE) which is correct (and, therefore, the error message you got was right, the selector is invalid).
Please, try once more, get rid of any quotes, make sure your type variable doesn't contain any quotes or backslashes or whatnot. The construct should definitely work. If it doesn't, post the new exception stack trace so we can see the exact selector that caused it.

A: I was also getting the same exception.
So I tried it by locating element through Xpath instead of Css selector and the problem was solved
Below was the Code having the problem
By.CssSelector("Css selector").GetAttribute("value");

Code which worked
By.XPath("Xpath of element").GetAttribute("value");


text:
Q: Const vs Final in C++ I was learning OOPS in C++ and I came across keywords const and final. Now I am having a doubt what is the difference between them.

A: I suppose this question needs an answer, given the other answers present.
You cannot apply final to variables in C++, so the question "which one is better" can only be answered with "const, because only this can compile".

final specifier was introduced to C++11 and can be applied:

*

*to classes, in this case class cannot be used as a base class

class A final {};
class B: public A {}; //error

*to virtual function, to prevent derived classes from overriding it

class A {
    virtual void foo() = 0;
};
class B: public A {
    void foo() final {}
};
class C: public B {
    void foo() {} //error
};

const keyword was in C++ since the very beginning and is used to

*

*mark variables as non-modifiable. Non-member variables must be initialized where they are declared, member must be initialized in constructor initializer list. It's not like final in Java, you cannot assign to it once.

const std::vector<int> v;
v = std::vector<int>{}; //error
v.push_back(1); //error

*to mark class member functions as usable with const objects. This also prevents you from modifying class members inside that function

class A {
    int n;
public:
    int getN() const {return n;}
    void setN(int n) {this->n = n;} //cannot be const, modifies a member
};

const A a;
a.getN(); //fine
a.setN(5); //error

A: No, that is not what final is used for.  You might be confusing it with the use on other languages.
As you can see here, final is not used when declaring variables at all.
const int val = foo();

This is how you define a variable that will not be changed, which is the situation you mention in your question.  final has nothing to do with it.  This might be similar to what final means in some other languages, since foo() is not known at compile time and the variable needs to be initialized and then not changed afterwards.  This is what const means in C++.
In C++, final is used to declare that a class will not be derived from, or a virtual function will not be further overridden.