text:
Q: Websphere hangs due to c3p0 I am using WAS 7.1 along with c3p0 (v 0.9.2.1)  & hibernate (3.2.6ga)
After some hours of usage Websphere hangs and I see this message in the log
[6/24/13 10:57:50:377 CEST] 00000031 ThreadMonitor W   WSVR0605W: Thread "WebContainer : 24" (00000048) has been active for 759356 milliseconds and may be hung.  There is/are 45 thread(s) in total in the server that may be hung.
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Object.java:196)
    at com.mchange.v2.resourcepool.BasicResourcePool.awaitAcquire(BasicResourcePool.java:776)
    at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:198)
    at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:170)
    at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:172)
    at com.mchange.v2.c3p0.PoolBackedDataSource.getConnection(PoolBackedDataSource.java:58)
    at org.hibernate.connection.C3P0ConnectionProvider.getConnection(C3P0ConnectionProvider.java:56)
    at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:423)
    at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:144)
    at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:119)
    at org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:57)
    at org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1326)
    at com.aaa.in.bbb.effort.daoImpl.GRDAO.getGroupList(GRDAO.java:60)
    at com.aaa.in.bbb.effort.delegate.GRBean.getGroupList(GRBean.java:40)
    at com.aaa.in.bbb.effort.action.GRAction.execute(GRAction.java:74)
    at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:419)
    at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:224)
    at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1194)
    at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:414)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:718)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:831)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1658)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:940)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:503)
    at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:181)
    at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3954)
    at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:276)
    at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:942)
    at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1592)
    at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:186)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:453)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:515)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:306)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:277)
    at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214)
    at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113)
    at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:165)
    at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
    at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
    at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
    at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
    at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
    at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
    at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1646)

I have no idea why the session is not closed. Here is the session code
public class HibernateUtil {
    private static final SessionFactory sessionFactory;
    static {
        try {
            Context ctx = new InitialContext();
            Object obj = ctx.lookup("HibernateSessionFactory");
            sessionFactory = (SessionFactory) obj;
        } catch (Throwable ex) {

            System.out.println("Initial SessionFactory creation failed: "
                    + ex.getMessage());
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static final ThreadLocal hibernateSession = new ThreadLocal();

    public static Session currentSession() {
        Session s = (Session) sessionFactory.openSession();
        hibernateSession.set(s);
        return s;
    }
    public static void closeSession() {
        Session s = (Session) hibernateSession.get();
        try {
            if(s != null)
            {
              hibernateSession.set(null);
              s.close();
              System.out.println("s!=null");
            }
        } catch (HibernateException e) {
            e.printStackTrace();
            System.out.println("Error occured in closesession()");
        }
        finally
        {
            s=null;
        }

    }
    public static void closeSession(Session session) {
         try {
            if(session != null)
             {
                session.flush();
                hibernateSession.set(null);
                session.close();
                session=null;

             }
        } catch (HibernateException e) {
            e.printStackTrace();
            System.out.println("Error occured in closesession(session)");

        }
    }
}

I checked the code and the request to close session is there but somehow the session itself is not being released by C3P0
The problem happens only after I introduced connection pooling. The reason I had to introduce connection pooling was to solve the max cursors errors reached in Oracle 11 (see Max cursors reached error in JSP + Hibernate)
has any one faced this errors? Any pointers?

A: The pool is waiting for Connections. If they never come, then you've likely exhausted it due to a Connection leak.
Please debug the leak using c3p0 config parameters unreturnedConnectionTimeout and debugUnreturnedConnectionStackTraces. See the discussion here.


text:
Q: OpenCV watershed on Grayscale image I am ready to pull my hair out, I have no idea what is going on.
I am performing watershed on an image I have. I have created markers for the watershed. I can apply the watershed on my original, 3 channel color image. HOWEVER, I need to do some image analysis prior to the watershed (noise reduction, etc., etc.).
Thus, the watershed applied to my original image does not turn out properly. Instead, I want to apply the watershed to an image with a distanceTransform applied, with my markers.
The relevant code:
# Need to watershed this
filled_img = filled_img.astype(np.uint8)
dist = cv2.distanceTransform(filled_img, cv2.DIST_L2, 0)

dist *= (1/dist.max())

dist3d = cv2.cvtColor(dist, cv2.COLOR_GRAY2BGR)

watershed_markers = cv2.watershed(dist3d, markers)
#watershed_markers = watershed(-dist, markers, mask=filled_img)

fig = plt.figure(figsize = (15,15))
plt.imshow(watershed_markers)

watershed_img = crop_img
watershed_img[watershed_markers==-1] == [255,0,0]

plt.figure(figsize=(20,20))
plt.imshow(watershed_img, 'jet')

However, no matter what I try, I get this error:
error                                     Traceback (most recent call last)
new_BSA.ipynb Cell 12 in <cell line: 10>()
      5 dist *= (1/dist.max())
      7 dist3d = cv2.cvtColor(dist, cv2.COLOR_GRAY2BGR)
---> 10 watershed_markers = cv2.watershed(dist3d, markers)
     11 #watershed_markers = watershed(-dist, markers, mask=filled_img)
     13 fig = plt.figure(figsize = (15,15))

error: OpenCV(4.5.5) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\segmentation.cpp:161: error: (-215:Assertion failed) src.type() == CV_8UC3 && dst.type() == CV_32SC1 in function 'cv::watershed'

Does anyone have any idea how to resolve this?
It is frustrating because my original image and the 3d distance image are both 3 channel images, I don't know why this error is showing up.
Any help is greatly appreciated
EDIT:
For a minimum reproducible example, I will start with my processed binary image, as I can't perform the watershed on my original image, which is shown here:
Original image
After processing, I get two binary images:
closing, on the left, which I use to obtain my markers, and filled_img on the right, which I want to apply the watershed to.
Processed image
From here, I extract the markers:
# Get difference between the two images, closing and filled_img
closing = closing.astype(np.uint8)
filled_img = filled_img.astype(np.uint8)
markers = cv2.subtract(filled_img, closing)

Then, I create a sure background from the image (areas close to the objects I know are background) by using dilation. Then, I extract the unknown regions, by using the difference between the sure foreground and my markers:
# sure background area
kernal = np.ones((3,3), np.uint8)
sure_bg = cv2.dilate(filled_img, kernal, iterations=3)

# sure fg area
sure_fg = markers

# unknown region
unknown = cv2.subtract(sure_bg, markers)

Then, following this example: https://docs.opencv.org/4.x/d3/db4/tutorial_py_watershed.html
I label my regions, ensuring that the unknown region is = 0, where the watershed will be flooded:
ret, markers = cv2.connectedComponents(sure_fg)
markers = markers+1

markers[unknown==True]=0

Here is an image of what the markers now looks like:
markers
Finally, from my initial post, I apply the watershed, where the error is appearing:
# Need to watershed this
filled_img = filled_img.astype(np.uint8)
dist = cv2.distanceTransform(filled_img, cv2.DIST_L2, 0)

dist *= (1/dist.max())

dist3d = cv2.cvtColor(dist, cv2.COLOR_GRAY2BGR)

watershed_markers = cv2.watershed(dist3d, markers)
#watershed_markers = watershed(-dist, markers, mask=filled_img)

fig = plt.figure(figsize = (15,15))
plt.imshow(watershed_markers)

watershed_img = crop_img
watershed_img[watershed_markers==-1] == [255,0,0]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Let A be a given 4x4 matrix. Find matrices $F_1,F_2,F_3$ such that $A=c_1F_1+c_2F_2+c_3F_3$, $F_1+F_2+F_3=I$ and $F_iF_j=0$ when $i\not = j$ Let $A=\begin{bmatrix}0 & 1 &0 & 1\\1 & 0 & 1 & 0\\0 & 1 & 0 & 1\\1 &0 &1 &0\end{bmatrix}$
Find matrices $F_1,F_2,F_3$ such that $A=c_1F_1+c_2F_2+c_3F_3$, $F_1+F_2+F_3=I$ and $F_iF_j=0$ when $i\not = j$.
So this seems to be a direct application of this theorem:

My attempt:
Suppose $A$ is the representation of an operator $T$ in some basis (not yet defined).
The characteristic values for $A$ (and $T$) are:
 $c_1=0$, $c_2= 2$, $c_3=-2$.
Let $W_i$ be subspace of the vectors associated to $c_i$.
We then  have:
$W_1=\langle(1,0,-1,0),(0,1,0,-1)\rangle$
$W_2=\langle(1,1,1,1)\rangle$
$W_3=\langle(-1,1,-1,1)\rangle$
So T is diagonalizable and we can apply the theorem.
So $E_1(a(1,0,-1,0)+b(0,1,0,-1)+c(1,1,1,1)+d(-1,1,-1,1))= a(1,0,-1,0)+b(0,1,0,-1)$
defines $E_1$.  It is analogous with $E_2$ and $E_3$.
We should have $T=c1E_1+c_2E_2+c_3E_3$ and so $[T] _B=c_1[E_1]_B+c_2[E_2]_B+c_2[E_3]_B$ for any basis B.
So now I choose B to be the basis $((1,0,-1,0),(0,1,0,-1), (1,1,1,1), (1,1,1,1))$ and define A to be the representation of T in that basis. Then
$[E_1]_B=\begin{bmatrix}1 & 0 &0 & 0\\0 & 1 & 0 & 0\\0 & 0 & 0 & 0\\0 &0 &0 &0\end{bmatrix}$
$[E_2]_B=\begin{bmatrix}0 & 0 &0 & 0\\0 & 0 & 0 & 0\\0 & 0 & 1 & 0\\0 &0 &0 &0\end{bmatrix}$
$[E_3]_B=\begin{bmatrix}0 & 0 &0 & 0\\0 & 0 & 0 & 0\\0 & 0 & 0 & 0\\0 &0 &0 &1\end{bmatrix}$
To my sorrow, these matrices accomplish all the conditions except the first one. Where did I go wrong?
Note: I realized that its not necessary to compute basis for the $W_i's$, since whatever basis I found  for each one, I will suppose that $A$ represents $T$ in that basis and so I will have for the $F_i's$ just ones and zeros depending on the dimension of the $W_i's$.

A: I didn't check your calculations, but assuming they are correct, you have found a basis of eigenvectors $\mathcal{B} = (v_1, \dots, v_4)$ for the matrix $A$ (or, equivalently, the operator $T = T_A \colon \mathbb{F}^4 \rightarrow \mathbb{F}^4$ defined using $A$ by left multiplication so $T_A(x) := Ax$). Since $\mathcal{B}$ is a basis of eigenvectors and $E_i$ are the corresponding projections, you indeed should have
$$ [T]_{\mathcal{B}} = \begin{pmatrix} 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 \\ 0 & 0 & 2 & 0 \\ 0 & 0 & 0 & -2 \end{pmatrix}, \\
[E_1]_{\mathcal{B}} = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 \end{pmatrix}, [E_2]_{\mathcal{B}} = \begin{pmatrix} 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 0 \end{pmatrix}, [E_1]_{\mathcal{B}} = \begin{pmatrix} 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 \end{pmatrix}$$
and so $[T]_{\mathcal{B}} = c_1 [E_1]_{\mathcal{B}} + c_2 [E_2]_{\mathcal{B}} + c_3 [E_3]_{\mathcal{B}}$ and in particular $T = c_1 E_1 + c_2 E_2 + c_3 E_3$. Looking at the representing matrices with respect to the standard basis $\mathcal{C}$ of $\mathbb{F}^4$, we must also have
$$ A = [T]_{\mathcal{C}} = c_1 [E_1]_{\mathcal{C}} + c_2 [E_2]_{\mathcal{C}} + c_3 [E_3]_{\mathcal{C}} $$
and so the matrices you are looking for are
$$ F_i := [E_i]_{\mathcal{C}} = [\operatorname{id}]_{\mathcal{C}}^{\mathcal{B}} [E_i]_{\mathcal{B}} [\operatorname{id}]_{\mathcal{B}}^{\mathcal{C}} = P [E_i]_{\mathcal{B}} P^{-1}$$
where $P = [\operatorname{id}]_{\mathcal{C}}^{\mathcal{B}}$ is a change of basis matrix whose columns are simply the eigenvectors $v_1, \dots, v_4$ of $A$.


text:
Q: What is terminal key code for Ctrl+Backspace I'm trying to find Ctrl+Backspace terminal keycode to make it delete whole words in shell.
While it is explained how to get those codes for arrows, Home, Del and such keys with cat or od commands:

*

*Fix key settings (Home/End/Insert/Delete) in .zshrc when running Zsh in Terminator Terminal Emulator

*what is terminal escape sequence for ctrl + arrow (left, right,...) in TERM=linux
or codes given directly here: https://code.google.com/p/mintty/wiki/Keycodes (^_ doesn't work for me)
I can't find a way to get Ctrl+Backpace code.
Any clues? Thanks.

A: The cursor- and home/end (editing-keypad) keys are different from the backspace key.  Those always send some type of escape sequence.  The backspace key does not.  It sends a single control character, which makes it a control sequence, rather than an escape sequence.  This distinction is used in the xterm manual.
Control/backspace (like any case where a control-modifier is applied to a control character) is a feature that may be provided by a terminal, but has no general meaning (much less a standard meaning).  rxvt (during the 1990s) used this combination to switch between ASCII BS (^H or 8) and DEL (^?, or 127).  xterm incorporated that in 1998 (patch #83) for the same purpose.  By the way, as a VT220 emulator, xterm refers to this as the "backarrow key" (VT200s had that, not a backspace key).
PuTTY does not appear to provide that feature; its behavior for control/backspace is the same as without the control-modifier.


text:
Q: How to stick custom header in React Native I am working on app where I have worked on app header . I have created custom component for header . Now I want to achieve stick header when user scroll down then I want to stick top header . Could someone please help me how to solve this issue .
Code
      <View>
        <Header navigation={navigation} newToken={this.state.token} />
        <SearchBar
          input={(value) => {
            this.onChangeTextDelayed(value);
            this.setState({
              subCategoriesShow: true,
              pharmLoader: true,
              inputValue: value,
              queries: [],
            });
          }}
          handleBlur={() => this.setState({ subCategoriesShow: false })}
        />
      </View>

A: You can do it by view and a scroll view.
<View style={{flex: 1, display: 'flex'}}>
    <View>
        <Header {...props}/>
    </View>
    <ScrollView style={{flex: 1}}>
        ... other things
    </ScrollView>
</View>

If this doesn't work you can try with
<ScrollView contentContainerStyle={{flex: 1}}>

instead of
<ScrollView style={{flex: 1}}>


text:
Q: Is there a way to dump a table data (json or csv) from the Google SQL Cloud via a REAST API in python? I am trying to locally dump a table data via a REST API from the Google Cloud SQL in python. I found a method with gcloud (description here) but I do not want to use this dependency. My question is if there is any way to download(on local storage) the data from a table without using gcloud or a proxy to the databse. Thank you!

A: In order to export your data to a CSV file, you need to export it in a bucket.  Here you can find an example on how to do it using REST. At this other documentation, you can try this API to see what you should expect to get as result.
On the other hand, if you do not have configured the access to your local, you can take a look at here that is another option if you do not want to use Cloud SQL Proxy.


text:
Q: Можно ли как-то открыть картинку на странице в PhotoSwipe? На странице есть картинка при клике на которую она должна открыться на весь экран, возможно ли такое реализовать с PhotoSwipe? В документации ничего похожего не увидел.
Если с PhotoSwipe так сделать не получится, у него есть какие-нибудь достойные аналоги?

A: Рабочий пример для Вашей задачи (в первую очередь смотрите JS) :

var openPhotoSwipe = function() {
    var pswpElement = document.querySelectorAll('.pswp')[0];

    //Указываем изображения и размеры
    var items = [
        {
            src: 'https://farm2.staticflickr.com/1043/5186867718_06b2e9e551_b.jpg',
            w: 964,
            h: 1024
        },
        {
            src: 'https://farm7.staticflickr.com/6175/6176698785_7dee72237e_b.jpg',
            w: 1024,
            h: 683
        }
    ];

    //Настройки
    var options = {
       history: false,
       focus: false,
        showAnimationDuration: 0,
        hideAnimationDuration: 0
    };

    //инициализируем галерею
    var gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
    gallery.init();
};
document.getElementById('btn').onclick = openPhotoSwipe;
<link href="http://photoswipe.s3.amazonaws.com/pswp/dist/default-skin/default-skin.css" rel="stylesheet"/>
<link href="http://photoswipe.s3.amazonaws.com/pswp/dist/photoswipe.css" rel="stylesheet"/>

<button id="btn">Open PhotoSwipe</button>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
                <button class="pswp__button pswp__button--share" title="Share"></button>
                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>
            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>


text:
Q: In SQL Server, which query performs better? --Suppose I want to:
UPDATE Foo SET Bar = 1 WHERE ID = 187

--OR I can accomplish the same by
UPDATE Foo SET Bar = 1 WHERE Bar <> 1 AND ID = 187

--OR I can accomplish the same by
IF EXISTS (SELECT * FROM Foo WHERE Bar <> 1 AND ID = 187)
UPDATE Foo SET Bar = 1 WHERE ID = 187

Assuming the queries above are all valid and have the same behavior (I know they might behave differently with certain triggers or with other database activity), is there a performance reason to choose one?  What if Bar is already 1 most of the time this runs?
The 2nd query seems like it would perform better and have fewer writes, but I'd assume SQL is smart enough to optimize this.
The 3rd query is going to do 2 seeks/scans/etc to find the row if Bar <> 1, but it might be faster in situations where it is already 1.

A: The long answer is always that you need to test in your environment with a couple variations, even with easy stuff :) .
But the biggest factor you need to to consider is indexing.
If your table is indexed on that id field, that will make a huge difference compared to being indexed on some other, unrelated column.
If it is indexed on Bar and not Id, then the search for Bar <> 1 might help.
If were indexed on both (id, bar), that might be optimal for this update.
And that might make it truly irrelevant which of your statements you choose.
Check out the links in this highly-voted post:
How to read an execution plan in SQL Server
Dump a bunch of records in your table on your target system, and try different combinations of

*

*indexing

*and queries

and see what you get.

A: Well, the first two queries will not produce the same results, unless all rows have an ID value =187.
The first query will update all the rows in your Table to have Bar=1 and ID = 187.
The second query will ensure that all rows with ID = 187 have a BAR value = 1
In general, the most simple SQL is a great place to start.
Update Foo SET BAR = 1 where ID = 187

As you performance tune, if there are a lot of rows that already have the BAR value = 1, then you could add:
WHERE BAR <> 1 and ID=187

to avoid extraneous updates, although engines may already optimize for this case, which is why starting with the most simple option and then analyze/tuning is generally best.

A: I recommend using where bar<>1 because it will update all rows with id =187 whether they need to be updated or not.  Why update 923,498 rows when you only need to update 11? It is just a good habit to be to add the where <>  clause. Sure it won't make much difference in small updates, but if it is habit, you will not forget when you need to do a big one.


text:
Q: Find a basis for the given subspace: confirmation I would like to have a confirmation if possible!
Let $V$ be the subspace of $\mathbb{R}^3$ given by the solution of the system
\begin{equation}
\begin{cases} x+6y-3z=0\\2x+12y-6z=0 \end{cases}
\end{equation}
Find a basis for $V$.
By solving the homogeneous system I can find $\infty^2$ solutions (as the two row vectors are linearly dependent) of the kind $(3z-6y,y,z)$, which can be rewritten as $z(3,0,1)+y(-6,1,0)$. Hence a basis is $(3,0,1),(-6,1,0)$ and the subspace is two-dimensional.
An example of solution is $(0,1,2)$, obtained by observing that for $y=,z=$ one has $2(3,0,1)+1(-6,1,0)=(0,1,2)$.
Is it all correct?

A: Yes, all what you have done is correct !

A: Ja, it is correct! In fact:$$
\begin{cases} x+6y-3z=0\\2x+12y-6z=0 \end{cases}
\text{ is equivalent to }
\begin{cases} x+6y-3z=0\\ \frac{2}{2}x+\frac{12}{2}y-\frac{6}{2}z=0
\end{cases}$$$$\text{and }\begin{cases} x+6y-3z=0\\ \frac{2}{2}x+\frac{12}{2}y-\frac{6}{2}z=0
\end{cases}
\text{ is equivalent to }
\begin{cases} x+6y-3z=0
\end{cases}
$$
then $x=-6y+3z$ with $y,z \in \Bbb{R} $. Therefore with $v \in \Bbb{R}^3$ we have $$\begin{align} v\in V &\leftrightarrow v=(-6y+3z,y,z)=y(-6,1,0)+z(3,0,1) \,\text{, with }y,z \in \Bbb{R} \\ &\leftrightarrow v \in \langle ((-6,1,0),(3,0,1)) \rangle \end{align}$$ In addition  $((-6,1,0),(3,0,1))$ is $\Bbb{R}$-linear independent then $((-6,1,0),(3,0,1))$ is basis for $V$ also $\dim_\Bbb{R}(V)=2$


text:
Q: Get last N records in a DynamoDB table Is there any way to get the last N records from a dynamodb table. The range key I have is the timestamp. So I could use the ScanIndex forward to order items chronologically.
But in order to query I need to have a hashKey condition, which I don't want to filter. Any thoughts?

A: DynamoDB is not designed to work this way. The items are distributed according to a hash on the HashKey in such a way that the order is not predictable.
Your options include:

*

*grouping the items under a single hash key (not recommended: you would overload a few servers with your data, and Amazon cannot guarantee your read/write capacity)

*scanning the whole table and keep the N most recent items (something like for (item in items) { if (item newer then oldest accumulated item) accumulate item; });

*partition your table into multiple tables (ie, instead of a table called Events, create one called Events20130705 for today's events, Events20130706 for tomorrow's events), and scan just like the previous option -- this way your scans are smaller

You could also maybe change your data model. For example, You could have one versioned entry that would keep references to the N most recent items. Or you could have something like a single counter that you'd increment and update N other entries under hashkeys such as recent-K where K is your counter mod N.
Maybe you could even use another tool for this job. For instance, you could have a Redis server to do this. Without knowing your use case with much more detail, it is hard to make a precise suggestion -- how scalable should this be? how reliable should it be? how much maintenance are you willing to perform? how much are you willing to pay for it?
It's usually better to embrace the limitation, know your constraints and be creative.

A: I'm not sure this is still relevant. I'm fairly sure you can use ScanIndexForward along with a rangeKey to get the latest value.


text:
Q: Redirect to index.php to prevent duplicate content I would like to redirect to index.php in url for seo reasons to prevent duplicate content without breaking the site.
https://www.example.com/index.php/fr/google [WORKS]
https://www.example.com/index.php/id/google [WORKS]
https://www.example.com/index.php - [NOT WORKING]
should redirect to
https://www.example.com/fr/google
https://www.example.com/id/google
https://www.example.com/
My nginx config looks as follows
location / {
        # Redirect index.php to root (prevent duplicate content)
        rewrite ^/(.*?)index\.php[^/] /$1? permanent;
        rewrite ^/(.*?)index\.php(?:/(.*))?$ /$1$2? permanent;

        try_files $uri $uri/ /index.php?$query_string;
    }

https://www.example.com/index.php is not getting redirect to https://www.example.com/


text:
Q: Is there an equivalent for docker testing something like tox for Python? tox allows you to test your code against different versions of Python. Is there something out there similar to tox that allows me to test my deployment code against different version of a distribution say like centos 7, 6.8, 6.5 etc ?

A: In most cases you would use some kind of Continuous Integration (CI) service, mostly coupled with some kind of version control system (VCS).
An example would be GitLab with GitLab CI or Gogs with drone.io. They use Docker containers to run your code and you can run your code in containers of different distributions.

A: You could check dox. See this blog article for a short overview. In summary dox behaves like tox but instead of running virtualenvs you are using docker containers.


text:
Q: SQL Server : Mapping table design I have 2 tables, Table A and Table B which have the following structure:

and

There is a 1-1 relationship between tables identified by Product_group in Table A and <campaign_month,campaign> in Table B.
For example, ' 1808 Product - Group 3a' = <'201808','group_3a'>.
I am trying to create a mapping table using Tables A and B which should contain 3 columns, namely, <Product_group, campaign_month, campaign>.
Since I am not able to join the two tables, I am looking for other ways of creating the mapping table.
Can someone point me in the right direction?

A: Consider the following, I am joining the two tables on the basis of whether the string in campaign column(without the _ ) is contained in product_group.
create table tablea(product_group varchar(50));
create table tableb(id_c int,campaign_month int, campaign varchar(50));

insert into tablea values('1808 Product - Group 3a')
insert into tablea values('1808 Product - Group 3b')
insert into tablea values('1808 Product - Group 1c - Test1')
insert into tablea values('1808 Product - Group 3s -1')
insert into tablea values('1808 Product - Group 4d')

insert into tablea values('1808 Product - Group 3a')
insert into tablea values('1808 Product - Group 3b')
insert into tablea values('1808 Product - Group 1c - Test1')
insert into tablea values('1808 Product - Group 3s -1')
insert into tablea values('1808 Product - Group 4d')

   select a.product_group, b.id_c,b.campaign_month,b.campaign
     from tablea a
left join tableb b
      on replace(a.product_group,' -',' ') like '%'+replace(b.campaign,'_',' ')+'%'

Demo link
https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=b1c19bc020e3a8a313ce78dd387f7c43


text:
Q: R sum list of data.frame with almost same structure Here is my question,
I have a list of data.frames. It's produced by same piece of codes with different data.
All of the data.frames looks like
US 100 (not guarantee to exist in another data.frame because data is different)
CA 50
...
Is there any fast/neat way to sum over all the data.frames?

A: I am not sure whether I have understood your problem correctly, but here a possible solution:
Try to put all your dataframes in a list, e.g., your_list=list(df1,df2,...)
Then use total_df=do.call(rbind,your_list) to combine all dataframes (row-wise).
After that you can use ddply(total_df,"country",function (x) sum(x$value)) to aggregate the data. Here, I have assumed that US and CA stand for entries in a country column and 100 and 50 for entries in a value column.


text:
Q: Spring Controller + Thymeleaf form generated by foreach (cannot get access to variables) In thymeleaf I generate "order book" with offers. It is being generated with another controller but I works fine. All data is being printed correctly. The problem is when I want to make an order. In @Controller I am not able to see variables from form. Here is a part of code of thymeleaf

    <form method="post" th:action="@{/makeOrder}" th:object="${cruise}" name="formOrder" modelAttribute="cruise">
         nameOfCruise
         id
         date
         cost
         start
         finish

             Interested?
                <input type="submit" value="order">

    </form>

I try to PostMapping method
@PostMapping(value = "/makeOrder")
public String order(@ModelAttribute Cruise cruise, Model model){
        logger.info(cruise.getNameOfCruise); //NULL
        if(cruise == null) //NOT NULL. It doesn't execute
            logger.info("Cruise is null);
        ...
}

I tried that way, but it had no other effect
public String order(@ModelAttribute("cruise") Cruise cruise, Model model)

Entity class
package com.zak.cruise.entity;

import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;
import java.sql.Time;
import java.time.LocalDate;

@Entity
@Table(name = "cruise")
@Getter
@Setter
public class Cruise {
    @Id
    @Column(name = "idcruise")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "name_of_cruise")
    private String nameOfCruise;

    @Column(name = "date")
    private LocalDate date;

    @Column(name = "time")
    private Time time;

    @Column(name = "cost")
    private int cost;

    @Column(name = "number_of_seats")
    private int numberOfSeats;

    @Column(name = "duration")
    private int duration;

    @ManyToOne
    @JoinColumn(name = "route_id_route")
    private Route route;

    @ManyToOne
    @JoinColumn(name = "ship_id_ship")
    private Ship ship;

    @Column(name = "description")
    private String description;

    public Cruise() {
    }

    public Cruise(String nameOfCruise, LocalDate date, Time time, int cost, int numberOfSeats, int duration, Route route, Ship ship, String description) {
        this.nameOfCruise = nameOfCruise;
        this.date = date;
        this.time = time;
        this.cost = cost;
        this.numberOfSeats = numberOfSeats;
        this.duration = duration;
        this.route = route;
        this.ship = ship;
        this.description = description;
    }
}

WHAT IS IMPORANT
cruise is NOT NULL any time and it's entity class.
Everything I want to get known is how to extract variables from form to work with them.
I count on your help, thank you in advance

A: Thymeleaf only does rendering, it does not magically add more data to form post over basic html. As such, a span element is not posted, only input elements are posted to controller.
So you'd either have to change all the span elements to input, or you can add a hidden input with the id value and get the corresponding Cruise object from database in the controller


text:
Q: Find last match in table range My original question was answered here. I've been trying to build on top of that to create a mirror action to what the original issue tried to resolve:
=SUMIFS( MyTable[Ending Account Balance], MyTable[Date], AGGREGATE( 15, 6, MyTable[Date] / ( MyTable[Ending Account Balance] <>"" ), COUNTIFS( MyTable[Date], "<="&D2, MyTable[Date], ">="&C2, MyTable[Ending Account Balance], "<>" ) ) )

I'd like to find first available Date value but counting UP from last given. The above works in its logic but always picks SECOND from last instead of the very last (D2) as I need it to. The reason for ">="&C2 is that, without it, I ran into the problem of when this formula is copied down the range it fills according to future dates but I need this to only apply to current time span.
Jan 8 balance of 222.00 is what I need to get in E2

A: Try
=SUM(MyTable[Ending Account Balance] * (MyTable[Date]=MAX(MyTable[Date])))

entered as an array formula (CTRL+SHIFT+ENTER).
Edit:
To have it match only within a range (C2 to D2 say):
=SUM(MyTable[Ending Account Balance] * (MyTable[Date]=MAX(MyTable[Date] *
  (MyTable[Date]>=C2) * (MyTable[Date]<=D2) )))

A: You are using the AGGREGATE¹ function's SMALL sub-function (15); it seems to me that you should be using the LARGE sub-function (14).
In E2 as,
=IF(COUNTIFS(MyTable[ending account balance],  "<>0", MyTable[date], ">="&C2, MyTable[date], "<="&D2),
    SUMIFS( MyTable[ending account balance], MyTable[date],
        AGGREGATE(14, 6, MyTable[date]/((MyTable[ending account balance] <>"")*(MyTable[date]>=C2)*(MyTable[date]<=D2)), 1))
   , "")

Filled down to E3 will result in a blank cell due to the COUNTIF function check.

¹ The AGGREGATE function was introduced with Excel 2010. It is not available in earlier versions.


text:
Q: Android - LiveData randomly doesn't trigger with the updated value (in depth question) Video demostration of the bug
At first watch the video to understand what is the bug: https://imgur.com/a/X9OVraS
I have mocked the code to automatically switch to the SmistamentoGiroCercaGiroFragment, go back to SmistamentoGiroTabFragment and add a new record to the database. In the 5th insertion the list is correctely updated, but the header counter is not updated and keep the value of 4. That happened because its specific LiveData is not correctely triggered.
Architecture
I'm using the MVVM approach along with Navigator for fragment navigation.
Activity
The activity is not a part of the problem. it just initializes the navigation graph and its lifecycle methods onPause, onDestroy... are never triggered as you can deduce from the video (obviously onCreate and onResume are called the moment in click on "SMISTAMENTO A GIRO")
Fragment
Two fragments are used in this demostration, SmistamentoGiroTabFragment (that has got child fragments as tabs but it's not important for the purpose of this question) and SmistamentoGiroCercaGiroFragment.
To switch from one to one, two actions are used:

*

*findNavController().navigate(SmistamentoGiroTabFragmentDirections.actionDashboardToCercaGiro...

*findNavController().navigate(SmistamentoGiroCartellaCarrelloFragmentDirections.actionGiroToDashboard...

So everytime I switch from one to one the entire lifecyle methods are called:
// Removed old fragment I am leaving
SmistamentoGiroCercaGiroFragment - onPause
SmistamentoGiroCercaGiroFragment - onDestroy
// New fragment just added
SmistamentoGiroTabFragment - onAttach
SmistamentoGiroTabFragment - onCreate
SmistamentoGiroTabFragment - onViewCreated
SmistamentoGiroTabFragment - onResume

And the other way.
Code
SmistamentoGiroTabFragment
In the onCreateView the LiveDate used to update the header counter is observed (for debug purpose, it is used in the layout):
smistamentoGiroTabViewModel.searchLVCount.observe(viewLifecycleOwner, Observer {
    Logger.debug("TestGrafico", "searchLVCount $it")
})

SmistamentoGiroTabFragment xml layout
app:bindInt is just a binding adapter that takes an Int and convert to String. Nothing important for this purpose.
<TextView
android:id="@+id/oggetti"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
app:bindInt="@{viewModel.searchLVCount}"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="18" />

SmistamentoGiroTabViewModel
val searchLVCount = smistamentoGiroRepository.searchLVCount()

searchLVCount directely in Dao
@Query("SELECT COUNT(codiceLdV) FROM SmistamentoGiroLV")
fun searchLVCount(): LiveData<Int>

How the insertion works
The fragment SmistamentoGiroTabFragment recieves from SmistamentoGiroCercaGiroFragment an object with the information to insert.
So at the end of the SmistamentoGiroTabFragment.onCreateView a method is called:
smistamentoGiroTabViewModel.handleArgs(args, activity().currentView)

Which leads to:
return smistamentoGiroLVDao.insert(smistamentoGiroLVEntity)

That inserts a record in the table observed by the fragment:
@Insert(onConflict = OnConflictStrategy.REPLACE)
Long insert(SmistamentoGiroLVEntity element);

Debug log:
The corresponding log of the test you have watched in the video is the following:
"TabWM init" is the following log in SmistamentoGiroTabViewModel:
init {
        Logger.debug("TestGrafico", "TabWM init")
    }

Log:
// First callback when opening the activity
TestGrafico - TabWM init
TestGrafico -
TestGrafico - searchLVCount 1

// First automatic insertion
TestGrafico - TabWM init
TestGrafico -
TestGrafico - searchLVCount 1
TestGrafico - searchLVCount 2

// Second automatic insertion
TestGrafico - TabWM init
TestGrafico -
TestGrafico - searchLVCount 2
TestGrafico - searchLVCount 3

// Third automatic insertion
TestGrafico - TabWM init
TestGrafico -
TestGrafico - searchLVCount 3
TestGrafico - searchLVCount 4

// Fourth automatic insertion
TestGrafico - TabWM init
TestGrafico -
TestGrafico - searchLVCount 4

As you can see I expected
TestGrafico - searchLVCount 5

But that's not triggered.
Conclusion
I have read the releated question Why LiveData observer is being triggered twice for a newly attached observer and every answer, but that is not helpful since they talk about the reason is being triggered twice and not why sometimes, it is not triggered the second time.
Update
SmistamentoGiroTabFragment fragment lifecycleOwner initialization:
override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
): View {
    var currentFragment: Fragment? = null
    val binding = FragmentSmistamentoGiroMainBinding.inflate(
            inflater, container, false
    ).apply {
        lifecycleOwner = viewLifecycleOwner

how ViewModel is initialized:
SmistamentoGiroTabFragment
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory

private val smistamentoGiroTabViewModel: SmistamentoGiroTabViewModel by viewModels {
    viewModelFactory
}

ViewModelModule (for Dagger injection)
@Binds
abstract fun bindViewModelFactory(factory: MagazzinoViewModelFactory): ViewModelProvider.Factory

@Binds
@IntoMap
@ViewModelKey(SmistamentoGiroTabViewModel::class)
abstract fun bindSmistamentoGiroTabViewModel(smistamentoGiroTabViewModel: SmistamentoGiroTabViewModel): ViewModel

ViewModelKey
@MustBeDocumented
@Target(
        AnnotationTarget.FUNCTION,
        AnnotationTarget.PROPERTY_GETTER,
        AnnotationTarget.PROPERTY_SETTER
)
@Retention(AnnotationRetention.RUNTIME)
@MapKey
annotation class ViewModelKey(val value: KClass<out ViewModel>)

MagazzinoViewModelFactory
@Singleton
class MagazzinoViewModelFactory @Inject constructor(
        private val creators: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>>
) : ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        val creator = creators[modelClass] ?: creators.entries.firstOrNull {
            modelClass.isAssignableFrom(it.key)
        }?.value ?: throw IllegalArgumentException("unknown model class $modelClass")
        @Suppress("UNCHECKED_CAST")
        return creator.get() as T
    }
}

Update 2
Here is the log of the bug with SmistamentoGiroTabViewModel addresses
TestGrafico - TabWM init SmistamentoGiroTabViewModel@467a7a4
TestGrafico - searchLVCount 18
TestGrafico - searchLVCount 19

TestGrafico - TabWM init SmistamentoGiroTabViewModel@3585336
TestGrafico - searchLVCount 19
TestGrafico - searchLVCount 20

TestGrafico - TabWM init SmistamentoGiroTabViewModel@3351174
TestGrafico - searchLVCount 20
TestGrafico - searchLVCount 21

TestGrafico - TabWM init SmistamentoGiroTabViewModel@c6c785f
// Bug occoured
TestGrafico - searchLVCount 21

Update 3
It's correct to have two values triggered by the observe, because the old value is the fragment/VM initialization, the new value is the result of the handleArgs method called (that leads to record insertion in db) at the end of the onCreateView as in-depth explainted above.

A: After one entire month of testing and analysis of the architectural elements of the project I have found the solution. In the initialization of the Room database I was using RoomDatabase.JournalMode.TRUNCATE.
The Google LiveData system is not completely compatible with the Room database journal mode TRUNCATE.
Here is  the ref link of the modes:
https://developer.android.com/reference/android/arch/persistence/room/RoomDatabase.JournalMode
What has to be used is WRITE_AHEAD_LOGGING (used by default). By using it, every random graphic errors disappeared.


text:
Q: How to remove duplicates usernames before a splitter in lines? I want to remove duplicated usernames in lines before the splitter : and keep only the first line of these usernames.
Lines Example:
zzzz:000000zl
zzzz:000000zl!
zzzz:000000zl1
zzzz:000000zl123
zzzz:000000zl69
zzzz:000000zl?
AdSFF12:Sample198445
AdSFF12:Sample198445!
AdSFF12:Sample198445#
AdSFF12:Sample198445$
AdSFF12:Sample1984456
TestOf13:Smpletest1211
TestOf13:Smpletest1211!
TestOf13:Smpletest1211#
TestOf13:Smpletest1211$
TestOf13:Smpletest12112
TestOf13:Smpletest561
TestOf13:Smpletest561!
TestOf13:Smpletest561#
TestOf13:Smpletest561$
TestOf13:Smpletest5612
TestOf13:SmpletestZ2
TestOf13:SmpletestZ2!
TestOf13:SmpletestZ2#
TestOf13:SmpletestZ2$
TestOf13:SmpletestZ23
TestOf13:Smpletestz3qwe
TestOf13:Smpletestz3qwe!
TestOf13:Smpletestz3qwe1
TestOf13:Smpletestz3qwe123
TestOf13:Smpletestz3qwe69
TestOf13:Smpletestz3qwe?

Result Needed:
zzzz:000000zl
AdSFF12:Sample198445
TestOf13:Smpletest1211

Your help will be much appreciated, thank you in advance <3.

A: *

*Ctrl+H

*Find what: ^((.*?:).+\R)(\2.+\R)+

*Replace with: $1

*CHECK Wrap around

*CHECK Regular expression

*UNCHECK . matches newline

*Replace all
Explanation:
^       # beginning of line
    (       # start group 1
        (       # start group 2
            .*?     # 0 or more any character but newline, not greedy
            :       # a colon
        )       # end group 2
        .+      # 0 or more any character but newline
        \R      # any kind of linebreak (i.e. \r, \n, \r\n)
    )       # end group 1
    (       # group 3, you can use (?: for non capture group
        \2      # back reference to group 2 (i.e. the part before the colon)
        .+      # 0 or more any character but newline
        \R      # any kind of linebreak (i.e. \r, \n, \r\n)
    )+      # end of group 3, may appear 0 or more times

Replacement:
$1          # content of group 1, the value of the first line

Screenshot (before):

Screenshot (after):


text:
Q: finding the taylor series for a function so im trying to find the taylor series representation of $\frac{1}{\sqrt{x}}$ around $1$.
i managed to find this so far:
$$
\sum_{n=0}^\infty \frac{(x-1)^n \cdot (-1)^n }{  2^n \cdot n!}
$$
the last thing im missing is in the numerator- but i cant figure out what exactly and how to represent it. Any ideas?

A: By using the binomial theorem, one has, for $|t|<1$,
$$
(t+1)^{-1/2}=1-\tfrac12t+\tfrac12\tfrac32\cdot t^2-\tfrac12\tfrac32\tfrac52\cdot t^3+\dots+(-1)^n\tfrac{1\cdot2\cdot3\cdots(2n-1)}{2\cdot4\cdot6\cdots2n}\cdot t^n+\cdots
$$ or, by putting $t=x-1$, as $x \to 1$
$$
\begin{align}
\frac1{\sqrt{x}}&=\frac1{\sqrt{t+1}}
\\\\&=1+\sum_{n=1}^\infty\:(-1)^n\cdot\frac{1\cdot2\cdot3\cdots(2n-1)}{2\cdot4\cdot6\cdots2n}\cdot(x-1)^{n}
\\\\&=1+\sum_{n=1}^\infty\:(-1)^n\cdot\frac{(2n)!}{2^{2n} (n!)^2}\cdot(x-1)^{n}.
\end{align}
$$

A: Why not just apply the binomial theorem? We note that $$\frac{1}{\sqrt{x}} = \frac{1}{\sqrt{1+(x-1)}} = [1+(x-1)]^{-1/2} =\sum_{n=0}^\infty(x-1)^n{-1/2 \choose n} $$
Note that we can turn this into your form by using the definition of Binomial Coefficients

A: If you're just looking for some compact notation, let me introduce to you the double factorial:  for $n$ odd,
$$
n!! = n \cdot (n-2) \cdot (n - 4) \cdots 1.
$$
So, if you take $a_n = (2n - 1)!!$, you have $a_1 = 1, a_2 = 3, a_3 = 15, a_4 = 105, a_5 = 1575$, and so forth;  this is exactly the sequence of odd coefficients that appears in the power series coefficients.


text:
Q: Configuring Restlet + JAX-RS-extension for Android Did anybody succed in configuring the JAX-RS-extension of Restlet to make it work on Android? There is no Android-specific release of the extension, but I would like to try it nevertheless.
Since Android Restlet doesn't support the autodiscovery mechanism, I need to know which classes must be injected manually.
Side Question (please answer with comment): Is there another REST framework which will work with Android and JAX-RS? I tried an unoffical Resteasy-Android-client, but it throwed StackOverflowErrors all along.


text:
Q: How to present a UIImageview modally in a UICollectionView I currently have a UICollectionView which consists of grid of images. What I want to do is, when I click on any particular image it should open a image view and I can pan around it.
Issues:

*

*Image view wont show the image.

*If I enable panning for the image view the whole grid view will move.

How do I avoid these problems?
This is what I have tried:
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    [self.collectionView registerNib:[UINib nibWithNibName:@"Cell" bundle:nil] forCellWithReuseIdentifier:@"CellID"];

    // Do any additional setup after loading the view, typically from a nib.
}

-(int)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{

    return 30;
}

-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    Cell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"CellID" forIndexPath:indexPath];
    cell.backgroundColor=[UIColor whiteColor];
    UIImageView *imgView=(UIImageView *)[cell viewWithTag:1];
    imgView.image=[UIImage imageNamed:@"57.png"];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    UIImageView *previewImage=[[UIImageView alloc]init];
    UIScrollView *imageScroll=[[UIScrollView alloc]init];
    imageScroll.clipsToBounds=YES;
    imageScroll.contentSize=previewImage.bounds.size;
    UIViewController *imageController=[[UIViewController alloc]init];
    imageController.view.backgroundColor=[UIColor whiteColor];
    [imageController.view addSubview:imageScroll];
    imageController.modalPresentationStyle=UIModalTransitionStyleCrossDissolve;
    imageController.modalPresentationStyle = UIModalPresentationFormSheet;
    [self presentViewController:imageController animated:YES completion:^{

    }];

}

Any pointers?

A: A couple of things:
You set the contentSize of your UIScrollView object imageScroll to be the size of the UIImageView object previewImage. Therefore you should set the frame of previewImage so imageScroll knows its contentSize and you should set the frame of imageScroll to ensure that it will scroll (remember the frame of a UIScrollView must be smaller than its contentSize). Something like this will work (you should change this to what you want):
UIImageView *previewImage=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
UIScrollView *imageScroll=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, 200, 200)];

You also did not add previewImage as a subview to imageScroll or set its image.
previewImage.image = //set image;
[imageScroll addSubview:previewImage];

With your UIScrollView set up correctly the user can easily pan around the imageView.

A: What you are effectively trying to do is build a viewcontroller hiearchy. You cannot do this as you have tried. You need to present it as a pop over controller at best for the UIImageView to even show. But then you cannot move it. So your approach wont work.
One idea might be to disable userinteraction on the UICollectionView and present your UIImageView as a subview on top of UICollectionView and then controller panning in the same controller that manages the UICollectionView.


text:
Q: Reducing left margin inside a TikZ node I would like to reduce the left margin inside this node:
\documentclass[a4paper,12pt,twoside]{article}
\usepackage{tikz}
\usepackage{enumerate}
\usetikzlibrary{shapes,arrows}
\begin{document}
\tikzstyle{block} = [rectangle, draw, text width=11em, text centered, minimum height=4em]
\begin{tikzpicture}[node distance=6cm, auto, >=stealth]
\node[block] (Example)
{\textbf{Example}
\begin{itemize}
\item First item: string
\item Second item: float
\item Third item: float
\end{itemize}};
\end{tikzpicture}
\end{document}

I'll appreciate a lot any help or advice!

A: The margin isn't introduced by the TikZ node, but by the enumerate environment. You can move your list to the left by adjusting the \leftmargini length, as explained in the answer to Changing left margin in itemize environment of beamer class.
\setlength{\leftmargini}{1.3em} works quite well in this case:
\documentclass[a4paper,12pt,twoside]{article}
\usepackage{tikz}
\usepackage{enumerate}
\usetikzlibrary{shapes,arrows}
\begin{document}
\tikzset{block/.style={rectangle,
  draw,
  text width=11em,
  text centered,
  minimum height=4em,
  execute at begin node={\setlength{\leftmargini}{1.3em}}
}
}
\begin{tikzpicture}[node distance=6cm, auto, >=stealth]
\node[block] (Example)
{\textbf{Example}
\begin{itemize}
\item First item: string
\item Second item: float
\item Third item: float
\end{itemize}};
\end{tikzpicture}
\end{document}

You can automatically execute this command in all of your block nodes by adding the key execute at begin node={\setlength{\leftmargini}{1.3em}} to the style definition.
On a side note, the PGF v 2.1 syntax for defining styles is \tikzset{<style name>/.style={<options>}} (instead of \tikzset{<style name>}=[<options>]).


text:
Q: Passing field value and tablename in a hyperlink field I've tried searching for this but I can't find what I need exactly. I have a gridview with data filled in from an access database. I have one hyperlink field databound to the id field which links to another page like page2.aspx?field=11.
I've got several pages going to page2 with an id, so I need to also send to page2 the name of the table the record is stored in, either by getting the name or manually typing it in.
I've found how to send multiple parameters, but if I type in the tablename I get an error that the field name cannot be found.
<asp:HyperLinkField DataNavigateUrlFields="DocID,tblDocs"
            DataNavigateUrlFormatString="Page2.aspx?field={0}&tblDocs={1}" HeaderText="SendFile"
            Text="Send"></asp:HyperLinkField>


text:
Q: Extreme values of function w/ rational power I'm trying to find the extreme value of the following function (in terms of $z$),
where $a$ is some positive real number:
$$f(z)=\frac{1}{\left(a+(z+a)^2\right)^{3/2}}-\frac{1}{\left(a+(z-a)^2\right)^{3/2}}$$
I have tried to find the root of its derivative:
$$f'(z)=\frac{-3(z+a)}{\left(a+(z+a)^2\right)^{5/2}}-\frac{-3(z-a)}{\left(a+(z-a)^2\right)^{5/2}}$$
$$0=\frac{-3(z+a)}{\left(a+(z+a)^2\right)^{5/2}}-\frac{-3(z-a)}{\left(a+(z-a)^2\right)^{5/2}}$$
$$\frac{z+a}{\left(a+(z+a)^2\right)^{5/2}}=\frac{z-a}{\left(a+(z-a)^2\right)^{5/2}}$$
I'm not sure how to proceed after this.
Graphically, I can see that the function is odd, with a minima at some positive $z$ and a maxima at some negative $z$ (extrema points are equidistant from 0).
Any help would be appreciated, thanks in advance!

A: $z$ for which $f'(z) = 0$ is a root of the irreducible polynomial
$$4 z^{10}+\left(20 a^{2}+15 a \right) z^{8}+\left(-24 a^{4}+20 a^{3}+20 a^{2}\right) z^{6}+\left(-24 a^{6}-70 a^{5}-20 a^{4}+10 a^{3}\right) z^{4}+\left(20 a^{8}+20 a^{7}-20 a^{6}-20 a^{5}\right) z^{2}+4 a^{10}+15 a^{9}+20 a^{8}+10 a^{7}-a^{5}$$
The quintic obtained by substituting $t$ for $z^2$ has Galois group $S_5$ for
typical values of $a$.
So you're not going to get a solution expressible in terms of radicals.
For particular values of $a$ you can solve it numerically.


text:
Q: Showing that for $\{u_n,u\}_{n \geq 1} \subseteq L^p(\Omega)$ it is $u_n \to u$ in $L^p(\Omega)$. Exercise :

Let $\Omega \subseteq \mathbb R^n$ be open and bounded, $\{u_n, u\}_{n \geq 1} \subseteq L^p(\Omega)$ with $1<p<\infty$ and we assume that $\|u_n\|_p \to \|u\|_p, \; u_n \xrightarrow{a.e.} u$. Show that $u_n \to u$ in $L^p(\Omega)$.

Attempt :
Since $\|u_n\|_p \to \|u\|_p$ then it is :
$$\|u_n\|_p^p \to \|u\|_p^p \Leftrightarrow \int_\Omega |u_n|^p \mathrm{d}x = \int_\Omega |u|^p\mathrm{d}x$$
To show that $u_n \to u$ in $L^p(\Omega)$, we need to show that $\|u_n - u\|_p \to 0$. But :
\begin{align*}
\|u_n-u\|_p^p &= \int_\Omega |u_n-u|^p\mathrm{d}x \\ &\leq \int_\Omega \left(|u_n| + |u|\right)^p\mathrm{d}x
\end{align*}
But from then on, I don't see how to continue in order to derive an expression of the form $\|u_n-u\|_p^p < \varepsilon$ where $\varepsilon > 0$.
Any hints will be greatly appreciated.

A: Since we know that $u_n\to u$ almost everywhere we can conclude that $|u_n-u|^p\to 0$ almost everywhere. Hence: (we will use Fatou lemma)
$2\int_{\Omega} |u|^pdx=\int_{\Omega}\lim_{n\to\infty}(|u|^p+|u_n|^p-|u-u_n|^p)dx\leq$
$\leq\liminf_{n\to\infty}\int_{\Omega}(|u|^p+|u_n|^p-|u-u_n|^p) dx=2\int_{\Omega} |u|dx-\limsup_{n\to\infty}\int_{\Omega} |u-u_n|^p dx$
In the last equality we used the fact that $\int_{\Omega} |u_n|^p\to\int_{\Omega} |u|^p$.
So what we got is that $\limsup_{n\to\infty}\int_{\Omega} |u-u_n|^pdx\leq 0$. Since this is a sequence of non negative real numbers this of course implies $\lim_{n\to\infty}\int_{\Omega} |u-u_n|^pdx=0$.


text:
Q: how to make titleBar of Flash mx.containers.Panel invisible? in FlashBuilder 4 beta 2, I've subclassed mx.containers.Panel, adding a public method to hide the titleBar:

    public function hideTitleBar(): void {

        if (null != this.titleBar){
            this.titleBar.visible=false;
        }
    }

I step through the code and see that the method is being invoked and that titleBar exists, and then step through the UIComponent classes and that all looks ok too: the component is initialized and $visible is being set to false.  Yet the gray bar across the top of the panel remains.  I want to eliminate that bar and would be grateful for some tips on how to do that.

A: What I ended up doing is to set the style headerHeight to 0
this.setStyle("headerHeight", 0);

A: The updateDisplayList method of the Panel sets titleBar.visible to true. Subclass the Panel class, override that method, and set it to false inside that. Don't forget to call super.updateDisplayList
override protected function updateDisplayList(unscaledWidth:Number,
                                              unscaledHeight:Number):void
{
    super.updateDisplayList(unscaledWidth, unscaledHeight);
    titleBar.visible = true;
}


text:
Q: Prove fractional integral at $\alpha = 0$ converges to the original function https://en.wikipedia.org/wiki/Riemann%E2%80%93Liouville_integral
Under the properties section, it says $I^{\alpha}f \rightarrow f$ as $\alpha \rightarrow 0.$ But it offers no proof, is there a proof of this somewhere?


text:
Q: how to decide sigma for FFT based Gaussian filter I am using a FFT-based guassian low pass filter and was wondering how to decide D0 in equation:
exp(-(D(u,v)^2/2D0^2))

Since I am filtering a 2D image, so how can I relate D0 to pixel size? For gaussian filter in the spatial domain, I typically use the standard deviation of the whole image as sigma (or multiple times of the standard deviation). So, is there a formula that can relate the standard deviation in the spatial domain to D0?
Thanks.


text:
Q: How do I get customized list as a output in python? I've this code.
character = input("Enter a character: \n")

def ASCIItoHEX(ascii):
    hexa = []
    for i in range(len(ascii)):
        ch = ascii[i]
        in1 = ord(ch)
        part = hex(in1)
        hexa += part
    return hexa

if __name__ == '__main__':
    hexadecimal = ASCIItoHEX(character)
    print(hexadecimal)

and it gives me output like this when I enter "1111":
['0', 'x', '3', '1', '0', 'x', '3', '1', '0', 'x', '3', '1', '0', 'x', '3', '1']
but I want my output like this:
['0x31', '0x31', '0x31', '0x31']
How to obtain this output?

A: Use list.append() instead += to append the whole string. Otherwise the string is treated as sequence and splittet into the characters.
character = input("Enter a character: \n")

def ASCIItoHEX(ascii):
    hexa = []
    for i in range(len(ascii)):
        ch = ascii[i]
        in1 = ord(ch)
        part = hex(in1)
        hexa.append(part)
    return hexa

if __name__ == '__main__':
    hexadecimal = ASCIItoHEX(character)
    print(hexadecimal)

Another way would be
hexa += [part]

to concatenate the two lists.


text:
Q: Adding keypress Events that use an existing function I have used a function which is activated on click events. I want to do the same using keypress events.
function addToText(target) {

  var exp = target.target;
  //alert(exp.value);
  if (newExp) {

    //clearText();
    document.getElementById("expression").value = exp.value;
    newExp=false;

  }

  else
    document.getElementById("expression").value = document.getElementById("expression").value + exp.value;

}

This is the function used. How do I modify it to use for keypress events also. Currently, it does not work initially(for keypress events). But after clicking once, then any keypress returns the same number that was previously clicked.
Full code here:http://codepen.io/jpninanjohn/pen/JXVpYb?editors=1010

A: Here's is your final solution, I test if charcode is between 48 and 57, what it means, numbers between 0 and 9.
   document.addEventListener('keypress', function(e){
      if (e.which >= 48 && e.which <= 57)
        document.getElementById("expression").value+= String.fromCharCode(e.which);
    });

A: You can use this function-
window.onkeyup = function(e) {
   var key = e.keyCode ? e.keyCode : e.which;
 document.getElementById("expression").value += key-48; //for getting the number

  alert(key);
   if (key == 38) {
      //whatever
   }else if (key == 40) {
      // whatever
   }
}

source
And you need to add + to the =
document.getElementById("expression").value+=

instead of -
document.getElementById("expression").value=

A: You have to add a different function for keyPress event, because the keypress event get the value of pressed key differently, not target.target
function addToTextKeypress(event) {

  var exp = String.fromCharCode(event.keyCode);
  //alert(exp);
  if (newExp) {

    //clearText();
    document.getElementById("expression").value = exp;
    newExp=false;

  }

  else
    document.getElementById("expression").value = document.getElementById("expression").value + exp;

}

Later you need to remove exp.value since it has the direct value


text:
Q: AWS custom IAM policy issue Is anyone help me with custom IAM policy with bellow criteria

*

*Read/Write access to 'cloudfront.abc.com'

*Full permission to 'abc_ftp' only s3 bucket but should not able to delete the bucket itself .
(abc-ftp is the name of the AWS S3 bucket , Where full permission with the criteria of should not able to delete bucket itself).
I  tried this

  {
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1633084481455",
      "Action": "s3:*",
      "Effect": "Allow",
      "Resource": "arn:aws:s3:::abc-ftp"
    },
    {
      "Sid": "Stmt1633085010153",
      "Action": [
        "s3:AbortMultipartUpload",
        "s3:BypassGovernanceRetention",
        "s3:CreateAccessPoint",
        "s3:CreateAccessPointForObjectLambda",
        "s3:CreateMultiRegionAccessPoint",
        "s3:DeleteObject",
        "s3:DeleteObjectTagging",
        "s3:DeleteObjectVersion",
        "s3:DeleteObjectVersionTagging",
        "s3:DeleteStorageLensConfiguration",
        "s3:DeleteStorageLensConfigurationTagging",
        "s3:DescribeJob",
        "s3:DescribeMultiRegionAccessPointOperation",
        "s3:GetAccelerateConfiguration",
        "s3:GetAccessPoint",
        "s3:GetAccessPointConfigurationForObjectLambda",
        "s3:GetAccessPointForObjectLambda",
        "s3:GetAccessPointPolicy",
        "s3:GetAccessPointPolicyForObjectLambda",
        "s3:GetAccessPointPolicyStatus",
        "s3:GetAccessPointPolicyStatusForObjectLambda",
        "s3:GetAccountPublicAccessBlock",
        "s3:GetAnalyticsConfiguration",
        "s3:GetBucketAcl",
        "s3:GetBucketCORS",
        "s3:GetBucketLocation",
        "s3:GetBucketLogging",
        "s3:GetBucketNotification",
        "s3:GetBucketObjectLockConfiguration",
        "s3:GetBucketOwnershipControls",
        "s3:GetBucketPolicy",
        "s3:GetBucketPolicyStatus",
        "s3:GetBucketPublicAccessBlock",
        "s3:GetBucketRequestPayment",
        "s3:GetBucketTagging",
        "s3:GetBucketVersioning",
        "s3:GetBucketWebsite",
        "s3:GetEncryptionConfiguration",
        "s3:GetIntelligentTieringConfiguration",
        "s3:GetInventoryConfiguration",
        "s3:GetJobTagging",
        "s3:GetLifecycleConfiguration",
        "s3:GetMetricsConfiguration",
        "s3:GetMultiRegionAccessPoint",
        "s3:GetMultiRegionAccessPointPolicy",
        "s3:GetMultiRegionAccessPointPolicyStatus",
        "s3:GetObject",
        "s3:GetObjectAcl",
        "s3:GetObjectRetention",
        "s3:GetObjectTagging",
        "s3:GetObjectTorrent",
        "s3:GetObjectVersion",
        "s3:GetObjectVersionAcl",
        "s3:GetObjectVersionForReplication",
        "s3:GetObjectVersionTagging",
        "s3:GetObjectVersionTorrent",
        "s3:GetReplicationConfiguration",
        "s3:GetStorageLensConfiguration",
        "s3:GetStorageLensConfigurationTagging",
        "s3:GetStorageLensDashboard",
        "s3:ListAccessPoints",
        "s3:ListAccessPointsForObjectLambda",
        "s3:ListAllMyBuckets",
        "s3:ListBucket",
        "s3:ListBucketMultipartUploads",
        "s3:ListBucketVersions",
        "s3:ListJobs",
        "s3:ListMultiRegionAccessPoints",
        "s3:ListMultipartUploadParts",
        "s3:ListStorageLensConfigurations",
        "s3:ObjectOwnerOverrideToBucketOwner",
        "s3:PutAccelerateConfiguration",
        "s3:PutAccessPointConfigurationForObjectLambda",
        "s3:PutAccessPointPolicy",
        "s3:PutAccessPointPolicyForObjectLambda",
        "s3:PutAccountPublicAccessBlock",
        "s3:PutAnalyticsConfiguration",
        "s3:PutBucketAcl",
        "s3:PutBucketCORS",
        "s3:PutBucketLogging",
        "s3:PutBucketNotification",
        "s3:PutBucketObjectLockConfiguration",
        "s3:PutBucketOwnershipControls",
        "s3:PutBucketPolicy",
        "s3:PutBucketPublicAccessBlock",
        "s3:PutBucketRequestPayment",
        "s3:PutBucketTagging",
        "s3:PutBucketVersioning",
        "s3:PutBucketWebsite",
        "s3:PutEncryptionConfiguration",
        "s3:PutIntelligentTieringConfiguration",
        "s3:PutInventoryConfiguration",
        "s3:PutJobTagging",
        "s3:PutLifecycleConfiguration",
        "s3:PutMetricsConfiguration",
        "s3:PutMultiRegionAccessPointPolicy",
        "s3:PutObject",
        "s3:PutObjectAcl",
        "s3:PutObjectLegalHold",
        "s3:PutObjectRetention",
        "s3:PutObjectTagging",
        "s3:PutObjectVersionAcl",
        "s3:PutObjectVersionTagging",
        "s3:PutReplicationConfiguration",
        "s3:PutStorageLensConfiguration",
        "s3:PutStorageLensConfigurationTagging",
        "s3:ReplicateDelete",
        "s3:ReplicateObject",
        "s3:ReplicateTags",
        "s3:RestoreObject",
        "s3:UpdateJobPriority",
        "s3:UpdateJobStatus"
      ],
      "Effect": "Allow",
      "Resource": "arn:aws:s3:::abc-ftp/*"
    }
  ]
}

A: Access to Amazon S3 bucket
To grant a specific user access to an Amazon S3 bucket, you should add a policy to the IAM User.
Here is a sample IAM policy from User policy examples - Amazon Simple Storage Service:
{
   "Version":"2012-10-17",
   "Statement":[
      {
         "Effect":"Allow",
         "Action": "s3:ListAllMyBuckets",
         "Resource":"*"
      },
      {
         "Effect":"Allow",
         "Action":["s3:ListBucket","s3:GetBucketLocation"],
         "Resource":"arn:aws:s3:::awsexamplebucket1"
      },
      {
         "Effect":"Allow",
         "Action":[
            "s3:PutObject",
            "s3:PutObjectAcl",
            "s3:GetObject",
            "s3:GetObjectAcl",
            "s3:DeleteObject"
         ],
         "Resource":"arn:aws:s3:::awsexamplebucket1/*"
      }
   ]
}

The above policy allows the user to list the names of all buckets, and upload/download to the awsexamplebucket1 bucket.
Access to CloudFront
Anybody can access a CloudFront distribution via HTTP. Access is not restricted via IAM.
If you have private content, you can Serve private content with signed URLs and signed cookies - Amazon CloudFront.
IAM is only used to grant permission to users to manage the distribution (eg change the configuration). It is not used to control access to the content.


text:
Q: Let C be a real number such that |C|<1. Show C^n converges to $0$. Let $C$ be a real number such that $|C|<1$. Show $$\lim_{x\to\infty}C^{n}=0$$
What I did so far: I made some cases.
When $C=0$ : then you have the constant sequence $0,0,0,\dots$, so that converges to $0$. (Let $N=1$.)
When $0<C<1$ : then the numbers in the sequence decrease because you're getting always strictly less than 100 % of the previous number. You can never go negative from multiplying positive numbers, so the sequence is bounded and decreasing. So the limit exists and now we have to show it's $0$. To find the right $N$, I tried to consider when $|C^{n}-0|<\epsilon\iff C^{n}<\epsilon$. I didn't know how to do the algebraic manipulations, but I think the idea is that given an $\epsilon$, you have to multiply $C$ enough times until it's $<\epsilon$, and "enough times" depends on $C$ (like if $C$ is larger, you'll have to multiply more of them because the decrease is slower). But I don't know how to write a specific formula for $N$. So my question is, how do I find a formula for $N$? (Or how do I show $N$ exists without saying what it should be?)
I was similarly stuck on the $-1<C<0$ case.
The book has solutions similar to what I have done so far, but I don't understand this: "We have $C^{n+1}=CC^{n}$ so by passing to the limit we get $L=CL$ which implies $L=0$." What does "passing to the limit" mean?
I'm self-learning analysis and doing practice problems in Aksoy and Khamsi's A Problem Book in Real Analysis. This is from Chapter 3, Problem 3.3.

A: To find a specific formula for $N$, you can use logarithms:
$$C^n < \varepsilon \iff n > \log_C \varepsilon.$$
Note the change of direction of inequality, as logarithms with bases strictly less than $1$ are strictly decreasing functions. I don't particularly like this approach, as logarithms are objects that need to be defined in their own good time in a real analysis course, and using them now for $\varepsilon$-$N$ proofs is somewhat jumping the gun.
I prefer the book's approach. There are already two answers explaining it.
For the $C < 0$ case, I suggest considering $|C|^n$. You already know it tends to $0$, from the $C > 0$ case. It should be clear, using that fact and the $\varepsilon$-$N$ definition of a limit, that the $C < 0$ case works too.

A: First you need to show the limit exists. This is accomplished by the monotone convergence theorem. Once you know that the limit exists, you may use the algebraic manipulations. Let $L = \lim_{n \to \infty}C^n$, then $$\lim_{n \to \infty}C^n = C \cdot\lim_{n\to \infty} C^{n-1}$$ $$L = C \cdot L$$ $$L = 0$$ When a textbook says "passing to the limit", it just means to take the limit of the expression or equation.

A: "Passing to the limit" means taking the limit of both sides. So if you assume that the limit of $C^n$ exists, and you have this equation:
$$C^{n+1}=CC^n$$
then
$$\lim_{n\to\infty}C^{n+1}=C\lim_{n\to\infty}C^n$$
and if the limit exists then the sequences $C^n, C^{n+1}$ must have the same limit.
Note that you can do that only if you already know that the limit exists.


text:
Q: Xamarin Android Api 29 Q10 can not reconnect to Wifi My app connects to a hotspot and then remove it. My issue is that the phone does not reconnect after to the previous WiFi network with the API 29. Any idea how to use new API?
This code used to work but is now obsolete:
WifiManager wifiManager =
   (WifiManager)Android.App.Application.Context.GetSystemService(Context.WifiService);
var wifiConfig = new WifiConfiguration{Ssid = $"\"{hotspotName}\""};
var network = wifiManager.ConfiguredNetworks.FirstOrDefault(n => n.Ssid == wifiConfig.Ssid);
wifiManager.Disconnect();
wifiManager.RemoveNetwork(networkId);
wifiManager.Reconnect();

new code that fails to reconnect to available WiFi:
WifiNetworkSuggestion.Builder wifiNetworkSuggestionBuilder = new
    WifiNetworkSuggestion.Builder();
wifiNetworkSuggestionBuilder.SetSsid(ssid);
WifiNetworkSuggestion wifiNetworkSuggestion =
    wifiNetworkSuggestionBuilder.Build();
IList<WifiNetworkSuggestion> wifiNetworkSuggestions = new
     List<WifiNetworkSuggestion> { wifiNetworkSuggestion };
 NetworkStatus networkStatus =
     WifiManager.RemoveNetworkSuggestions(wifiNetworkSuggestions);

A: The Reconnect and RemoveNetwork methods was deprecated in API level 29/Q and always return false on that API level.
You should now use WifiNetworkSpecifier.Builder() on 29/Q to have an application-level scope wifi connection and since it is app scoped, you do not have to remove it and reconnect to the user's previous wifi network as the OS will now do it for you.

*

*https://developer.android.com/reference/kotlin/android/net/wifi/WifiNetworkSpecifier.Builder


text:
Q: SQL using fallback column for match Say I have a table in an sql database like
name    age  shoesize
---------------------
tom      20      NULL
dick   NULL         4
harry    30         5

and I want an SQL statement that selects names that have age == X, or as a fallback, if no such names exist, use those with shoe size == Y. In other words, in this table, for X=20,Y=4 I should only get 'tom', while for X=25,Y=4 I should get only 'dick'. I can't do that with
SELECT name FROM table WHERE age = 20 OR shoe size = 4;

because that will select both tom and dick. I'm currently using
SELECT COALESCE ((SELECT name FROM tab WHERE age = 20),(SELECT name FROM tab WHERE shoesize = 4));

but is there a neater way? Also using coalesce like this doesn't allow me to get the whole row - i.e. I can't use SELECT * FROM tab, I can only select a single name.

A: You can use ORDER BY and FETCH FIRST 1 ROW ONLY or some similar clause:
SELECT name
FROM tab
ORDER BY (CASE WHEN age = X THEN 1
               WHEN shoesize = Y THEN 2
               ELSE 3
          END)
FETCH FIRST 1 ROW ONLY;

Some databases spell FETCH FIRST 1 ROW ONLY like LIMIT or TOP or even something else.


text:
Q: How to use adverbial phrases with season/year? Time adverbial phrases seem very confusing. Google doesn't show any past questions on this. I'd like to ask how I should write a sentence with a temporal phrase indicating season and year:

[subject] [verb] [temporal adverbial phrase]

Now the problem is with the temporal adverbial phrase. Do I have to use the definite article to denote seasons? Do I have to you the preposition "in"? And what combinations work? What don't? A comment helpfully suggests this version works: in the season of year. And I'd like to know what other versions work. What makes it really confusing is we see similar phrases in headlines all the time with random words omitted, even in the body of online articles. For example:

*

*Morgan Hill City Officials voted 5-0 to pass the Butterfield Fire Station construction to start summer 2023.
2. New Football Operations/Development Building. Projected to start Summer 2023 and be done by Winter 2024.
3. The project is planned to start summer of 2023.

So some variations I have thought of are, and I'd like to know, as a very specific question about grammaticality and style, to what degrees are these acceptable in writing, and to what degrees can they be used in headlines:

*

*✅I started learning Java summer 2010.

*✅I started learning Java summer of 2010.

*I started learning Java in summer 2010.

*I started learning Java the summer 2010.

*✅I started learning Java the summer of 2010.

*I started learning Java in the summer 2010.

*I started learning Java in summer of 2010.

*I started learning Java in the summer of 2010.

*Summer 2010, I started learning Java.

*Summer of 2010, I started learning Java.

*The summer 2010, I started learning Java.

*The summer of 2010, I started learning Java.

*In summer 2010, I started learning Java.

*In the summer 2010, I started learning Java.

*✅In summer of 2010, I started learning Java.

*In the summer of 2010, I started learning Java.

A: Measure for Measure
You've combined a lot of permutations, some of which are ok but many of which are unlikely to go over well.  These sorts would probably be ok in most circumstances:

*

*I learned Java in/over/during/starting the summer of 2010.

*I learned Java the summer of 2010.

*The summer of 2020 was when I first started learning Java.

*Summer of 2020 was when I first started learning Java.

*Winter 2019 I finished learning C++, so Summer 2020 I began learning Java.

But precisely when you can skip one or another preposition, and when you can front the adverbial, is a bit complicated.

Measure phrases are a subtype of noun phrase that enjoy various special syntactic
properties.
One of these properties is that measure phrases of time,
duration, and frequency can function as adjuncts all on their own, modifying other syntactic
elements without needing any preposition like in, from, or for — nor for that matter any postposition like ago or away, either.
These can be adnominal adjuncts the way they are here:

*

*The discussion that night left them unconvinced.

But more commonly they're adverbial adjuncts the way they are here:

*

*They left unconvinced that night.

*They worked three days, then left.

*I'm working nights this week.

*They studied for their exam all week.

*I leave for France next week.

*The dinner special runs three hours nightly.

*Her Majesty reigned three-score years and ten.

*She was gone five minutes when the phone rang.

*We met in France last Christmas.

As you see, deictic elements like this, next, last are especially common in these.
Some kinds of these temporal measure phrases serving as adverbial adjuncts can
be fronted for focus giving special emphasis to the measure phrases, but
other types cannot. (Doing so can sometimes trigger inversion, but rarely.)

*

*That night they left unconvinced.

*Three days they worked, then left.

*❌ Nights this week I'm working.

*Next week I leave for France.

*All week they studied for their exam.

*❌ Three hours nightly the dinner special runs.

*Three-score years and ten reigned Her Majesty.

*❌ Five minutes she was gone when the phone rang.

*Last Christmas we met in France.

Locative measure phrases can also be adverbial adjuncts unadorned by
adpositions when the context allows:

*

*I ran ten miles that day.

*Ten miles I ran that day.

*Ten miles did I run that day.

Of course, that day is also an adverbial adjunct of this type, only  temporal this time, not locative. It too can be fronted:

*

*That day I ran ten miles.

For more information, you might perhaps care to look at the teacher training materials on time adjuncts
from ELT Concourse.


text:
Q: Sum of squares of determinants of principal minors I am interested in computing the sum of squares of determinants of principal minors.  Let $A$ be an $n\times n$ positive semidefinite matrix and $A_S$ be a principal minor of $A$ indexed by the set $S \subseteq \{1,\ldots,n\}$.  The classical result (without squares) is:
$\sum_{S \subseteq \{1,\ldots,n\}} \det(A_S) = \det(A+I)$
Are there any results on computing
$\sum_{S \subseteq \{1,\ldots,n\}} \det^2(A_S)$
or any other powers?

A: The identity you mention does generalize to sums of powers, but I don't know if it can give you anything computationally efficient. Given a set $X\subset \mathbb R$, let $D(X^n)$ denote all $n\times n$ diagonal matrices with diagonal elements from $X$. Then if you take $X_k=\{1,\omega,\cdots,\omega^{k-1}\}$ the $k$-th roots of unity, the following holds
$$\sum_{S\subset \{1,2,\cdots,n\}}\det(A_S)^k=\frac{1}{k^n}\sum_{M\in D(X^n)}\det(A+M)^k$$
the proof is basically the same as the one for the case $k=1$ with a few more algebraic manipulations.


text:
Q: How do GC in HotSpot cooperate with each other As we all know that in HotSpot there are seven GCs like Serial,CMS,G1 and so on.What I am confused is that all of them or only part of them is working at a time? How do them cooperate with each other to cover the task of garbage collection?
I appreciate any answer to this question.
Best wishes to everyone of you!

A: Below are possible combinations of GC algos in Java 8.

*

*-XX:+UseSerialGC - Serail Young (DefNew) + Serial Old Mark Sweep Compact

*-XX:+UseParallelGC - Parallel Young (PSYoungGen) + Serial Old  Mark Sweep Compact

*-XX:+UseParallelOldGC - Parallel Young (PSYoungGen) + Parallel Old Mark Sweep Compact

*-XX:+UseParNewGC - Parallel Young (ParNew) + Serial Old Mark Sweep Compact

*-XX:-UseParNewGC -XX:+UseConcMarkSweepGC - Serial Young (DefNew) + Concurrent Mark Sweep (Old)

*-XX:+UseParNewGC -XX:+UseConcMarkSweepGC - Parallel Young (ParNew) + Concurrent Mark Sweep (Old)

*-XX:+UseG1GC - G1
Source of information.
Parallel Scavenge and ParNew are very similar, but ParNew is compatible with CMS (concurrent mark sweep) and Parallel Scavenge with parallel Mark Sweep Compact old space collectors.
G1 solely covers both young and old collections.


text:
Q: Grant access to file in S3 bucket by a unique hash (Go)? So I have an S3 bucket. I want to grant access to a single file within that bucket to a unique person. Is it possible to grant access based on a secure hash or something like that?
So for instance. File is uploaded to bucket. Emails is sent to user with a link:
https://s3-us-west-2.amazonaws.com/mycoolbucket/test.txt?key=asdqwerwerhsdhsdfh23562346
Access to that file is granted if the key (or whatever) is present and correct. If that key wasn't correct access would be denied. And access would only be granted for that single file in the bucket. Trying to avoid changing policies and what not.
Thanks in advance!

A: Take a look at pre-signed URLs, for example in Java: http://docs.aws.amazon.com/AmazonS3/latest/dev/ShareObjectPreSignedURLJavaSDK.html

A: So after looking over all the existing golang packages and what not I decided it was best to just build my own package specifically for creating a secure url to a specific item in an S3 bucket. It works great but documentation is a work in progress. Hopefully it helps someone:
https://github.com/markhayden/s3querybuilder


text: Q: Отображение метки пользователя на карте в WPF Задача состоит в следующем: нужно отобразить маркер пользователя на карте по введенным им данным(город, улица,дом). Подскажите пожалуйста как реализовать это используя интерфейс WPF.


text:
Q: Site is too wide on mobile The site I created makes an unnecessary large width on the page. The page is supposed to fit to the screen of a mobile phone. But I seem to have to scroll to the right for nothing. This is the site: https://gwenlotest.000webhostapp.com/index.html
it works perfectly on big screens but as soon as I open the site on mobile websites I have to scroll to get to the burger menu and I don't understand why.

A: It is caused because of the elements that animate from the right. Look into putting them in another div that wraps these elements. The div will should have 100% width.
As you might notice, as you scroll down, when the elements animate from the right edge of the screen, the right extension disappears.

A: Add shrink-to-fit=no to your meta name="viewport" so it should be in the form
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">

i think that should fix the issue.


text:
Q: Automated Posts Made to Facebook Page Via API Can't be Seen by Users I recently set up an HTTP poster that uses cURL, PHP and the Facebook API to post to my page's timeline.
The page is a dedicated #nowplaying page for an online radio station, so the auth token and associated facebook app is only for one user, which is myself.
The poster has been working for a few weeks, but I have only just now realised that only I can see the posts, which (as they appear to me) are made 'as the page'. Other page followers can only see a single manual post I made welcoming people to the page.
I know this might be a super user question, but I have checked all relevant page settings, and the fact that they can see manual posts by the page makes me thing it's an API/Token thing.
Q: Why can't my facebook page visitors see my automated posts?

*

*Here is my page

*Here is what I see, and what I want users to
see. Note: notice the little world logo on each post indicating that they are public.

Edit: I'm making the post over http at https://graph.facebook.com/{pageID}/feed...


text:
Q: Cq ui clientlib is not accessible I have util page that used in publish enviromets. HtmlLibraryManager is used to include  ui
<%
        HtmlLibraryManager htmlMgr = sling.getService(HtmlLibraryManager.class);
        if (htmlMgr != null) {
            htmlMgr.writeCssInclude(slingRequest, out, "cq.wcm.edit");
            htmlMgr.writeJsInclude(slingRequest, out, "cq.wcm.edit");
        }
%>

But some requested libs doesn't loaded
/libs/cq/ui/widgets.js and /libs/cq/ui/rte.js
They brokes my page.
Also if I will try to acces them http://servername:port/libs/cq/ui/widgets.js , error is returned:

The requested file cannot be found.

How could I get access to this clientlibs?
AEM 6.0 is used.
I have found follwing error in log file:
23.09.2015 11:03:55.124 *ERROR* [172.18.251.90 [1443020634874] GET /libs/cq/ui/widgets.js HTTP/1.1] com.day.cq.widget.impl.HtmlLibraryManagerImpl Error while saving changes: javax.jcr.RepositoryException: Error during assembly of /libs/c
q/ui/widgets.js. reverting.
23.09.2015 11:03:55.124 *ERROR* [172.18.251.90 [1443020634874] GET /libs/cq/ui/widgets.js HTTP/1.1] com.day.cq.widget.impl.HtmlLibraryManagerImpl Error while sending cached library: javax.jcr.RepositoryException: Error during assembly of
 /libs/cq/ui/widgets.js
23.09.2015 11:03:55.125 *ERROR* [172.18.251.90 [1443020634874] GET /libs/cq/ui/widgets.js HTTP/1.1] com.day.cq.widget.impl.HtmlLibraryServlet Cannot create library for /libs/cq/ui/widgets.js
java.io.IOException: Error while sending cached library: javax.jcr.RepositoryException: Error during assembly of /libs/cq/ui/widgets.js

A: Problem was in courrupted lib. See more at adobe forum


text:
Q: Pass ID prop to onChange for a materialUI Slider Component I'd like to update my easy-peasy store when I change a value on a material-UI slider component. I need to pass the id of the slider component that I'm changing to my handleChange function so I can specify which property in my store I want to update. The problem I'm having is that onChange returns a different event target depending on which part of the slider you click on.
Click on rail returns:

Click on track returns:

Clicking on the containing span returns:
  <input type="hidden" value="17">17

Only clicking on the root span element returns a target with the id value when onChange is fired. Is there a way to get the material UI slider to return the id value no matter where on the slider I click?

import React, { useState, useEffect } from 'react';
import { makeStyles, withStyles } from '@material-ui/core/styles';
import Slider from '@material-ui/core/Slider';
import { useStoreState, useStoreActions } from 'easy-peasy'

const PrettoSlider = withStyles({
  root: {
    color: '#52af77',
    height: 8,
  },
  thumb: {
    height: 0,
    width: 0,
    backgroundColor: '#fff',
    border: '2px solid currentColor',
    marginTop: -8,
    marginLeft: -12,
    '&:focus, &:hover, &$active': {
      boxShadow: 'inherit',
    },
  },
  active: {},
  valueLabel: {
    left: 'calc(-50% + 4px)',
  },
  track: {
    height: '60%',
    borderRadius: 4,
  },
  rail: {
    height: 8,
    borderRadius: 4,
  },
})(Slider);

export function SubdivisionControls(props){

  const handleChange = (event, newValue) => {
    console.log(event.target)
    console.log(event.target.id)
    console.log(newValue)
    setStoreVal({id: props.id, targetSliderId: event.target.id})
   };

  const setStoreVal = useStoreActions(actions=> actions.panels.setParameter)

  return(

     <PrettoSlider valueLabelDisplay="auto" aria-label="pretto slider 1" defaultValue={20} onChange = {handleChange} id = {'subdivValue0'} />
     <PrettoSlider valueLabelDisplay="auto" aria-label="pretto slider" defaultValue={20} onChange = {handleChange} id = {'subdivValue1'} />
     <PrettoSlider valueLabelDisplay="auto" aria-label="pretto slider" defaultValue={20} onChange = {handleChange} id = {'subdivValue2'} />

  )
}

export default SubdivisionControls

A: Temporary Solution:
Set pointerEvents to 'none' for all elements other than root for the slider:
const PrettoSlider = withStyles({
  root: {
    color: '#52af77',
    height: 8,
    zIndex: 10,
  },
  thumb: {
    height: 0,
    width: 0,
    backgroundColor: '#fff',
    border: '2px solid currentColor',
    marginTop: -8,
    pointerEvents: 'none',
    marginLeft: -12,
    '&:focus, &:hover, &$active': {
      boxShadow: 'inherit',
    },
  },
  active: {},
  valueLabel: {
    left: 'calc(-50% + 4px)',
  },
  track: {
    height: '60%',
    borderRadius: 20,
    pointerEvents: 'none'
  },
  rail: {
    height: 8,
    borderRadius: 4,
    pointerEvents: 'none'
  },
})(Slider);


text:
Q: Counting template instantiations with inline variables Let's say we want to count the number of a template instantiations for a certain template.
In C++17 I think I can do it like this:
static inline size_t my_template_count = 0;

template <typename T>
struct my_template {
  static inline char count_me = []{ my_template_count++; return 0; }();

  // mention count_me in all functions.
};

My questions are:
 - Will it work?
 - Can there be a race condition on the total_count?
   (Reading while DLL loading, something like that).
Update: as @n.m. correctly pointed out - I have to reference the variable.
It's ok for my usecase to include (void)count_me in all constructors, destructor, static methods etc. And if none of them are used, it's ok to ignore the instantiation.

A: A similar question came up in a discussion with Sean Parent.
He said:

Not thread safe because deferred dynamic initialization is not guaranteed to happen on the main thread cppreference


text:
Q: Example of gtkmm 4 FileChooserNative code I can't find code examples using Gtk::FileChooserNative to help me understand how to work with this class. Documentation from here isn't that helpful.
My goal is to create a function which opens a native file chooser dialog and after the user selects the folder, prints the path to the folder into a terminal.
When I try to compile this:
void MyWindow::on_button_browse_clicked()
{
    Gtk::FileChooserNative dialog ("Please choose a folder",
                                   Gtk::FileChooser::Action::SELECT_FOLDER,
                                   "Choose",
                                   "Cancel");
}

I get the following error:
error: calling a protected constructor of class 'Gtk::FileChooserNative'

How can I create a Gtk::FileChooserNative?

A: I don't have Gtkmm 4 here, but from the documentation you posted, it seems you need to use a factory method instead of a constructor to create such a dialog:
static Glib::RefPtr<FileChooserNative> Gtk::FileChooserNative::create(
        const Glib::ustring& title,
        Window&              parent,
        FileChooser::Action  action,
        const Glib::ustring& accept_label = {},
        const Glib::ustring& cancel_label = {}
)

In your case, something like:
void MyWindow::on_button_browse_clicked()
{
    auto dialog = Gtk::FileChooserNative::create("Please choose a folder",
                                                 *this,
                                                 Gtk::FileChooser::Action::SELECT_FOLDER ,
                                                 "Choose",
                                                 "Cancel");

    dialog->show();
}


text:
Q: How to wrap div fields and maintaing equal width while using @media screen Anyone know how to wrap div's using @media screen and maintain equal width on all div's. I have tried using float and inline-block but can't find a way to keep all field widths equally justified. Using table-cells provides the means to maintain equal field width but does not permit row/cell changes on @media screen. I have provided an example using table cells just to show what I'm trying to achieve. Note: I'm also trying to avoid fixed field width.
Example: https://jsfiddle.net/6jj6qx8a/

From this...

Name:

John Johnson

Employer:

ABC Company

Address:

123 State St NW

Zip Code:

12345

to this on @media screen and ( max-width: 400px )

Name:

John Johnson

Employer:

ABC Company

Address:

123 State St NW

Zip Code:

12345

A: Use a div containing both tables.
Set table width to 100% and set the parent div a % with too.


text:
Q: InvalidArgumentException Unexpected data found когда я пытаюсь сохранить дату публикации Задача: Если пользователь не вводил дату публикации, то ставится текущее время, иначе его данные.
Форма
@if($publishedDate === 1)
<div class="form-group">
    {!! Form::label('published_at',"Дата публикации :") !!}
    {!! Form::input('datetime-local', 'published_at', date('Y-m-d H:i'), [
        'class' => 'form-control',
         'min' => date('Y-m-d')
     ]) !!}
</div>

Модель News
 public function setPublishedAtAttribute($date) {
    //dd($date);
    if($date === null) {
        //dd($date);
        $this->attributes['published_at'] = Carbon::createFromFormat('Y-m-d\TH:i:s', date('Y-m-d\TH:i:s') )
            ->copy()->format('F j, Y @ g:i A');
    }

}
protected $fillable = [
    'title',
    'body',
    'published_at',
    'updated_at',
    'news_wall',
    'slug'
];
protected $dates = ['published_at', 'updated_at'];

При том, что функция которая делает то же самое для другого поля работает хорошо
public function setUpdatedAtAttribute($date){
    $this->attributes['updated_at'] = Carbon::createFromFormat('Y-m-d\TH:i:s', $date)->format('Y-m-d H:i:s');
}


text:
Q: What does global scope means in client-side Javascript that runs inside web browser According to MDN:

In client-side JavaScript, the global scope is generally the web page inside which all the code is being executed.

Now because of hoisting when HTML web page loads(that is the start of the global scope), all global variable should be created and initialized to undefined.
To test this I created three files:
test.html:
<html>
<head>
</head>
<body>
<script src = "test2.js"></script>
<script src = "test1.js"></script>
</body>
</html>

test2.js:
alert(g); // ReferenceError: g is not defined (web browser console)
function increment()
{
    g = g + 1;
}

test1.js:
var g = 1;
increment();
alert(g); // alert's 2

why alert(g) in test2.js results in a ReferenceError? why g's declaration isn't hoisted up to the start of the global scope?
I think g's declaration is not hoisted up to the start of the global scope because if it was, g must have been created and initialized to undefined when test.html loads and thus alert(g) in test2.js should alert undefined.

A: This has nothing to do with scope. It is about timing.
Each <script> will be executed as it is parsed.
Variables defined in subsequent scripts, while they will appear in the same scope, are not hoisted so they exist while a previous script runs.

A: All variable inside  tags or script files (XXX.js) is global if the variable is not scope in functions. you don't add global words or anything else when you define a variable if you want the variable be global.
In this case you need first define variable after that call them , in JS language, machine first parsing all code line by line and when finished first Js file go to parsing to another file . when compiler look at test2.js does not find any variable because the variable will be defined after parsing of test2.js complated in test1.js


text:
Q: iphone sdk nsstring as object - get text I'm having an issue with a string which is being returned from a webservice. I am setting the string up in the header file, simple with
NSString *serviceUserID;
@property (nonatomic, retain) NSString *serviceUserID;

then I'm synthesizing it as normal. I can set it using
serviceUserID = @"4fffrdscfbg-44-06dfgf-dfgdfg-32eer456134";

but when it's set using the service return, it seems to save an object which I cannot access later on. So the code below doesn't work...
NSLog(@"result = %@", result);
serviceUserID = result;

The code above will output the serviceUserID string to the log window, but when I try to do the same outside of that function it crashes with no error messages. I've no idea what's up. I have tried to set the string with initWithFormat and all sorts, but nothing's working!! I just need to set the serviceUserID Variable so I can use it in other functions... is there a way to set the text that I'm missing??
Thanks for any help.

A: You need to retain string value you assign to your iVar - in your example you're likely assigning autoreleased string which becomes invalid outside current scope. As you have declared property for it the correct way to do that will be:
self.serviceUserID = result;

The reason why serviceUserID = @"4fffrdscfbg-44-06dfgf-dfgdfg-32eer456134"; works is that you're assigning string literal here - it is created at compile-time and doesn't get released at all.


text:
Q: Missing the pg_ctl package in Postgres 9.3 installation I have installed postgresql 9.3 on ubuntu 14.04 using "apt-get install postgresql".
Everything was going well until I discovered that I do not have access to the "pg_ctl" commands. Installing the postgres-xc literally breaks postgresql server. The package links become broken. I cannot re-install and have had to revert my VM and keep working without pg_ctl.
My question is, to get access to this package, should I start from scratch or uninstall and re-install postgresql?
What should I have installed in the first place?
Alternatively, is there something wrong with my path?
(I am new to postgresql and have been tossed into it for work purposes)

A: In Debian/Ubuntu, the functionalities of pg_ctl  are provided by pg_ctlcluster. Quoted from its manpage:

NAME

       pg_ctlcluster - start/stop/restart/reload a PostgreSQL cluster

SYNOPSIS

       pg_ctlcluster [options] cluster-version cluster-name action -- [pg_ctl
       options]

       where action = start|stop|restart|reload|promote

DESCRIPTION

       This program controls the postmaster server for a particular cluster.
       It essentially wraps the pg_ctl(1) command. It determines the cluster
       version and data path and calls the right version of pg_ctl with
       appropriate configuration parameters and paths.

It's not technically true that pg_ctl is not installed with postgres packaged for Debian/Ubuntu. It's actually installed in /usr/lib/postgresql/X.Y/bin, where X.Y is the postgres version. This path is intentionally not in any user's default PATH since it should never needed to be invoked directly.
The reason for this setup is that the Debian/Ubuntu packaging supports several PostgreSQL instances running in parallel, either identical or different major versions.
To learn about that, it's best to read first https://help.ubuntu.com/community/PostgreSQL , before the real PostgreSQL manual or any other non-Ubuntu documentation.
postgres-xc is a multi-master fork of PostgreSQL that shouldn't be confused with PostgreSQL itself. The hint suggesting to install it to get pg_ctl is an unfortunate nonsense, probably a machine-generated advice based on the contents of postgres-xc.

A: As these command pg_ctl and initdb were installed with postgresql and these are present at "/usr/lib/postgresql/9.3/bin" so change the $PATH environment variable so that you can use it like
export PATH=/usr/lib/postgresql/9.3/bin:$PATH
but make sure that you are logged in at postgres user as this is the one who is creating the server for you.
I hope i was able to provide you solution
Thank you,