text:
Q: What's next? $\text{Hom}(U,V)$, tensor product and so on I don't think this question is as soft as soft-question tag, but if I not how to tag it, I would not be asking this question:
I have taken second year linear algebra (Axler's Linear Algebra Done Right), but I still find much trouble understanding $\text{Hom}(U,V)$, like what is its basis; and no idea about tensor product.
So should I consider "a third year linear algebra"? Though there is not really a course named so - but is there a course or book I should read after Axler? Or I can learn more about these in some other course, like functional analysis? Is Representation theory related/necessary at this level?

A: It can be often illuminating to forget some of the technology and go back to a simpler time. Axler's text is a favourite of mine. If you can do all the problems in that book, then you know your linear algebra, let me assure you.
Regarding $Hom$...
You have two vector spaces $U,V$ (lets say they're finite dimensional). In plain english, $Hom(U,V)$ is the set of all (linear) maps from $U$ to $V$. We're in a finite dimensional case so lets go ahead and pick bases for $U$ and $V$ so they each look like $k^n$ for (possibly different) $n$. Think of them as column vectors.
So, how do you map one set of column vectors to another: you use matrices! You know how to scale matrices, and add matrices. In other words, $Hom(U,V)$ has just been given the structure of a vector space all on its own. Its a big vector space consisting of matrices of the appropriate size (so multiplying them with column vectors from $U$ makes sense) and one basis for instance is given by putting $0$ everywhere in the matrix except in one spot.
You can write this down in fancier ways without choosing bases too: Given maps $\phi$ and $\psi$ from $U$ to $V$, we can (pointwise) add and scale them and we get new linear maps. It is a good exercise to figure out what the basis I described above in terms of matrices looks like without explicitly thinking about the matrices. It is going to be a distinguished linear transformation. Figure out what it is!
Another great exercise is to set $V = k$ and understand $U^*$, the dual vector space. What do the above matrices look like in this case? Can you see for yourself that $U\cong U^*$ once you picked a basis?
Tensor products are somewhat more subtle. I would suggest trying to understand them in terms of ``what they do''. The tensor product of $U$ and $V$ is built to be the most general machine that can handle linear maps from $V\times U$, that are in fact bilinear (linear in each variable). Sit on this idea for a while. Then look at how a tensor product is defined in terms of generators and relations.
Once you have, try and make sense of: $k^n\otimes k^m \cong k^{mn}$.


text:
Q: How do I get questions regarding emails to get more attention? This may be a non-question or a question in the wrong place, so I understand if its rapidly shut down, but I notice that any questions I've asked about email get little attention and very rarely answered. I did a quick search and that seems to be a broader phenomenon on the imap and email tags.
Is this just not an area not of interest to SO users, or is it something to do with the way the questions are being posed. Thanks

A: I believe it's just strictly a matter of user interest and the amount of beginners entering the area. The most common and frequented tags are definitely the languages themselves, c#, java, php, which both have a lot of interest and have frequent questions from people with little experience. This leads to a lot of activity.
Email is probably not the favorite area for most people, and anyone getting into it is probably not a beginning programmer, so it's unlikely to be heavily trafficked.
I honestly think it happens to many tags.  For example, I'm personally a fan of Hadoop, which gets even less traffic than email. I'm pretty confident its for the reasons I described: it's very specialized, and most people entering are already fairly experienced programmers, though often they need lots of setup advice ;) .

redpajama_set_name: RedPajamaStackExchange


text:
Q: Need some help fixing a For Each loop in VBA For some reason this loop doesn't call the sub formatCells to run on each cell in the selection. It will only run on the top left cell in the selected range.
Sub selectionLoop()

    Dim rng As Range, itm As Range
    Set rng = Selection

    For Each itm In rng
        Call formatCells
    Next

End Sub

Sub formatCells() 'Formats cells based on what is in the cell

    If WorksheetFunction.IsText(ActiveCell) = True Then 'Searching for text in the cell

        With ActiveCell.Font  'Applies text format
        .Name = "Calibri"
        .Size = 18
        .Underline = xlUnderlineStyleNone
        .ThemeColor = xlThemeColorLight1
        .TintAndShade = 0
        .ThemeFont = xlThemeFontMinor
        .Bold = True
        End With

        With ActiveCell
        .HorizontalAlignment = xlLeft
        .VerticalAlignment = xlBottom
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
        End With
    Else
        ActiveCell.NumberFormat = "#,##0_);(#,##0)"  'Applies number format
    End If

End Sub

A: Some improvements to your code:

*

*Use option explicit to avoid trouble with undeclared variables

*Name your variables to something meaningful

*Don't rely on ActiveCell unless you really mean it

*Optional: replace your IF with Select Case

Option Explicit

Sub selectionLoop()

    Dim targetRange As Range
    Dim cell As Range

    Set targetRange = Selection

    ' Loop through each cell in range
    For Each cell In targetRange
        ' Pass the cell to procedure
        formatCells cell
    Next

End Sub

Private Sub formatCells(ByVal cell As Range) 'Formats cells based on what is in the cell

    If WorksheetFunction.IsText(cell.Value) = True Then 'Searching for text in the cell

        With cell.Font  'Applies text format
        .Name = "Calibri"
        .Size = 18
        .Underline = xlUnderlineStyleNone
        .ThemeColor = xlThemeColorLight1
        .TintAndShade = 0
        .ThemeFont = xlThemeFontMinor
        .Bold = True
        End With

        With cell
        .HorizontalAlignment = xlLeft
        .VerticalAlignment = xlBottom
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
        End With
    Else
        cell.NumberFormat = "#,##0_);(#,##0)"  'Applies number format
    End If

End Sub


text:
Q: Invalid length for a Base-64 char array I'm getting the following error in my ASP.net web page:
Invalid length for a Base-64 char array.
This happens when a user activates an ajax request before the previous request completes.  How can I prevent this error from occurring?
edit: here's the stack trace.  Because the error doesn't appear to be happening in my own code, I'm not sure what to do.
at System.Convert.FromBase64String(String s)
at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString)
at System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState)
at System.Web.UI.HiddenFieldPageStatePersister.Load()

A: You could try and prevent subsequent requests during the ajax request:
function OnRequestStart(sender, args) {
                if (args.EventTargetElement) {
                    var control = document.getElementById("<%= SomeButton.ClientID %>");
                    if (control != null) {
                        if (args.EventTargetElement.id == control .id) {
                            control .disabled = true;
                        }
                    }
                }
            }
            function OnResponseEnd(sender, args) {
                if (args.EventTargetElement) {
                    var control = document.getElementById("<%= SomeButton.ClientID %>");
                    if (control != null) {
                        if (args.EventTargetElement.id == control .id) {
                            control .disabled = false;
                        }
                    }
                }
            }

A: Base64 strings have a length that is a multiple of three. While I cannot tell where the invalid Base64 string comes from it seems obvious that some code is trying to decode an string that is either a corrupted Base64 string or not a Base64 string at all.


text:
Q: Looking for upper bound for a sum over compositions Consider the matrix \begin{bmatrix}
1 & \alpha_1 & 0 & \dots &  & & 0 \\
\alpha_1 & 1 & \alpha_2 & 0 & \dots & & 0 \\
0 & \alpha_2 & 1 & \alpha_3 & 0 & \dots & 0 \\
 \vdots & \ddots & \ddots & \ddots & \ddots & \ddots & \vdots \\
 \vdots &  & \ddots & \ddots & \ddots & \ddots & 0 \\
\vdots &  &  & \ddots & \alpha_{n-2} & 1 & \alpha_{n-1} \\
0 & \dots & \dots & \dots & 0 & \alpha_{n-1} & 1 \\
\end{bmatrix} where $0 < \alpha_i < 1$ for $i = 1, \dots, n-1$.
I am trying to bound the following sum over compositions:
$\sum_{a_1 + \dots + a_{n-1} = r} \frac{2^r}{\pi^{\frac{n}{2}}a_1 ! \dots a_{n-1}!}\Gamma(\frac{1+a_1}{2})\Gamma(\frac{1+a_1+a_2}{2})\Gamma(\frac{1+a_2+a_3}{2})\dots \Gamma(\frac{1+a_{n-3}+a_{n-2}}{2})\Gamma(\frac{1+a_{n-2}+a_{n-1}}{2})\Gamma(\frac{1+a_{n-1}}{2})\alpha_1^{a_1} \dots \alpha_{n-1}^{a_{n-1}}$. My experimental results indicate that a possible upper bound is $(1-\lambda_{min})^r$ where $\lambda_{min}$ is the minimum eigenvalue of the matrix above. I have proved it for $n=2$ by using the known forms for Gamma function values of half integers and separating into the two cases where $r$ is either even or odd. For higher dimensions, this argument doesn't seem to apply so well. Any suggestions for higher dimensions would be appreciated.


text:
Q: Update ListBox after Change SortDescription in CollectionViewSource i've a ListBox in my Application, there have a CollectionViewSource as ItemsSource. In the CollectionViewSource is a SortDescription. There will works fine.
But now i have an Event there will Change the SortDescription. That works fine, but the ItemsSource will not refresh. When i try to update the ItemsSource with CollectionViewSource.View.Refresh() than i become an Error because CollectionViewSource.View is null.
Here is the Code that i used:
The CollectionViewSource:
<Grid.Resources>
    <CollectionViewSource Source="{Binding Path=Vertraege}" x:Key="VertraegeSource">
        <CollectionViewSource.SortDescriptions>
            <scm:SortDescription PropertyName="Vertrag.Gruppe.ID" Direction="Ascending" />
        </CollectionViewSource.SortDescriptions>
    </CollectionViewSource>
</Grid.Resources>

The ListBox
<ListBox Name="lb_Vertraege" Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="3" ItemTemplate="{StaticResource VertragsListBoxTemplate}" ItemsSource="{Binding Source={StaticResource VertraegeSource}}" ScrollViewer.VerticalScrollBarVisibility="Visible">

Has anywhere an Idea, what i can do to Update the ItemsSource after Modifying the SortDescription? At the Moment i try this with this C# Code:
ControlTemplate template = this["LeistungserbringerVertraegeTemplate"] as ControlTemplate;
Grid grid = template.LoadContent() as Grid;

CollectionViewSource viewSource = grid.FindResource("VertraegeSource") as CollectionViewSource;

viewSource.SortDescriptions.Clear();
viewSource.SortDescriptions.Add(new System.ComponentModel.SortDescription("VertragsID", System.ComponentModel.ListSortDirection.Ascending));

viewSource.View.Refresh();

A: From my experience, Template.LoadContent() is very unusual and not recommended in WPF.
A common way to retrieve the CollectionView is to get it from the ItemsControl that hosts the ItemsSource:
ICollectionView collectionView = CollectionViewSource.GetDefaultView(lb_Vertraege.ItemsSource);

then add your sort descriptions to the Filter delegate:
collectionView.Filter = ... // your sort descriptions


text:
Q: Keyset as registered is invalid exception when Importing a RSA Key Container using aspnet_regiis I have been trying to import a RSA key container from aspnet_regiis. Steps are as follows.

*

*Run the command prompt as administrator

*cd C:\windows\Microsoft.NET\Framework\v2.0.50727

*aspnet_regiis -pi myrsakey E:\keyfile.xml

When followed the above steps I get the error as follows
**

Importing RSA Keys from file.. Keyset as registered is invalid.
<Exception from HRESULT: 0x8009001A> Failed!

**
For this "Keyset as registered is invalid" error almost every web result says to try renaming RSA file in the path C:\Users\myuser\AppData\Roaming\Microsoft\Crypto to RSA.old and reboot. If that does not work try renaming Crypto folder as Crypto.old. Eventhough I tried these steps it did not resolve the above issue. I am even running the cmd as administrator. So I was not sure what I am missing in here. Would you be help me to find a solution or a workaround for this issue.
Thanks in advance

A: Okay I found the answer.
As I was installing this RSA as a machine level key I should have renamed the RSA to RSA.old in the path C:\ProgramData\Microsoft\Crypto
After rename and I reboot the system. And then did the above mentioned steps again in the cmd. This time it succeded.
Previously I was renaming the RSA folder in the wrong place which is in my personal area (C:\Users\myuser\AppData\Roaming\Microsoft\Crypto).


text:
Q: Sending and receiving data over http in J2ME and handling menus and screens I am new to J2ME and am building a mobile application where users can register, login and be presented with some member only screen where they can perform some operations.
(I am into web development, hence kindly correct me where I use a web approach. Also, I clearly understand basic java concepts but have not built a mobile app before)
So far, I have created the first screen with a login form containing a username and password textbox, and Login and Exit buttons.
The problems I am currently facing are:

*

*How can I provide access to Register, Login and Exit at the same time (it seems the phone can only have two buttons at a time). Do I provide them as command buttons or normal 'web like buttons that appear on page'? Kindly tell me how for any of the options that seems appropriate.

*How do I send and receive data over http in the mobile application? Sample code will be appreciated.

*How do I manage the different screens? In web development, I simply create pages and link them up. In this case, how can I display a register screen when the register button is pressed? The home screen when login is successful? or an error message when unsuccessful?
Do I have different functions that dynamically generates the screens? and I call them each time when the screens are requested?
Simple samples will be highly appreciated.

A: In J2ME,
You have the display object which determines what is shown on the screen. There are something which can be displayed. For example a Form, List, Textbox  etc. Therefore what you can do is you can create the following displays
public class IndexScreen extends List implements CommandListener {

    //This will contain the options
    //1. Register
    //2. Login
    //3. Exit
}

public class RegsterScreen extends Form implements CommandListener {

    //This will contain register fields and submit cancel command buttons

}

public class LoginScreen extends Form implements CommandListener {

   //This will contain Login specific controls
}

Now once these displayable objects are ready you can keep changing the display on some events like click of a command button.
public void commandAction(Command c, Displayable d) {
    if (c == OK) {
        nextScreen = new RegisterScreen();
        display.setCurrent(nextScreen);
    }
    if (c == BACK) {
        display.setCurrent(prevScreen);
    }

For sending and receiving data the following may help....
package madmin.client;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Display;
import madmin.res.Globals;

public class ClientRequest {

private Client client;
private Display display;
private String requestServlet;
private String requestCode;
private String requestId;
private String userId;
private String url;
private String response;
private String parameterOne;

public ClientRequest() {

}

 public boolean sendRequest() {

      boolean result = false;
      userId = Globals.getUserId();
      url = Globals.getURL() + requestServlet + "?requestCode=" + requestCode + "&requestId=" + requestId + "&userId=" + userId + "&clientIP=" + client.getIpAddress() + "&clientHostName=" + client.getHostname() + "&parameterOne=" + parameterOne;

      System.out.println("User Id value in ClientRequest " + userId);

      System.out.println("Start HTTP Connection");
      HttpConnection connection = null;
      InputStream inputstream = null;

       try {
            connection = (HttpConnection) Connector.open(url);
            connection.setRequestMethod(HttpConnection.GET);
            connection.setRequestProperty("Content-Type", "//text plain");
            connection.setRequestProperty("Connection", "close");

            System.out.println("Status Line COde: "+ connection.getResponseCode());
            System.out.println("Status Line Message: "+ connection.getResponseMessage());

            if(connection.getResponseCode()==HttpConnection.HTTP_OK){
                inputstream = connection.openInputStream();
                int length = (int) connection.getLength();
                if(length!=-1){
                    byte incomingData[] = new byte[length];
                    inputstream.read(incomingData);
                    response = new String(incomingData);
                }
                else {
                    ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
                    int ch;
                    while((ch = inputstream.read())!=-1){
                        bytestream.write(ch);
                    }
                    response = new String(bytestream.toByteArray());
                    bytestream.close();
                }

               System.out.println("Response:" + response.trim());

               if(response.trim().equals("Request Submitted Successfully")){
                       result = true;
               }
               else{
                    result = false;
               }
            }
            connection.close();
            if(inputstream!=null)inputstream.close();
        }
        catch(Exception e) {
            e.printStackTrace();
        }
        finally {
            if(inputstream!=null){
                try{
                    inputstream.close();
                }
                catch(Exception e){
                    e.printStackTrace();
                }
            }
        }
     return result;
 }

public Client getClient() {
    return client;
}

public void setClient(Client client) {
    this.client = client;
}

public Display getDisplay() {
    return display;
}

public void setDisplay(Display display) {
    this.display = display;
}

public String getRequestCode() {
    return requestCode;
}

public void setRequestCode(String requestCode) {
    this.requestCode = requestCode;
}

public String getRequestId() {
    return requestId;
}

public void setRequestId(String requestId) {
    this.requestId = requestId;
}

public String getRequestServlet() {
    return requestServlet;
}

public void setRequestServlet(String requestServlet) {
    this.requestServlet = requestServlet;
}

public String getResponse() {
    return response;
}

public void setResponse(String response) {
    this.response = response;
}

public String getUrl() {
    return url;
}

public void setUrl(String url) {
    this.url = url;
}

public String getUserId() {
    return userId;
}

public void setUserId(String userId) {
    this.userId = userId;
}

public String getParameterOne() {
    return parameterOne;
}

public void setParameterOne(String parameterOne) {
    this.parameterOne = parameterOne;
}

}
and....
package madmin.client;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import madmin.res.Globals;

public class ClientResponse {

private String response;

public String getResponse(String requestId) {

         System.out.println("Start HTTP Connection");
         HttpConnection connection = null;
         InputStream inputstream = null;
         response = "";

          try{

            connection = (HttpConnection) Connector.open( Globals.getURL() + "ResponseServlet?requestId=" + requestId);
            connection.setRequestMethod(HttpConnection.GET);
            connection.setRequestProperty("Content-Type", "//text plain");
            connection.setRequestProperty("Connection", "close");

            System.out.println("Status Line COde: "+ connection.getResponseCode());
            System.out.println("Status Line Message: "+ connection.getResponseMessage());

            if(connection.getResponseCode()==HttpConnection.HTTP_OK){
                inputstream = connection.openInputStream();
                int length = (int) connection.getLength();
                if(length!=-1){
                    byte incomingData[] = new byte[length];
                    inputstream.read(incomingData);
                    response = new String(incomingData);
                }
                else {
                    ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
                    int ch;
                    while((ch = inputstream.read())!=-1){
                        bytestream.write(ch);
                    }
                    response = new String(bytestream.toByteArray());
                    bytestream.close();
                }

               System.out.println("Response:" + response.trim());

              connection.close();
              if(inputstream!=null)inputstream.close();
            }
            }
            catch(Exception e){

                e.printStackTrace();
            }

    return response;
}
}

edited:
something like this
     public class MenuScreen extends List implements CommandListener{

     public MenuScreen() {
 append("Register", null);
     append("Login", null);
     append("Forgot password", null);

     select = new Command("Select", Command.OK, 1);
     addCommand(select);
     setCommandListener(this);

}
}
     public void commandAction(Command command, Displayable display) {

      if(command==List.SELECT_COMMAND){
        String menuItem = this.getString(menuIndex);
      }

      if(command==select){
        if( menuItem.equals("Register"))
     display.setCurrent(new RegisterScreen())
 }
      }


text:
Q: Magento different ways to get same variable - which is better? So I am working with some Magento code that was done by another developer (or the pre-installed Magento code, i'm not sure which) and my method for getting the price variable differs from theirs.
We are both trying to access the price of a product.  My method is...
$_configurable_model = Mage::getModel('catalog/product_type_configurable');
$_child_products = $_configurable_model->getUsedProducts(null, $_product);

echo round($_child_product[0]->getPrice(), 2);

The alternative is:
echo $_coreHelper->currency($_price,true,true);

Now obviously their method is shorter, but I do not know how to use the coreHelper-> currency call in order to look at the children product prices so I implemented it my way.
So I am essentially wondering what are the advantages/disadvantages of both of our methods, if any?
Many thanks in advance!

A: Using the helper's currency method takes a number and converts according to the appropriate store's formatting. Since different stores may have different currencies and localization this is very useful.
Since it only needs a number you can mix the methods like this:
Mage::helper('core')->currency($_child_product[0]->getPrice());

The second and third parameters are optional.


text:
Q: PN junction basics: why is there diffusion to create depletion initially? I consider two doping N and P materials.
N and P are neutral, but N is composed of impurities that increase the number of free electron. P is composed of impurities that increase the number of holes.
When we put N and P together, what is said is that the extra electrons from N would move to combine with hole in P. And it will create the depletion region.
What I don't understand is what initiate this motion initially. Indeed, everything being neutral there is no reason for such motion initially.
I barely have understood that there is some competition between the diffusion that is initially created and the electric fields created when the depletion region has been made. What are the mechanisms explaining this diffusion ?
[edit] To make my question more precise: what is the simplest model showing the equations governing the diffusion vs electrostatic forces in this ?

A: Diffusion is a process in which particles move according to their concentration gradient(Higher concentration to lower concentration). It happens because particles have to align evenly in-order to minimize the energy of the system.

A: If your junction is at a temperature $T>0 K$ how certainly it will be because of the third principle of tdm, then the free electrons in the N doped region are moving randomly inside the semiconductor; the same is true for the holes in the P doped region.  When you join the two regions, there will be some free electrons which will move from the N zone to the P, occupying a hole. This process is early stopped by the electric field which is generated by the donor ions near the contact surface. Indeed this electric field generates an energetic barrier which makes harder for electrons to go in the other region; this doesn't mean that there are not electrons that are able to go from the n to the p region, but only the more energetic are able to do so.


text:
Q: Not registered on the local machine I have a problem connecting to the database.It keeps giving this error:
provider local machine is not registered.
My connection string is:
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Users.accdb

•I installed the driver
•I restarted my computer
•My computer is 64bit
Thank you for your help


text:
Q: Объединить несколько строк в одну строку в Pandas Есть датафрейм pandas, у которого искомые значения указаны в индексе.
Как можно объединить строки получив сумму значений столбцов.
Например: исходный датафрейм
               column1    column2    column3    columnN
200100000001    1        20         1              3
200100000009    1        55         1              3
200100000004    1        30         2              12
200100000005    1        50         3              4

из исходного датафрейма ищу значения по индексу из списка
listgroup = [some list]
df[df.index.isin([200100000004,200100000005])]

и хочу получить следующий результат:
                           column1    column2    column3    columnN
200100000004,200100000005   2        80         5              16

количество столбцов, и их наименования заранее не известны


text:
Q: How to prove the existence of $b$ in $Q$ such that $aI would like to prove the existence of $b \in \mathbb Q$ such that $a<b^2<c$ for any given $a,c \in \mathbb Q$ with $a,c>0$
I want to use the statement above to prove a statement in a link
I thought that '$b$' must be exist. But, in my opinion, $\sqrt{}$ can't not be used because $\sqrt{a}$ or $\sqrt{c}$  may not exist in $\mathbb Q$ for some $a$ and $c$.
I couldn't find a clue to prove the statement before the real number is constructed from $\mathbb Q$. Would you help me to prove that?
Thanks all for replying and pointing out errors.

A: Suppose that there is no such $b$. Then for each $n\in\Bbb Z^+$ there is a $k_n\in\Bbb N$ such that $$\frac{k_n^2}{n^2}\le a<c\le\frac{(k_n+1)^2}{n^2}=\frac{k_n^2}{n^2}+\frac{2k_n+1}{n^2}\;.$$ For each $n\in\Bbb Z^+$ we then have $$\frac{2k_n+1}{n^2}\ge c-a$$ and hence $$k_n\ge\frac{(c-a)n^2-1}2$$
and
$$\begin{align*}
\frac{k_n^2}{n^2}&\ge\frac{\left((c-a)n^2-1\right)^2}{4n^2}\\
&=\frac{(c-a)^2n^2}4-\frac{c-a}2+\frac1{4n^2}\\
&\ge\frac{(c-a)^2n^2}4-\frac{c}2\;.
\end{align*}$$
But $a\ge\dfrac{k_n^2}{n^2}$, so we have $$a\ge\frac{(c-a)^2n^2}4-\frac{c}2$$ and hence
$$n^2\le\frac{2(2a+c)}{(c-a)^2}$$
for all $n\in\Bbb Z^+$, contradicting the Archimedean property.

A: Here's a constructive answer based on Newton-Raphson approximation. The construction is guaranteed to work by the Archimedean property (AP), which I'll explicitly state wherever it is needed. It should be clear that this gives an actual simple program to find the desired answer.
$
\def\lfrac#1#2{{\large\frac{#1}{#2}}}
$

First we can assume that $1 < a$, because we can (by AP) multiply the desired equation by $k^2$ for some sufficiently large natural $k$ such that $1 < k^2·a$. Then $a < a^2$.
Let $f(b) = \lfrac{b^2+a}{2b}$ for every rational $b > 0$. Note that $f$ maps rationals to rationals.
Given any rationals $a,b>0$ such that $a < b^2$:
  $f(b)^2 > a$ since $(b^2-a)^2 > 0$.
  $f(b)^2 = \Big( \lfrac{b}{2}+\lfrac{a}{2b} \Big)^2 = \lfrac{b^2}{4}+\lfrac{a}{2}+\lfrac{a^2}{4b^2} < \lfrac{b^2}{4}+\lfrac{a}{2}+\lfrac{a}{4} = \lfrac{3a+b^2}{4}$.
  Thus $0 < f(b)^2-a < \lfrac14(b^2-a)$.
  Thus $0 < f^n(b)^2-a < 4^{-n}(b^2-a)$ for every natural $n > 0$ (by induction).
Therefore $a < f^n(a)^2 < c$ for every natural $n > 0$ such that $4^{-n} < \lfrac{c-a}{a^2-a}$.
We only need one such natural $n$, which exists (by AP) because $\lfrac{c-a}{a^2-a} > 0$.

For simple proofs of the claims involving AP, note that $k^2 \ge k$ for every natural $k$ (by induction), and $4^n \ge n$ for every natural $n$ (by induction), so it suffices to find a natural number $c$ such that $\lfrac1c < \lfrac1a$ and $\lfrac1c < \lfrac{c-a}{a^2-a}$ respectively, which exists by AP.


text:
Q: Get the Members of the local group I am checking weather the user belongs to a particular group. My code is written as follows
public static  bool IsInGroup(string user, string group)
    {
        Console.WriteLine("The user name and group name is {0} {1}", user, group); //Check the parameter values

        bool result = false;
        PrincipalContext context = new PrincipalContext(ContextType.Domain);
        UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(context,user);
        GroupPrincipal groupPrincipal = GroupPrincipal.FindByIdentity(context, group);
        if (userPrincipal != null)
        {
            if (userPrincipal.IsMemberOf(groupPrincipal))
            {
                result = true;
            }
        }
        return result;
    }

But I am facing an error which looks like this
The user name and group name is sampat TestGrp1
Value cannot be null.
Parameter name: group

Is there any possible solution for this issue?

A: groupPrincipal is null because the group are you searching for ('TestGrp1') is never found - most likely it does not exist.
Your code works correctly with an existing group.


text:
Q: JavaFX 2 ComboBox setValue() does not set CB text My problem is that the selected ComboBox item text is not visible on the screen after selecting it with setValue().
Here are some details:
Adding items to my CB:
combo.getItems().add("a");
combo.getItems().add("b");
combo.getItems().add("c");
combo.getItems().add("d");

Afterwards, when Button A is pushed:
combo.setValue(null);

When Button B is pushed:
combo.setValue("a");

Now, if I push Button B first, "a" is shown, thats OK.
After that if I push Button A, no text is shown on the ComboBox, thats OK.
Then I push B, and the value did not change on the screen. However, if I click on the CB, the row for "a" is highlighted, and combo.getValue() returns "a".
Any suggestions how to handle this?

A: I have the same problem. It looks like a bug. Here is a full working example with a ComboBox that contains Locales:
package org.example;

import java.util.Arrays;
import java.util.List;
import java.util.Locale;

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.util.StringConverter;

public final class ComboBoxTest extends Application {
    @Override
    public void start(final Stage stage) throws Exception {
        // Initialize UI
        stage.setTitle("ComboBox Test");
        final HBox root = new HBox(5.0f);
        final ComboBox<Locale> cbLocales = new ComboBox<>();
        cbLocales.setConverter(new StringConverter<Locale>() {
            @Override
            public String toString(final Locale locale) {
                return locale.getDisplayName();
            }

            @Override
            public Locale fromString(String string) {
                throw new UnsupportedOperationException();
            }
        });
        cbLocales.setPrefWidth(250);
        HBox.setMargin(cbLocales, new Insets(10));
        root.getChildren().add(cbLocales);
        final Button btnFill = new Button("Fill");
        HBox.setMargin(btnFill, new Insets(10));
        root.getChildren().add(btnFill);
        final Scene scene = new Scene(root);
        stage.setScene(scene);

        btnFill.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(final MouseEvent event) {
                // Fill with content
                final List<Locale> locales = Arrays.asList(Locale.ENGLISH,
                        Locale.GERMAN, Locale.FRENCH);
                final Locale defaultLocale = locales.get(1);
                // cbLocales.getItems.setAll(locales) doesn't work
                cbLocales.getItems().clear();
                cbLocales.getItems().addAll(locales);
                // Set default locale
                cbLocales.setValue(defaultLocale);
                cbLocales.setPromptText(cbLocales.getConverter().toString(
                        cbLocales.getValue()));
            }
        });

        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

When the ComboBox filled for the first time, all works fine: The ComboBox contains all 3 Locales and the second Locale is set.

After filling a second time, ComboxBox.setValue doesn't work: The ComboBox contains all 3 Locales but the second Locale is not set. No item is selected an no prompt is shown.

I fixed the prompt problem with
// Set default locale
cbLocales.setValue(defaultLocale);
cbLocales.setPromptText(cbLocales.getConverter().toString(
        cbLocales.getValue()));

but it doesn't select the item in the list:

A work around is that:
cbLocales.getSelectionModel().select(defaultLocale);
cbLocales.setPromptText(cbLocales.getConverter().toString(cbLocales.getValue()));

To select the item and set the prompt. But I don't know, if there are athor problems with that (tool tips or similar)

A:
When creating a combo box, you must instantiate the ComboBox class and
  define the items as an observable list, just like other UI controls
  such as ChoiceBox, ListView, and TableView.

Sample Code :
ObservableList<String> options =
    FXCollections.observableArrayList("A","B","C","D");

combo.setItems(options);

now results should be as u expected :) (tested on my local machine)
Reference :
Combo Box

A: I recognized a strange behavior. It looks like the setItems() should not be done before you set your "value"... Here's some code which works for me:
 ComboBox<String> editableComboBox = new ComboBox<String>(); // <- setting the items here
                                                             // brings the "bug"
    editableComboBox.setId("combobox_fields" + i);
    String desciption = pair.getDescription();
    editableComboBox.setValue(desciption);
    editableComboBox.setEditable(true);
    editableComboBox.setItems(FieldType.FIELD_TYPES); // <- here we go!

And here the values..
public static final ObservableList<String> FIELD_TYPES =
            FXCollections.observableArrayList("A", "B", "C",
                                              "D", "E", "F",
                                              "G", "H", "I");


text:
Q: Django - when using different databases - should I use "using" or "db_manager"? To select a specific database you write either:
Object.objects.using('other_db')...

or:
Object.objects.db_manager('other_db')...

Both seem to work completely fine. So what is the difference between both?
EDIT
I mean - should I always use the 'db_manager('other_db')' which would cover all cases for the 'using('other_db')' statement?

A: It depends on your situation. If you don't use any manager method then using() is fine, otherwise you will need db_manager().

You can select the database for a QuerySet at any point in the QuerySet "chain." Just call using() on the QuerySet to get another QuerySet that uses the specified database.

But if you need to use manager methods, this will not work.
The following explanation is taken from the docs:
Say you have a custom manager method that touches the database – User.objects.create_user(). Because create_user() is a manager method, not a QuerySet method, you can't do User.objects.using('another_db').create_user(). The create_user() method is only available on User.objects, the manager, not on QuerySet objects derived from the manager. The solution is to use db_manager(), like this:
User.objects.db_manager('another_db').create_user(...)

db_manager() returns a copy of the manager bound to the database you specify.


text:
Q: Countability of a sequence of natural numbers I am trying to determine if that the set, $T$, of all eventually constant sequences of natural numbers is countable.
My intuition: The set $T$ is countable. . Let $T_j$ denote the set of sequences of natural numbers so that $t_i=t_j$ for all $i>j$.
If we can show that $\mathbb{N}^k$ for all $k\in\mathbb{Z}^+$ is countable, then the union $$T=\bigcup_{j\in\mathbb{N}}T_j$$ is countable as a countable union of countable sets is also countable.
Is my intuition correct?

A: First let's prove that $|\mathbb{N}^2| = |\mathbb{N}|$. An easy way to do this is by using Schröder-Cantor-Bernstein. We easily see that $|\mathbb{N}| \leq |\mathbb{N}^2|$ by sending $n$ to $(n, 0)$. We also find an injection $|\mathbb{N}^2| \leq |\mathbb{N}|$ by sending $(a, b)$ to $2^a 3^b$. By induction we thus have that $|\mathbb{N}^n| = |\mathbb{N}|$ for each natural $n \geq 1$.
Now we can complete the argument based on your sketch.
A finite sequence of length $n$ is just an element of $\mathbb{N}^n$. An eventually constant sequence is a finite sequence with an infinite tail that has constant value $k \in \mathbb{N}$. So for each $n,k \in \mathbb{N}$ there is a set $S_{n,k}$ of sequences that after $n$ values just become the constant sequence with value $k$. Then
$$
|S_{n,k}| = |\mathbb{N}^n| = |\mathbb{N}|.
$$
We have
$$
T = \bigcup_{n,k \in \mathbb{N}} S_{n,k},
$$
which is a countable union of countable sets and hence countable.

As pointed out in the comments below your question, we generally need the axiom of choice (or a weak version of it) to prove that the countable union of countable sets is countable. This is because for each of the sets in the union we would have to choose a bijection. However, we can get around choice by explicitly constructing bijections $\mathbb{N}^n \to \mathbb{N}$. See for example the Cantor pairing function.
Edit: or see the excellent answer of String, describing an explicit bijection directly, showing that we do not need choice.

A: Your suggestion works well, but I just felt tempted to propose the following bijection:
$$
f:T\longleftrightarrow\mathbb N
$$
given by:
$$
f(\{t_1,t_2,...,t_k,t_k,...\})=\prod_{i=1}^k p_i^{t_i-1}
$$
where $p_i$ denotes the $i^{th}$ prime number.

TonyK is completely correct in the comments. I will suggest a fix in a minute!


text:
Q: How to do canary deployments? I have an AWS environment with one ALB, two api nodes and an RDS. I perform in place deployments today. I read about canary releases and was wondering how I could transform my current environment to use canary deployments. My environment is entirely on AWS. The main question I have is about routing, what service/component is needed to dial up/down?

A: Route53's Weighted Routing, The big disadvantage of this approach is that propagating DNS changes can take some time, another approach is to use autoscaling groups(ASG) to upscale the new version and then downscale the old version once you are confident.

Weighted routing lets you associate multiple resources with a single
  domain name (example.com) or subdomain name (acme.example.com) and
  choose how much traffic is routed to each resource. This can be useful
  for a variety of purposes, including load balancing and testing new
  versions of software.


text:
Q: Python module for playing sound data with progress bar? I have an array of raw sound data samples, and I'm trying to make a graphical player that displays the waveform along with the progress of the audio as it plays.
I can plot it easily enough with matplotlib, and I can play it with audiolab, but audiolab appears to have no way to get the "current location" of the playhead.
Are there any modules capable of doing this?

A: If you just want a progress bar and not a "seek" function- just want to show how much is done and left, you can easily build that using tkintr and integrate with whatever you have now.
Otherwise,
There are basically two modules that give you a progress bar.

http://code.google.com/p/py-audio-gui/wiki/PageName

PyAudio plays only MP3. Main drawback. But is easier to use.
There is another module called Snack which supports a lot of different formats and has the progress bar feature as well.
This is a bit harder to use but I heard they did make available some good tutorials/samples recently.
So, I would suggest shift to Snack if you want that.
Cheers.

A: If you know the number of audio frames, and the samplerate, you don't need to audiolab to tell you the current location, you can compute it.
Sndfile.frames / Sndfile.samplerate will give you the duration of the file in seconds, you can then use this in conjunction with elapsed time since since sound file start to compute relative current location. To illustrate the principle:
import time

start_time = time.time()
duration_s = sndfile.frames / sndfile.samplerate

while 1:
    elapsed_time = time.time() - start_time
    current_location = elapsed_time / float(duration_s)
    if current_location >= 1:
         break
    time.sleep(.01)

To implement this in practice, you could use Python threading, to play the sound file asynchronously, and then compute the current location (as above) in the parent thread. To handle the case where playback fails, wrap your call to scikits.audiolab.play() in an exception handler, and then use threading.Event to pass an event to the parent thread if/when the play() call fails.
In the parent thread you would then need to check event.isSet() accordingly:
if current_location >= 1 or fail_event.isSet():
    break

A: I have found a good code which is able to run what you are looking for.
Here is the Link:
https://gist.github.com/deeplycloudy/2152643
I wasn't able to run the code from the author but I have made some corrections in a comment below that repository.
Saludos!!


text:
Q: How to change text color in footline I hope this is not a duplicate question, but I did not find my answer. I have seen how to change the background color of footline, but not how to change text color.
I have this code for my footline:
\makeatletter
\newdimen\mywidth%
\setlength{\mywidth}{\paperwidth}%
\addtolength{\mywidth}{-\beamer@sidebarwidth}%
\setbeamertemplate{footline}
{
  \leavevmode%
  \hbox{%
  \begin{beamercolorbox}[wd=\beamer@sidebarwidth,ht=2.25ex,dp=1ex,right]{sidebar}%
  \end{beamercolorbox}
  \begin{beamercolorbox}[wd=\mywidth,ht=2.25ex,dp=1ex,right]{normal text}%
    \usebeamerfont{date in head/foot}\hfill\insertshortauthor{}\hspace*{2em}
    \insertframenumber{} / \inserttotalframenumber\hspace*{2ex}
  \end{beamercolorbox}}%
  \vskip0pt%
}
\makeatother

This code produces just what I want: Author and frame number in footline, but I want it to show the text in a specific color I have defined before:
\definecolor{beamer@ColorIPN}{RGB}{140,17,17}

My question is, how do I change text color in foot line from black to IPN color?

A: If you look about beamercolorbox in beameruserguide will see that its parameter is a beamercolor. Therefore, your footline uses normal text color to write text in it. As I image you don't want to change normal text definition, I'll explain how to change it for your footline text.
Once you have defined the color you want with
\definecolor{beamer@ColorIPN}{RGB}{140,17,17}

you need to use it in any beamercolor, let's say,
\setbeamercolor{myfootlinetext}{fg=beamer@ColorIPN}

With this command a new beamercolor called myfootlinetext is defined and it foreground component is fixed. Its background component is not defined.
Now you can use where you need it. In this case, replace normal text with myfootlinetext in the second beamercolorbox. That's all.

Following code uses Berkeley theme because your footline failed with default theme.
\documentclass{beamer}

\usetheme{Berkeley}

\makeatletter

\definecolor{beamer@ColorIPN}{RGB}{140,17,17}
\setbeamercolor{myfootlinetext}{fg=beamer@ColorIPN}

\newdimen\mywidth%
\setlength{\mywidth}{\paperwidth}%
\addtolength{\mywidth}{-\beamer@sidebarwidth}%
\setbeamertemplate{footline}
{
  \leavevmode%
  \hbox{%
  \begin{beamercolorbox}[wd=\beamer@sidebarwidth,ht=2.25ex,dp=1ex,right]{sidebar}%
  \end{beamercolorbox}
  \begin{beamercolorbox}[wd=\mywidth,ht=2.25ex,dp=1ex,right]{myfootlinetext}%
    \usebeamerfont{date in head/foot}\hfill\insertshortauthor{}\hspace*{2em}
    \insertframenumber{} / \inserttotalframenumber\hspace*{2ex}
  \end{beamercolorbox}}%
  \vskip0pt%
}
\makeatother

\author{I'm the author}
\title{}

\begin{document}
\section{First Section}
\begin{frame}{First frame}

\end{frame}
\end{document}


text:
Q: onClick Notification to fragment Android I am working on notification part. I am able to navigate user to activity onclick of Notification message. My actual task is to navigate user to fragment.
Here is the notification code which works fine.
NotificationCompat.Builder builder =
            new NotificationCompat.Builder(getApplicationContext())
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("Lugmah Order Status")
                    .setContentText("The Order Status of Order Id: "+selectedOrderId+ " is: "+status_desc)
                    .setDefaults(NotificationCompat.DEFAULT_SOUND)
                    .setAutoCancel(true);
    int NOTIFICATION_ID = 12345;

    Intent targetIntent = new Intent(getApplicationContext(), MainActivity.class);

    targetIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    targetIntent.putExtra("isTrackOrder", false);
    targetIntent.putExtra("orderNotification", "orderNotification");
    targetIntent.putExtra("isLoggedIn", true);
    targetIntent.putExtra("status_desc", status_desc);
    targetIntent.putExtra("selectedOrderId", selectedOrderId);

    PendingIntent contentIntent = PendingIntent
                .getActivity(getApplicationContext(), 0, targetIntent, PendingIntent.FLAG_ONE_SHOT);

    builder.setContentIntent(contentIntent);

    NotificationManager nManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
    nManager.notify(NOTIFICATION_ID, builder.build());

I have added MainActivity.java in intent because that is the place I load all fragments. In this activity, I did something like this.
Here is the code inside onCreate():
String orderNotification = getIntent().getStringExtra("orderNotification");

        android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();

        if (orderNotification != null)
        {
            if (orderNotification.equals("orderNotification"))
            {
                TrackOrderFragment trackOrderFragment = new TrackOrderFragment();
                fragmentTransaction.replace(android.R.id.content, trackOrderFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
            }
        }

Help would be appreciated.

A: Your notification code works fine you need to adjust a bit the code onCreate.
if(getIntent().getExtras() != null) {
   String orderNotification = getIntent().getStringExtra("orderNotification");

  if (orderNotification.equals("orderNotification"))
            {
                TrackOrderFragment trackOrderFragment = new TrackOrderFragment();
                fragmentTransaction.replace(android.R.id.content, trackOrderFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
            }
        }

You need to check if you are receiving any extras every time your activity runs onCreate because a null pointer exception can occur.


text:
Q: How to shorten \hline in a matrix I indicate blocks in a matrix using \hline:
\documentclass{article}
\usepackage{amsmath}
\begin{document}
  \begin{equation*}
    \begin{bmatrix}
      a & b\\
      \hline
      c & d
    \end{bmatrix}
  \end{equation*}
\end{document}
\endinput

However, for normal point sizes the document is generated in (11pt), the rule drawn crosses over the matrix borders. (For poster sizes, this is not the case.)
How can I shorten the rule on both sides so that this does not occur, while still preserving the vertical spacing provided by \hline?

A: Try switching to array instead, apparently the bmatrix environment doesn't work well with horizontal lines (judging from what I've seen in other forums).
If you switch between \begin{array}{@{}cc@{}}, as suggested by daleif, \begin{array}{cc}, it will change the appearance.

\documentclass{article}
\usepackage{amsmath}
\begin{document}
    \[ \left[ \begin{array}{@{}cc@{}}
    a & b \\ \hline
    c & d
    \end{array} \right]
    %
    \left[ \begin{array}{cc}
    a & b \\ \hline
    c & d
    \end{array} \right]
    \]
\end{document}

A: The bmatrix environment and also the other matrix related ones use internally array, but do a backup after the left delimiter and before the right one. Therefore the rule made by \hline presents the problem you're facing.
There are technical reasons for using a backup rather than removing the intercolumn spacing at either end with @{}. There are two different solutions; one is to use booktabs and the other one is making a new environment for matrices with rule separators.
The first is more elegant, in my opinion. Both require you to specify the columns in some way.
\documentclass{article}
\usepackage{amsmath}

\usepackage{booktabs} % required for the first solution

% this is for the second solution; the argument is the number of columns
\newenvironment{lbmatrix}[1]
  {\left[\array{@{}*{#1}{c}@{}}}
  {\endarray\right]}

\begin{document}
\begin{equation*}
\begin{bmatrix}
  a & b\\
  \cmidrule(lr){1-2}
  c & d
\end{bmatrix}
\end{equation*}
\begin{equation*}
\begin{lbmatrix}{2}
  a & b\\
  \hline
  c & d
\end{lbmatrix}
\end{equation*}
\end{document}


text:
Q: TCP socket connection interference on send message in Kubernetes I'm creating an application in C that intermediates and manages scheduled applications (NodeJs) to collect information into MongoDB.
This makes possible the application's scalability and avoids replicated values.
Problem

*

*Local tests: OK

*Container tests: Ok

*K8s Minikube tests: scheduled application error in bson parse

*EKS Production tests: scheduled application error in bson parse

Code of C application to send socket message:
static void
ssq_connection_server_handler()
{
    ...

    for (i = 0; i < ssq_max_sockets; i++) {
        sd = ssq_connection->clients[i];
        if (FD_ISSET(sd, &master)) {
            if ((ret = ssq_connection->recv(sd, buffer, SSQ_SERVER_MAX_BUFFER_SIZE)) <= 0) {
                continue;
            }

            buffer[ret] = '\0';
            token = ssq_strtok(buffer, ":");
            opts = ssq_strtok(NULL, ":");

            limit = ssq_atoi(opts, ssq_strlen(opts));
            if (limit == SSQ_ERROR) {
                limit = 10;
            }

            if (ssq_strcmp("next", token) == 0) {
                u_char *tasks;
                size_t len;

                tasks = ssq_mongo_collection_find(limit, ssq_mongo->collection, &len);
                ssq_connection->send(sd, tasks, len);
            }
        }
    }

    ...
}

static ssize_t
ssq_connection_send_handler(int fd, u_char *buf, size_t size)
{
    ssize_t n;
    ssq_err_t err;

    for (;;) {
        n = send(fd, buf, size, 0);

        ssq_log_debug("send: fd:%d %z of %uz", fd, n, size);

        if (n > 0) {
            return n;
        }

        err = ssq_socket_errno;

        if (n == 0) {
            ssq_log_error(SSQ_LOG_ALERT, err, "send() returned zero");
            return n;
        }

        if (err == SSQ_EAGAIN || err == SSQ_EINTR) {
            ssq_log_debug_error(err, "send() not ready");

            if (err == SSQ_EAGAIN) {
                return SSQ_AGAIN;
            }
        } else {
            return SSQ_ERROR;
        }
    }
}

Code in NodeJs to receive message:
const net = require('net');
const { EJSON } = require('bson');

const sock = new net.Socket();

sock.connect(process.env.SSQ_PORT || 3145, process.env.SSQ_HOST || '127.0.0.1', () => {
    console.log('socket connection established');
});

sock.on('data', (data) => {
    try {
        const tasks = EJSON.parse(data);
        console.log(tasks);
        process.exit(0);
    } catch (err) {
        console.error(err);
        process.exit(1);
    }
});

sock.on('error', () => {
    /* void */
});

sock.on('close', () => {
    console.warn('socket connection has been closed');
});

sock.write(Buffer.from('next:10'));

I think that something coming from K8s is intercepting and modifying the message.


text:
Q: DataObjectSerializer interface implementation CS0535 I am trying to make a class of my project serializable so I can exchange objects of it throgh a network for a client/server-application.
Since I also want to include "child"-objects and private members I chose to do so with the help of DataContractSerializer.
However, although I am layzily trying to copy-paste my first draft out of MSDN's respective site, do not get good results. I already referenced the System.Runtime.Serialization.dll as well as all the related namespaces.
Here's my issue:
When trying to compile I get

CS0535 'Server.Anfrage' does not implement interface member 'System.Runtime.Serialization.IExtensibleDataObject.ExtensionData' (CS0535)

although I got my the specified member implemented.
For now I am only trying to get it to work with the 3 strings, but later it's going to be more.
[DataContract]
public class Anfrage : IExtensibleDataObject
{

    [DataMember]
    internal string sender, aktion, param;

    internal halbAuftrag execute(){

        Bahnhof von = Program.bahnhoefe[Program.getIndex(sender)];
        Bahnhof zu = Program.bahnhoefe[Program.getIndex(param)];

        return new halbAuftrag(von, aktion, zu);
    }

    internal ExtensionDataObject extensionData_Value;

    public ExtensionDataObject extensionData {

        get {
            return extensionData_Value;
        }

        set {
            extensionData_Value = value;
        }
    }
[...]
}

Can anyone tell me why I am getting the aforementioned error?
Thanks a lot.

A: You have a small typo. The following line
public ExtensionDataObject extensionData {

Should be
public ExtensionDataObject ExtensionData {

(capital E)


text:
Q: How to set margins to two div inside another div? I want to set different margins to two divs, inside another div. The first div should appear top of the second div.

   This should be appar top of the second div.

   second div

</div

I used above mention code, but first div also getting margin 50, not margin 24.
How to resolve this issue?
Cannot use position:absoulte to the second div.

A: enter this code  inside div
margin: 5px auto;

A: You can use the following code:

       This should be appar top of the second div.

       second div


text:
Q: Why does PySequence_GetItem return a new reference? I've been caught out by a memory leak in a C/C++ python extension for assuming that PySequence_GetItem would return a borrowed reference, in the same way as PyList_GetItem and PyTuple_GetItem. My question is: why does PySequence_GetItem return a new reference while PyList_GetItem and PyTuple_GetItem return borrowed references?
From the docs:
PyObject* PySequence_GetItem(PyObject *o, Py_ssize_t i)
    Return value: New reference.
    Return the ith element of o, or NULL on failure. This is the equivalent of the Python expression o[i].

A: You get the new reference from PySequence, because this is what the PySequence-protocol defines.
There are however good reasons, to define the protocol this way: not all sequencies are backed by memory (like list, tuple), for some the items are created on the fly (like range, unicode).
For list and tuple all items are owned by the list/tuple (they aren't temporary objects) so we can borrow them (the borrowing is a small optimization) - the list/tuple will free the memory in the end.
range is another example for a sequence. It implements PySequence-protocol):
static PySequenceMethods range_as_sequence = {
    (lenfunc)range_length,      /* sq_length */
    0,                          /* sq_concat */
    0,                          /* sq_repeat */
    (ssizeargfunc)range_item,   /* sq_item */
    0,                          /* sq_slice */
    0,                          /* sq_ass_item */
    0,                          /* sq_ass_slice */
    (objobjproc)range_contains, /* sq_contains */
};

However, the objects returned by PySequence_GetItem are temporaries (i.e. nobody owns a reference to it outside of the function), we can verify this in the source code of range_item:
static PyObject *
range_item(rangeobject *r, Py_ssize_t i)
{
    PyObject *res, *arg = PyLong_FromSsize_t(i);
    if (!arg) {
        return NULL;
    }
    res = compute_range_item(r, arg);
    Py_DECREF(arg);
    return res;
}

where compute_range_item boils down to compute_item:
static PyObject *
compute_item(rangeobject *r, PyObject *i)
{
    PyObject *incr, *result;
    /* PyLong equivalent to:
     *    return r->start + (i * r->step)
     */
    incr = PyNumber_Multiply(i, r->step);
    if (!incr)
        return NULL;
    result = PyNumber_Add(r->start, incr);
    Py_DECREF(incr);
    return result;
}

Nobody owns the object in returned result, thus the receiver has to take care for decreasing the reference count.
There are maybe other solutions possible (some kind of caching of created items), but returning a new reference is the most simple/transparent way to handle the problem of items created on the fly.


text:
Q: How can I assign a Google Sheet script to only one sheet? I have this script here, but I want it to only run on ONE specific sheet named "Nes Smart Data" (SheetNo5). Currently it runs on all sheets and puts the data on cells where I don't want them to be. Can you help me correct the code? Thanks a lot!
function onEdit(e){
  var sheet = SpreadsheetApp.getActiveSheet();
  var range = e.range;
  var column = range.getColumn();
  var row = range.getRow();
  var text;

  if (column==11) { //Replace 2 with the column number of your comments cell//
    var newRange = sheet.getRange(row,column-5); //If the date is in the next column
    var today = Utilities.formatDate(new Date(),Session.getScriptTimeZone(),'dd.MM.yyyy');
    newRange.setValue(today);
  }
  if (column == 11){
    text = sheet.getRange(row, 23).getValue();
    sheet.getRange(row, 23).setValue(text + e.value+".");
  }
}

A: Replace the following variable and things should work as desired -
Current:
var sheet = SpreadsheetApp.getActiveSheet();
Modification proposed:
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Nes Smart Data');
Let me know if it doesn't!


text:
Q: How to Back Up and Verify a Windows 10 System Partition on Linux? I have a dual-boot computer running Windows 10 and Fedora 31.  I would like to image my Windows 10 partition, but am not fully comfortable with its own backup facilities.  Therefore, I am looking for a way to do this from my Fedora system.
In the past, I have successfully used partimage to image my Windows 7 systems.  I've also tried fsarchiver, but that gave (non-fatal) error messages which made me reluctant to trust it.  When I try to image my Windows 10 system with partimage, I now get two non-fatal error messages: one saying that partimage can't handle resident attributes, and the other saying it can't process $BITMAP.  I have no idea what the consequences of these errors are, so again I don't want to trust that I can recover fully from this backup.  I've tried fsarchiver, but that now gives me fatal errors.  I've tried ntfsclone, and this apparently worked; at least it generated no error messages.
But how do I know if I can recover my Windows 10 system using the ntfsclone-generated backup if I need to?  The fact that partimage now shows errors when it didn't in the past may mean that Windows 10 uses some aspects of ntfs which are new or weren't used by Windows 7; how do I know whether ntfsclone handles these aspects correctly?  I could restore the image to an unused partition, but don't know how to verify that the file systems are identical.  There is the ntfscmp utility, but that is part of the same package as ntfsclone, and therefore could have the same shortcomings (if any).
Any suggestions?

A: ntfsclone actually performs a block-level copy, and the only NTFS-specific feature is that it skips clusters which are marked as "unused" in the NTFS allocation bitmap ($Bitmap file). After reading this single file, it copies all data structures without even trying to parse them. This means that ntfsclone doesn't have to deeply understand all new features – only the most essential ones.
What I would try is to make a full-size image using dd, mount it on Linux as a loop image, run fstrim against the mounted filesystem (which will discard unallocated clusters), then unmount and compare the trimmed "full" image against the ntfsclone-created image. They should be mostly identical.
You could also convert the image from 'raw' to 'VHD' (vpc) or 'VHDX' format using qemu-img or vboxmanage, then see if it can be successfully mounted on a different Windows 10 system. (Alternatively, attach it to a VM running Windows 10.) Then run chkdsk to make sure there aren't any obvious issues.

I have recently used the Windows dism /create-image tool to create a WIM-format image of the entire system partition. It is specifically meant for creating images of the OS partition (and that's also how the OS gets installed in the first place); WIM images are file-level but that should not cause any issues. You can run it from a Windows install USB stick – just minimize the installer window and hit Shift+F10 to open a command shell.


text:
Q: Cannot install NodeJS via NUGET While trying to install Node.js via the Nuget package manager, I am getting the following error. No further information to tap into. Any idea what is happening there?
I tried changing the .NET framework version of the project but I still get the same issue.
A few other people on different forums have pointed out similar issues while installing nodejs via the package manager. Just want to make sure if this is known issue.

Could not install package nodejs-v.0.8.16 0.8.16. You are trying to install this package into a project that targets
  .NETFramework,Version=v4.5.2, but the package does not contain any
  assembly references or content files that are compatible with that
  framework.
For more information, contact the package author.

A: Reading your problem statement; I believe you're trying to run Node.js from a localized directory within your solution directory structure instead of installing node.js separately.
The official package from the Node.js Foundation - node.js (note the ".") - The Official node.js package is what you are likely after, you'll notice this indeed does work when executed against a 4.5.2+ project like the one you were testing against:
Install-Package Node.js

Note: The absolute oldest version you can install for this particular package against a 4.5.2 project is 0.10.26.1 from what I tested.

Side note:
What you were referencing is a substantially older package of "nodejs"  (note the missing ".") from here which I checked out myself, it doesn't install irrespective of the framework version specified in project properties, also 0.8.16 is old.


text:
Q: How to enable codelens for merging I recently got a new device and have been playing around with git and tried to merge two branches, but vscode's codelens doesn't seem to show the usual "accept current change accept incoming change" menu. Instead, it just puts it in raw text - how do I fix this?
What it is currently:

Desired:


text:
Q: Apache doesn't let Flask app create file I'm trying to get a JPEG image from an app to another. Where I'm receiving it, the stream comes on the request's body and I try to make the file whole again, like this:
if r.status_code == 200:
    f = open(os.path.join(os.path.dirname(os.path.realpath(__file__)) + "\\static\\tmp\\" + filename), 'wb')
    f.write(r.content)
    f.close()
    return True

which works just fine when running in localhost. The file is in its place and just like it was when I uploaded it.
When I went to deploy all the apps and test them, Apache didn't allow me to do f = open(...), giving me the error:
IOError: [Errno 13] Permission denied: u'/var/www/my_url\\static\\tmp\\2378687.jpeg'

And that's strange, because the tmp folder has the attributes
unconfined_u:object_r:httpd_sys_rw_content_t:s0

Shouldn't it allow me to create the new file, even not being the sudo user?

A: *

*Use os.path.join instead of \\. This make your code more portable between linux/windows os.
f = open(os.path.join(os.path.dirname(os.path.realpath(__file__), "static,"tmp" , filename), 'wb')

*you are not referring to /tmp, instead you are trying to write in static folder: /var/www/my_url. Try to use absolute path for this.

A: You have a bug in line the very first line of your function. It should be
f = open(os.path.join(os.path.dirname(os.path.realpath(__file__),
                      "static", "tmp", filename), 'wb')

The directory separator is different on Windows and Linux. That is why it works locally, but not on the server. The os module is there to abstract away those differences, but you don't actually use it to construct your filename. The way your code is written, the os.path.join() is a noop.
Your code tries to write a file named my_url\static\tmp\2378687.jpeg to the directory /var/www/my_url.
Also, you should use a context manager, probably a configurable constant for the file path and catching errors would be good idea, too:
UPLOAD_DIR = '/var/www/my_url/static/tmp'

if r.status_code == 200:
    try:
        with open(os.path.join(UPLOAD_DIR, filename), 'wb') as f
            f.write(r.content)
    except IOError as e:
        # log e.message or something
        return False
    return True


text:
Q: Does the Transcend JetDrive Lite 360 fit on iMac? Transcend JetDrive 360 is a nice option to expand storage on mbp 15" Mid 2015.
I'm wondering if it can be used on iMac also, can someone confirm? Or somewhere else besides mbp 2015.

A: This FAQ at Transcend (which is linked to at the bottom of the link you provided) indicates indirectly that the only non-laptop mac compatible with the JetDrive Lite series is a Mac Mini.
I used one of these JetDrive devices several years ago on a 2nd gen MBA, and it is designed to lie flush with the edge of the laptop to prevent damage whilst in a bag or elsewhere. If I were going to try using one of these devices, I'd choose the one with the greatest length to make sure it seats correctly in the internal SD socket.
On the other hand, any of the high-performance SD cards now on the market will be much less of a pain to use with your iMac. Personally, I'd choose a SanDisk, Sony or Transcend SD card.
Remember that no matter how much improvement has been made in the quality of SD card fabrication and data reliability over the years, they are still more fragile than other data storage media, and are susceptible to data loss from static shock and other environmental conditions such as high magnetic fields, moisture and excessive heat.
Disclaimer: I'm a satisfied user of SanDisk, Sony and Transcend products, and have no financial or other ties with these companies.


text:
Q: How to avoid gaps in fluid grid using packery I am an amateur and beginner trying to make my first web page with a fluid image grid for vertical and horizontal photos with same height. So I am applying the Packery javascript to make it more responsive.
See link to Codepen: http://codepen.io/nor159/pen/WbpWpe/?editors=110
    * {
margin: 0px 0px 0px 0px;
padding: 0px 0px 0px 0px;
border: 0px 0px 0px 0px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
body {
background: #f0f0f0;
}
img {
width: 100%;
display: block;
}
.packery {
margin: 8% 8% 8% 8%;
}
.packery:after {
content: ' ';
display: block;
clear: both;
}
.item {
float: left;
}
@media screen and  (max-width:400px) {
.item.v, .grid-sizer {
width:  calc(4/14*100%);
}
.item.h {
width:  calc(9/14*100%);
}
.gutter-sizer {
width:  calc(1/14*100%);
}

I find 2 problems:
1) Open gaps between the images appear randomly as I resize the screen.
2) Loading in Chrome gives overlapping images.
Does anyone know how to resolve this? Can this grid be made using Packery?
Response to my questions will be highly appreciated.
Regards
Jan, Oslo

A: Not sure if this will help 100% but Using imagesLoaded(), has fixed some of my problems with masonry before. you can find more information @ http://packery.metafizzy.co/appendix.html
$(document).ready(function(){

         // element
imagesLoaded( document.querySelector('#container'), function( instance ) {
 console.log('all images are loaded');
});
// selector string
imagesLoaded( '#container', function() {
    var $container = $('#container').packery({
        gutter: 10,isHorizontal:false,stamp: '.stamp',itemSelector: '.item',columnWidth: '.grid-sizer'});
        });
});
// multiple elements

another trick is to put the image larger than its supposed to be in the grid. The woman married to the Guy that Sings that 99 problems song => her site did this:
container img{width:105%}


text:
Q: NEHotspotConfiguration is not working in ios 11 I tried to connect the specific wifi with ssid and password using NEHotspotConfiguration, it has the internal server error.
Please help me if you have the answer for how to connect to a wifi AP on ios.

A: Try the following:

*

*To enable Network Extensions and Hotspot within App IDs.

*Xcode -> TARGETS -> Capabilities open Network Extensions and Hotspot.

*import  in the your code.

Here is my code, it may work for you:
-(IBAction) joinWiFi_ButtonPressed: (id) sender {

    if (@available (iOS 11.0, *)) {
        NEHotspotConfiguration * configuration = [[NEHotspotConfiguration alloc] initWithSSID: @ "Your SSID" passphrase:            @ "Password" isWEP: NO];
        configation.joinOnce = YES;
        [[NEHotspotConfigurationManager sharedManager] applyConfiguration: configuration completionHandler: ^ (NSError * _Nullable error) {
        if (error == nil) {
            NSLog (@ "Is Connected!!");
        } else {
            NSLog (@ "Error is:% @", error);
        }}];
        } else {
            NSLog (@ "This Device Not iOS 11 +");
        }
    }

Can you post your error log? It could help me to better understand your question and refine my answer.


text:
Q: HTML button to run SQL command I'm a bit of a noob at php/sql (well all languages in general), I am trying to get an sql command to run on the click of a html button.
The sql command that I am trying to run is UPDATE supplies SET quantity = quantity + 1 WHERE Id=1
This is what I have at the moment:
dp.php
<?php
$servername = "localhost";
$dbname = "tonor";
$username = "root";
$password = "password";

    try {
        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch(PDOException $e) {
        echo "Connection failed: " . $e->getMessage();
    }
?>

index.php
<!DOCTYPE html>

    <?php
        require_once 'db.php';

        if(isset($_POST['data'])){
            $sth = $conn->prepare("UPDATE supplies SET quantity = quantity + 1 WHERE Id=1");
            $sth->execute();
        }
    ?>
    <title>Homepage</title>
    <link rel="stylesheet" type="text/css" href="style/main.css">

testpage

    <form method="POST" action="index.php">
        <input type="submit" name="data" value="1"/>
    </form>

A: You should try this out, but you need to read, and practice further.
PDO manual: http://php.net/manual/en/book.pdo.php
It's a lot to look at, but just take a look at their examples to get an idea of how it works.
Read this as well to make it easier: https://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
PHP is a server side language.
I any case, the following should be enough to get you started.
 <?php
    $servername = "localhost";
    $dbname = "databasename";
    $username = "username";
    $password = "password";

    try {
        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch(PDOException $e) {
        echo "Connection failed: " . $e->getMessage();
    }

    return $conn;
?>

<!DOCTYPE html>

    <?php
        require 'db.php';

        if(isset($_POST['data'])){
            $sth = $conn->prepare("UPDATE supplies SET quantity = quantity + 1 WHERE Id=1");
            $sth->execute();
        }
    ?>
    <title>Homepage</title>
    <link rel="stylesheet" type="text/css" href="style/main.css">

testpage

    <form method="POST" action="">
        <input type="submit" name="data" value="1"/>
    </form>

A: I am answering on john's post.
The reason it executes every time you reload the page is because the browser resends the post data to the server. You need to use header() to redirect on post. Your code is not perfect but it works. You should organize it. Maybe place all database logic in a class. An example of redirection that works for this example.
<?php
    if(isset($_POST['data']))
    {
        require 'db.php';
        $sth = $conn->prepare("UPDATE supplies SET quantity = quantity + 1 WHERE Id=1");
        $sth->execute();
        header("Location: {$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']}");
        die("Posted, now redirecting");
    }
?>


text:
Q: Drawable offset Добрый день, имеется такой xml
<layer-list>
        <item android:top="2dp">
            <shape
                   android:shape="rectangle">
                <solid android:color="@color/btn_pressed_color"/>
            </shape>
        </item>

        <item android:bottom="2dp"
              android:top="2dp">
              <shape
                    android:shape="rectangle">
                <solid android:color="@color/btn_normal_color"/>
              </shape>
        </item>
</layer-list>

Необходимо создать его программно, конкретно интересует <item android:top="2dp">
setPadding не помогает, что можно придумать?
A: У меня есть класс который создавал программно ползунок для моей линии прокрутки. Он к сожалению узкоспециализирован. Конструктор вам скорее всего не нужен, попробуйте изменить нули в двух методах. Они вроде как отвечают за зазор, может поможет:
public class ThumbCreator {

    private Resources res;
    private BitmapDrawable left, right;

    public ThumbCreator(Resources r) {
        res = r;
        right = (BitmapDrawable) res
                .getDrawable(android.R.drawable.ic_media_play);
        right.setGravity(Gravity.RIGHT);
        Bitmap rightBitmap = BitmapFactory.decodeResource(res,
                android.R.drawable.ic_media_play);
        Matrix x = new Matrix();
        x.setScale(-1, 1);
        Bitmap leftBitmap = Bitmap.createBitmap(rightBitmap, 0, 0,
                rightBitmap.getWidth(), rightBitmap.getHeight(), x, true);
        left = new BitmapDrawable(res, leftBitmap);
        left.setGravity(Gravity.LEFT);
    }

    public Drawable createScrollBarThumb() {
        Drawable array[] = new Drawable[] {
                left.getConstantState().newDrawable(),
                right.getConstantState().newDrawable() };
        LayerDrawable layer = new LayerDrawable(array);
        layer.setLayerInset(1, right.getBitmap().getWidth(), 0, 0, 0);
        return layer;

    }

    public Drawable createZoomSBThumb() {
        BitmapDrawable mag = (BitmapDrawable) res
                .getDrawable(android.R.drawable.ic_menu_search);
        mag.setGravity(Gravity.CENTER);
        Drawable array[] = new Drawable[] {
                left.getConstantState().newDrawable(), mag,
                right.getConstantState().newDrawable() };
        LayerDrawable layer = new LayerDrawable(array);
        layer.setLayerInset(2, mag.getBitmap().getWidth()
                + left.getBitmap().getWidth(), 0, 0, 0);

        return layer;
    }
}


text:
Q: Angularjs State transition I am building a hybrid mobile app using ionic framework and cordova (first time).I am having problems with state transition because by default angular renders the template before completing the transition.This makes the the app look slow (when you click a menu item and wait for it to come).This happens only for those who load data from local storage or service! My Question is: How can I make the template come empty in the moment I click the menu item , then show a loader until the template is ready.Below is some code is use in my menu controller for the state transition!
//I use ng-click="navigateTo('state name')"

$scope.navigateTo = function (stateName) {
    $timeout(function () {
        $mdSidenav('left').close();
        if ($ionicHistory.currentStateName() != stateName) {
            $ionicHistory.nextViewOptions({
                disableAnimate: false,
                disableBack: true
            });
            $state.go(stateName);
        }
    }, ($scope.isAndroid == true ? 1000 : 0));
};// End navigateTo.

Below is the controller code for the view that needs a solution
appControllers.controller("calendar_Ctrl", function($scope,$rootScope, $state,$stateParams, $ionicHistory, $filter, $q, $timeout, $log, MaterialCalendarData, $moment) {
$scope.isAnimated =  $stateParams.isAnimated;

$scope.selectedDate = null;
$scope.weekStartsOn = 0;
$scope.dayFormat = "d";
$scope.disableFutureDates = false;
$scope.directionn = "horizontal";

$scope.setDirection = function(direction) {
    $scope.directionn = direction;
    $scope.dayFormat = direction === "vertical" ? "EEEE, MMMM d" : "d";
};

$scope.dayClick = function(date) {
    $scope.msg = "You clicked " + $filter("date")(date, "MMM d, y h:mm:ss a Z");
};

$scope.setContentViaService = function() {
    var today = new Date();
    MaterialCalendarData.setDayContent(today, '<span> :oD </span>')
}

$scope.getItems = function(){
  if(localStorage.getItem("eventsData")){
     var eventsData = localStorage.getItem("eventsData");
     return JSON.parse(eventsData);

  }else{
    return [];
  }
}

var events =  $scope.getItems();

// You would inject any HTML you wanted for
// that particular date here.
var numFmt = function(num) {
    num = num.toString();
    if (num.length < 2) {
        num = "0" + num;
    }
    return num;
};

var loadContentAsync = false;
$log.info("setDayContent.async", loadContentAsync);
$scope.setDayContent = function(date) {

    var key = [date.getFullYear(), numFmt(date.getMonth()+1), numFmt(date.getDate())].join("-");
    var data = (events[key]||[{ type: ""}]);

    if (loadContentAsync) {
        var deferred = $q.defer();
        $timeout(function() {
            deferred.resolve(data);
        });
        return deferred.promise;
    }

    return data;

};

$scope.isAnimated =  $stateParams.isAnimated;

});

Thank You Very Much for your time and help!!

A: Hi Use $ionicLoading Service to solve this problem,
http://ionicframework.com/docs/api/service/$ionicLoading/


text:
Q: Is there any interruption of service when switching recovery models? I need to switch to FULL recovery model for several SQL Server 2008 databases. However these are in production. Whilst doing these things out of hours is good practice I wanted to plan for any down time or interruption in service, no matter how brief.
Does anybody know the impact changing the recovery model to Full has on a production database?
Clarification: I have a whole process scripted (backup's and logging) and tested for log shipping and restoring the other end. However the one thing I couldn't find details on was if changing the model would have an impact on availability or performance during the process.

A: I've never had any issues from switching from simple to full. You will have to consider your backups tho.
Microsoft has some information about making the switch in the link below,
http://technet.microsoft.com/en-us/library/ms178052(v=sql.105).aspx


text:
Q: Obtaining the surface area element geometrically My text book derives a parametric formula for the surface area element $dS$ (which I follow and can understand). However it then goes on to remark that the surface area element can also be obtained geometrically as
$$dS=\bigg|\frac{1}{\cos\theta}\bigg|dxdy=\frac{|\textbf{n}|}{|\textbf{n} \bullet\textbf{k}|}dxdy$$
where $\cos\theta$ is the angle between the normal vector n to the surface, and the unit vector k in the direction of the positive z-axis.
I am confuse with the $\bigg|\frac{1}{\cos\theta}\bigg|$ part? I thought that $\cos\theta$ might come from $\textbf{n} \bullet\textbf{k}=|\textbf{n}||\textbf{k}|\cos\theta$, where $|\textbf{n}|=|\textbf{k}|=1$ but I think this assumption is wrong as $\textbf{n}$ is not a unit vector nor does it explain why the fraction $\frac{1}{\cos\theta}$?


text:
Q: Does remote mysql databases support ajax? I keep getting 500 internal errors when trying to make any calls I recently just deployed my laravel application on to Heroku but not having any success when making Ajax requests. Offline everything works perfectly but for some reason after deployment I just receive 500 internal error status code, connection refused. I've downloaded the heroku cli and ran composer install/npm install, generated a key, and cleared the cache. I'm able to even run php artisan:migrate succesfully and populate the tables.
I have the csrf token in my headers, I've tried to use Heroku's cleardb, an AWS RDS, and finally tried to use a remote MySQL database from hostinger.
I have a Students.Vue component that is supposed to fetch from the api or use a standard get to receive the list of students. I've tried both ways and still receive a 500 internal error, connection refused.
Csrf in the meta:
 <meta name="csrf-token" content="{{ csrf_token() }}">

<script>
export default {
window.axios = require("axios");
window.axios.defaults.headers.common = {
  _token: document
    .querySelector('meta[name="csrf-token"]')
    .getAttribute("content"),
  "X-Requested-With": "XMLHttpRequest",
  "X-CSRF-TOKEN": document
    .querySelector('meta[name="csrf-token"]')
    .getAttribute("content")
};
  data() {
return {
  loading: '',
  students: []
  }
},

 methods: {
      fetchStudents() {
     this.loading = true;
  axios
    .get("api/students")
    .then(res => {
      this.loading = false;
      this.students = res.data;
    })
    .catch(err => {
      this.loading = false;
      alert(err);
    });
},

created() {
this.fetchStudents();
 }
}
</script>

How the route looks in web.php and api.php:
Route::get('students/', 'StudentController@index');

My index function:
use App\Student;

public function index()
{
    return Student::latest()->get();
}

Is there something I'm doing wrong? Or is there a remote database server that supports Ajax pretty well?


text:
Q: Microsoft Word - Column breaks too soon for no apparent reason
On one page in my document the column breaks too soon and leaves a blank space in the bottom left of the page. It breaks in the middle of a sentence and the only way to fill that space is to add more text at the top left of the page, which unfortunately isn't an option for me.
There are no column breaks or anything. What can I do to make it use that blank space and only break once it's full?
I'm using Office 365.


text:
Q: Remove useless zero from scientific notation in PHP Is there any way to Remove useless zero from scientific notation and make the number as simple as possible.
In PHP I have the following code:
<?PHP
  $result = 1/1000000000;
  echo $result;
?>

the output is 1.0E-9
it should 1E-9

A: If you need it this way you can use str_replace:
$result = 1/1000000000;
echo str_replace(".0E", "E", $result);

This outputs 1E-9


text:
Q: how to write Rails3 routes exceptions? Hello
I have an application where URI looks like http://mysite.com/post1 or http://mysite.com/post2 etc.
But with routing as this i can't get images because it stored at http://mysite.com/images/ folder in my server.
So how to overcome this problem?

A: How about using the path_to_image() or image_tag() helper?

A: Take a look at Compass. It is a stylesheet authoring framework which allows you to use helpers such as image_url in scss stylesheets. image_url can be used in combination with a configuration variable asset_host, that prepends that path to images in your stylesheets.
Here is an example:
.content{
  background: image_url("background.png") "no-repeat";
}


text:
Q: Flutter Hero Animation dismissing keyboard on textfield I have two screens with different size of text fields. I am trying to make a hero animation for them. I want the end text field to auto focus, but the keyboard get dismissed at the second screen.
I tried to use flightShuttleBuilder to check if the animation is completed and request focus. But it is not working.

Here is the code for the second screen
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class Search extends ConsumerStatefulWidget {

  @override
  ConsumerState createState() => _SearchState();
}

class _SearchState extends ConsumerState<Search> {

FocusNode focusNode = FocusNode();

@override
void initState() {
// TODO: implement initState
super.initState();

// focusNode = FocusNode();

// focusNode?.requestFocus()
}

@override
void dispose() {
  // TODO: implement dispose
  focusNode.dispose();

  super.dispose();

}

@override
Widget build(BuildContext context) {

WidgetsBinding.instance.addPostFrameCallback((_) => () => focusNode.requestFocus());

Size size = MediaQuery.of(context).size;

focusNode.requestFocus();

return Scaffold(
  appBar: AppBar(
    title: Container(
      child: Hero(
        tag:'searchBar',
        flightShuttleBuilder: ((flightContext, animation, flightDirection, fromHeroContext, toHeroContext){

        animation.addStatusListener((status) {
          if (status == AnimationStatus.completed) {
           focusNode.requestFocus();
          }
        });

          return toHeroContext.widget;
        }),
        child: Material(
          type: MaterialType.transparency,
          child: SizedBox(
            height:size.height * 0.05,
            child: TextField(
              focusNode: focusNode,
              decoration: InputDecoration(
                prefixIcon: const Icon(Icons.search, size: 25.0,),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(50.0),
                  borderSide: const BorderSide(
                    width: 0,
                    style: BorderStyle.none,
                  ),
                ),
                filled: true,
                hintStyle: TextStyle(color: Colors.grey[800]),
                hintText: 'Search a word',
                fillColor: Colors.white,
                // isDense: true,
                contentPadding: EdgeInsets.all(0.0),
              ),
            ),
          ),
        ),
      ),
    ),
  ),
  body: Container(),
);
 }
 }

A: My first advice is avoid doing calculations or calling methods in the build method, this will cause to be called each time the widget tree needs to refresh (unless you use Flutter Hooks which holds the state of what is currently doing, but thats a different story)
class Search extends ConsumerStatefulWidget {
  @override
  ConsumerState createState() => _SearchState();
}

class _SearchState extends ConsumerState<Search> {
  FocusNode focusNode = FocusNode();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    // focusNode = FocusNode();

    // focusNode?.requestFocus()
  }

  @override
  void dispose() {
    // TODO: implement dispose
    focusNode.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    /// no Widget WidgetsBinding.instance.addPostFrameCallback nor requestFocus call here
    Size size = MediaQuery.of(context).size;

    return Scaffold(
      appBar: AppBar(
        title: Container(
          child: Hero(
            tag: 'searchBar',
            flightShuttleBuilder: ((flightContext, animation, flightDirection,
                fromHeroContext, toHeroContext) {
              /// Don't try to add a Listener here, use a StatefulWidget that uses that logic in its initState
              return _FocustWidget(
                animation: animation,
                child: toHeroContext.widget,
                focusNode: focusNode,
              );
            }),
            child: Material(
              type: MaterialType.transparency,
              child: SizedBox(
                height: size.height * 0.05,
                child: TextField(
                  focusNode: focusNode,
                  decoration: InputDecoration(
                    prefixIcon: const Icon(
                      Icons.search,
                      size: 25.0,
                    ),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(50.0),
                      borderSide: const BorderSide(
                        width: 0,
                        style: BorderStyle.none,
                      ),
                    ),
                    filled: true,
                    hintStyle: TextStyle(color: Colors.grey[800]),
                    hintText: 'Search a word',
                    fillColor: Colors.white,
                    // isDense: true,
                    contentPadding: EdgeInsets.all(0.0),
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
      body: Container(),
    );
  }
}

class _FocustWidget extends StatefulWidget {
  final Widget child;
  final Animation<double> animation;
  final FocusNode focusNode;

  const _FocustWidget({
    Key? key,
    required this.focusNode,
    required this.animation,
    required this.child,
  }) : super(key: key);

  @override
  State<_FocustWidget> createState() => __FocustWidgetState();
}

class __FocustWidgetState extends State<_FocustWidget> {
  @override
  void initState() {
    super.initState();
    widget.animation.addStatusListener(_status); ///Check for the animation state
  }

  void _status(AnimationStatus status) {
    if (status == AnimationStatus.completed) {
      Future.microtask(() => mounted ? widget.focusNode.requestFocus() : null);
    }
  }

  @override
  void dispose() {
    widget.animation.removeStatusListener(_status); /// dispose the listener
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => widget.child;
}

Now I talked about hooks because I see you using Consumer so I believe you use riverpod (and therefore maybe you are familiar with hooks if you saw hooks_riverpod package). If you're still grasping the concept of riverpod without hook then this is it, else you could try using hooks to reduce the statefulWidget:
class Search extends HookConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final focusNode = useFocusNode(); /// created once with hook
    Size size = MediaQuery.of(context).size;

    return Scaffold(
      appBar: AppBar(
        title: Container(
          child: Hero(
            tag: 'searchBar',
            flightShuttleBuilder: ((flightContext, animation, flightDirection,
                fromHeroContext, toHeroContext) {
              return HookBuilder(
                builder: (context) {
                  final mounted = useIsMounted();
                  useEffect(() {
                    if (animation.status == AnimationStatus.completed) {
                      Future.microtask(
                        () => mounted() ? focusNode.requestFocus() : null,
                      );
                      return null;
                    }

                    void _status(AnimationStatus status) {
                      if (status == AnimationStatus.completed) {
                        Future.microtask(
                          () => mounted() ? focusNode.requestFocus() : null,
                        );
                      }
                    }

                    animation.addStatusListener(_status);

                    return () => animation.removeStatusListener(_status);
                  }, const []);
                  return toHeroContext.widget;
                },
              );
            }),
            child: Material(
              type: MaterialType.transparency,
              child: SizedBox(
                height: size.height * 0.05,
                child: TextField(
                  focusNode: focusNode,
                  decoration: InputDecoration(
                    prefixIcon: const Icon(
                      Icons.search,
                      size: 25.0,
                    ),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(50.0),
                      borderSide: const BorderSide(
                        width: 0,
                        style: BorderStyle.none,
                      ),
                    ),
                    filled: true,
                    hintStyle: TextStyle(color: Colors.grey[800]),
                    hintText: 'Search a word',
                    fillColor: Colors.white,
                    // isDense: true,
                    contentPadding: EdgeInsets.all(0.0),
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
      body: Container(),
    );
  }
}


text:
Q: Database for online shop with many products How do I create a database which contains many different products of various categories?
They also have different attributes.
My idea is to create 3 tables:
Product (pid)
Category (cid, parentcategory)
Product_category (pid, cid)
I think this manages the categories, but how do i store the attributes efficiently?

A: If your products will not be in two or more categories, you don't need conenction table.
According to the comment section, I have a suggestion for you:
If and only if you decide to store category and sub_category then you have to implement it like this:
category(id, name)
sub_category(id, name, category_id)
product(id, name, sub_category_id)
With this method every products are aware of what is their subcategory. If we have the subcategory, then we are also able to determine the (main) category of every product.
I hope I could help you. Designing the scheme of the database is a very important step of developing an application.


text:
Q: XStream double underline handling (Java) I wanted to serialize a java class to XML with XStream.
I needed to generated an XML element with one underline (canal_operateur), but XStream adds a second underline in the xml element name.
So how to keep only one underline ?
With the default configuration for this class :
public class Document implements Serializable {
    private String typedoc;
    private Fichier fichier;
    private String canalOperateur;
    //xstream.aliasField("canal_operateur", Document.class, "canalOperateur");
    /*
    ** setter and getter
    */
}

XStream doubles the underline :
<document>
    <canal__operateur>canal</canal__operateur>
    <commentaire>commentaire</commentaire>
    <metadonnees/>
</document>

A: According to here:

XStream maps Java class names and field names to XML tags or
  attributes. Unfortunately this mapping cannot be 1:1, since some
  characters used for identifiers in Java are invalid in XML names.
  Therefore XStream uses an XmlFriendlyNameCoder to replace these
  characters with a replacement. By default this NameCoder uses an
  underscore as escape character and has therefore to escape the
  underscore itself also. You may provide a different configured
  instance of the XmlFriendlyNameCoder or a complete different
  implementation like the NoNameCoder to prevent name coding at all.
  However it is your responsibility then to ensure, that the resulting
  names are valid for XML.


text:
Q: long running process for worker processes to respond to rabbitmq messages My web application is writing messages to rabbitmq.  Example, a user wants to export their data, so I write this message to the queue.  The web application is not java based.
Now I am looking for suggestions on how to create an environment for responding to these messages i.e. worker processes
I want to be able to have multiple worker processes responding to new messages in the queue, and be able to tweak the # of worker processes to respond to demand etc.
Are there any java frameworks that are long running processes?

A: You could create a grid of working processes to respond to requests available in that rabbitmq. As by frameworks for handling this you could use GridGain, an Open Source Grid/Cloud infrastructure that would allow you to distribute the requests to a number of # worker processes. Another similar option is Condor. Both resolve similar issues but GridGain is more Java oriented.