text:
Q: Orbital dimension of the action of $S_n$ on 2-subsets I have a question on a proof in a paper on the orbital dimension of a permutation group.
Let $G \le S^\Omega$ be a permutation group. A base for $G$ is a subset $\Sigma \subseteq \Omega$ for which the pointwise stabilizer $G_{(\Sigma)}$ is the identity.  The base size of $G$, denoted $b(G)$, is the smallest size of a base for $G$.
Suppose $G$ has orbitals $\{R_1,\ldots,R_t\}$ (these are the $G$-orbits on $\Omega \times \Omega$).   Define the color $C(x,y)$ of an ordered pair $(x,y) \in \Omega \times \Omega$ to be the value of $i$ for which $(x,y) \in R_i$.  A resolving set for $G$ is a subset $S = \{x_1,\ldots,x_k\} \subseteq \Omega$ such that for any $y,z \in \Omega, y \ne z$, we have $C(y,x_i) \ne C(z,x_i)$ for some $x_i \in S$.  The orbital dimension of $G$, denoted $\mu(G)$, is defined to be the smallest size of a resolving set for $G$.  It can be shown that every resolving set for $G$ is a base for $G$, whence $b(G) \le \mu(G)$.
Let $G$ be the action of $S_n$ on the 2-subsets of $\{1,\ldots,n\}$, and henceforth assume also that $n \equiv 1 \pmod 3$.
In Proposition 2.24 of [Bailey and Cameron, "Base size, metric dimension and other invariants of groups and graphs", preprint], it is shown that $b(G) = \frac{2}{3}(n-1)$.  In Theorem 3.32, it is shown that a particular set $S$ of size $b(G)$ is not a resolving set for $G$, but augmenting this set $S$ by adding one more element to it gives a resolving set for $G$.  From what I understand, this implies only that $b(G) \le \mu(G) \le b(G)+1$, whereas the authors conclude that $\mu(G)=b(G)+1$.  How is this equality proved?  I can see that $\mu(G)$ is one of $b(G)$ or $b(G)+1$.  But to prove $\mu(G)=b(G)+1$, we need to show that any set $S$ of size $b(G)$ is not a resolving set for $G$.
I think the proof of Theorem 3.32 implicitly uses the fact that a base for $G$ that has cardinality $b(G)$ is unique (up to graph isomorphism).  Using this fact and the fact that a resolving set for $G$ is a base for $G$, it follows that if $G$ had a resolving set $S$ of size $b(G)$, then this set $S$ would have to be the unique base for $G$, which can be shown to not be a resolving set, a contradiction.  Uniqueness of minimum bases would thus establish that $\mu(G)=b(G)+1$. Is this what was assumed implicitly in the proof?


text:
Q: Integrate $1/(x^5+1) $from $0$ to $\infty$? How can I calculate the integral $\displaystyle{\int_{0}^{\infty} \frac{1}{x^5+1} dx}$?

A: Consider the contour integral of the integrand from 0 to R on the real axis, then a circle segment of radius R from R to R exp(2 pi i/5) and then along a straight line back from there to 0. The integral along this line is proportional to the one you want to evaluate. There is one pole at z =  exp(pi i/5) located inside the contour, the residue is trivial to compute.

A: The change of variable $\frac{1}{1+x^{5}}=u$ gives $dx=-\frac{u^{-1-\frac{1}{5}}(1-u)^{-\frac{4}{5}}}{5}du$
Hence our integral reduces to $$\frac{1}{5}\int_{0}^{1}{u^{\frac{4}{5}-1}(1-u)^{\frac{1}{5}-1}du}=\frac{1}{5}\beta(1-\frac{1}{5},\frac{1}{5})=\frac{1}{5}\Gamma(1-\frac{1}{5})\Gamma(\frac{1}{5})=\frac{1}{5}\frac{\pi}{\sin(\frac{\pi}{5})}$$ we can actually simplify things a bit more by considering the following identity, deduced by De'Moivres formula $$\sin(5x)=16\sin^{5}(x)-20\sin^{3}(x)+5\sin(x)$$ pluggin in $x=\frac{\pi}{5}$ combined with the fact that $\sin(\frac{\pi}{5})>0$ We get $$16\sin^{4}(\frac{\pi}{5})-20\sin^{2}(\frac{\pi}{5})+5=0$$ which we can begin by solving for $\sin^{2}(\frac{\pi}{5})$ and then taking the positive root. We will end up with $\sin(\frac{\pi}{5})=\sqrt{5-\sqrt{5}}$ hence your integral will finally evaluate at $$\frac{1}{5}\frac{\pi}{\sqrt{5-\sqrt{5}}}$$

A: In this answer, it is shown, using contour integration, that
$$
\frac{\pi}{m}\csc\left(\pi\frac{n+1}{m}\right)=\int_0^\infty\frac{x^n}{1+x^m}\,\mathrm{d}x
$$
Plug in $n=0$ and $m=5$ to get
$$
\int_0^\infty\frac1{1+x^5}\,\mathrm{d}x=\frac\pi5\csc\left(\frac\pi5\right)
$$

A: $\newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack}
 \newcommand{\ceil}[1]{\,\left\lceil\, #1 \,\right\rceil\,}
 \newcommand{\dd}{{\rm d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}
 \newcommand{\fermi}{\,{\rm f}}
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{{\rm i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\pars}[1]{\left(\, #1 \,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,}
 \newcommand{\sech}{\,{\rm sech}}
 \newcommand{\sgn}{\,{\rm sgn}}
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
\begin{align}
\overbrace{\int_{0}^{\infty}{\dd x \over x^{5} + 1}}
^{\ds{\mbox{Set}\ x^{5} \equiv t}\ \imp\ x = t^{1/5}}&=
\color{#00f}{{1 \over 5}\int_{0}^{\infty}{t^{-4/5} \over t + 1}\,\dd t}
={1 \over 5}\,2\pi\ic\expo{-4\pi\ic/5}
-{1 \over 5}\int_{\infty}^{0}{t^{-4/5}\expo{-8\pi\ic/5} \over t^{5} + 1}\,\dd t
\\[3mm]&={1 \over 5}\,2\pi\ic\expo{-4\pi\ic/5}
+ \expo{-8\pi\ic/5}\,
\color{#00f}{{1 \over 5}\int_{0}^{\infty}{t^{-4/5} \over t^{5} + 1}\,\dd t}
\end{align}

\begin{align}
\int_{0}^{\infty}{\dd x \over x^{5} + 1}&
=\color{#00f}{{1 \over 5}\int_{0}^{\infty}{t^{-4/5} \over t^{5} + 1}\,\dd t}
={1 \over 5}\,2\pi\ic\expo{-4\pi\ic/5}\,{1 \over 1 - \expo{-8\pi\ic/5}}
={\pi \over 5}\,{2\ic \over \expo{4\pi\ic/5} - \expo{-4\pi\ic/5}}
\\[3mm]&={\pi \over 5}\,{2\ic \over 2\ic\sin\pars{4\pi/5}}
\end{align}

$$
\color{#66f}{\large\int_{0}^{\infty}{\dd x \over x^{5} + 1}}
={\pi \over 5}\,\csc\pars{4\pi \over 5}
=\color{#66f}{\large{\root{50 + 10\root{5}} \over 25}\,\pi}\approx {\tt 1.0690}
$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android - SupportMapFragment with GoogleMaps API 2.0 giving IllegalArgumentException I am trying to use the latest Map API 2.0 provided for Android. I am using the Support Library as I want to support Android 2.2. Following is my code:
Main Activity class
public class MainActivity extends FragmentActivity {

    public FragmentManager fManager ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fManager = getSupportFragmentManager();
        Button showMapButton = (Button) findViewById(R.id.showMapButton);
        showMapButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                loadMapFragment();
            }
        });
    }

    private void loadMapFragment() {
        MapPageFragment plotterFragment = new MapPageFragment();
        FragmentTransaction ft = fManager.beginTransaction();
        ft.replace(R.id.allFragmentsFrameLayout, plotterFragment);
        ft.addToBackStack(null);
        ft.commit();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

Main Activity layout file
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/showMapButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Show Map"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:layout_marginTop="30dp"
        android:layout_alignParentTop="true" />

    <FrameLayout
        android:id="@+id/allFragmentsFrameLayout"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentTop="true">
        <!-- Put fragments dynamically -->
    </FrameLayout>

</RelativeLayout>

Map Fragment Class
public class MapPageFragment extends SupportMapFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                         Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        return inflater.inflate(R.layout.map_fragment_layout, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }
}

Map Fragment Layout
<?xml version="1.0" encoding="utf-8"?>
<fragment
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    android:id="@+id/map"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    class="com.google.android.gms.maps.SupportMapFragment"
    map:uiCompass="true"
    map:mapType= "normal"
    map:uiRotateGestures="true"
    map:uiScrollGestures="true"
    map:uiTiltGestures="true"
    map:uiZoomControls="true"
    map:uiZoomGestures="true" />

Android Manifest File
<?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mapfragmentexample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <permission
        android:name="com.plotter.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>
    <uses-permission android:name="com.plotter.permission.MAPS_RECEIVE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyA5FtIeLQ1gGUihZIZPQVi3Yz_0l4NG9PY"/>
    </application>

</manifest>

Everything is working fine for the first time. i.e. When I click on the Show Map button the map fragment gets loaded and displays the map. When I press back button, the map fragment is unloaded and I can see the Show Map button again.
I face an issue when I press the Show Map button again. I get the following error:
FATAL EXCEPTION: main
android.view.InflateException: Binary XML file line #2: Error inflating class fragment
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:699)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:468)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
    at com.mapfragmentexample.MapPageFragment.onCreateView(MapPageFragment.java:17)
    at android.support.v4.app.Fragment.performCreateView(Fragment.java:1460)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:911)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
    at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:429)
    at android.os.Handler.handleCallback(Handler.java:605)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4503)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
    at dalvik.system.NativeStart.main(Native Method)

Caused by: java.lang.IllegalArgumentException: Binary XML file line #2:
       Duplicate id 0x7f040006, tag null, or parent id 0x0 with another fragment
       for com.google.android.gms.maps.SupportMapFragment
    at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:285)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:671)
    ... 18 more

I am not getting where I am getting wrong or missing anything.

A: You need to use getChildFragmentManager() to add SupportMapFragment not not through xml.
For "why", see official documentation: http://developer.android.com/about/versions/android-4.2.html#NestedFragments
Take a look at my answer here: https://stackoverflow.com/a/15512285/2183804

A: You can fix this, if you delete all nested fragments in onDestroyView(). Don't know if it is a proper solution.
public void onDestroyView() {
   super.onDestroyView();
   Fragment fragment = (getFragmentManager().findFragmentById(R.id.map));
   FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
   ft.remove(fragment);
   ft.commit();
}

And inflating them as usual in onCreateView()
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.map, container, false);
}

A: You cannot inflate a layout into a fragment when that layout includes a fragment. Nested fragments are only supported when added to a fragment dynamically. More detail here!

A: Used this solution (similar to others):
public void onDestroyView() {

    FragmentManager fm = getActivity().getSupportFragmentManager();
    Fragment fragment = (fm.findFragmentById(R.id.map));

    if (fragment.isResumed()) {
        FragmentTransaction ft = fm.beginTransaction();
        ft.remove(fragment);
        ft.commit();
    }
    super.onDestroyView();
}

I had problems before using the if (fragment.isResumed).

A:

I was facing the same issue in JakeWhartonViewPagerIndicatore along with SherlockFragments. Here is sample TestFragment with solved issue, thanks to Natalia for providing above solution. Your fragment may be a little different from mine.
Reference: Making ActionBarSherlock and ViewPagerIndicator play nice

Good Luck..!!

package com.example.vpiabstest;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragment;

public class TestFragment extends SherlockFragment {
    private String mContent = "???";
    private String text;
    private static final String KEY_TAB_NUM = "key.tab.num";

    public static TestFragment newInstance(String text) {
        TestFragment fragment = new TestFragment();

        // Supply num input as an argument.
        Bundle args = new Bundle();
        args.putString(KEY_TAB_NUM, text);
        fragment.setArguments(args);

        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        text = getString(R.string.tab_page_num) + mContent;

        View view = null;

        if(text.contains("2")) {
            view = inflater.inflate(R.layout.pinpoints_list, null);
        } else if(text.contains("1")) {
            view = inflater.inflate(R.layout.main_fragment_activity, null);
        } else {
            view = inflater.inflate(R.layout.activity_main, null);
            ((TextView)view.findViewById(R.id.text)).setText(text);
        }

        return view;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContent =  getArguments() != null ? getArguments().getString(KEY_TAB_NUM) : "???";
    }

    public void onDestroyView() {
        super.onDestroyView();

        // Your Programing skills goes here

        if(text == null || !text.contains("1")) {
            return;
        }

        // Do Not Miss this
        try {
            Fragment fragment = (getFragmentManager().findFragmentById(R.id.map_fragment));
            FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
            ft.remove(fragment);
            ft.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

A: Use dialog.SetContentView() method in your activity's onCreate() cause when we tring to load.
Dialog again it loads only dialog not the whole activity life cycle and leads it to exception of Duplicate id.
Try it.

A: Try this
Maps fragment layout
<?xml version="1.0" encoding="utf-8"?>
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
map:uiCompass="true"
map:mapType= "normal"
map:uiRotateGestures="true"
map:uiScrollGestures="true"
map:uiTiltGestures="true"
map:uiZoomControls="true"
map:uiZoomGestures="true"
tools:context="the.package.name.of.mappagefragment.MapPageFragment" />

Map fragment class
public class MapPageFragment extends SupportMapFragment
{

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    View rootView = super.onCreateView(inflater, container, savedInstanceState);
    if (rootView == null)
    {
        rootView = inflater.inflate(R.layout.map_fragment_layout, container, false);
    }
    return rootView;
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
    super.onViewCreated(view, savedInstanceState);
}
}

A: I used Natalia response but at times broke the application.
Use this one and it worked perfectly without breaking.
@Override
public void onDestroyView() {

  try{
    FragmentTransaction transaction = getSupportFragmentManager()
            .beginTransaction();

    transaction.remove(nestedFragment);

    transaction.commit();
  }catch(Exception e){
  }

    super.onDestroyView();
}

https://stackoverflow.com/a/7953801/3364157

A: Fragment fragment = (getChildFragmentManager().findFragmentById(R.id.mapview));
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();

Use this saves the day.

A: Use intent flags:
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

when calling main activity.

A: I had the same problem. Try adding ...
android:name="com.mapfragmentexample.MapPageFragment"

... to fragment in the layout file!


text:
Q: Control spacing within I'm trying to build a small listing of terms with definitions. Below is a MWE. I want the items after the \indents to line up.
\documentclass{article}

\begin{document}

FOV \indent Field of View

A \indent  Half-Angle of FOV (subscripts apply)

\end{document}

Suggestions?

A: I think you are looking for a tabbing:
% arara: pdflatex

\documentclass{article}

\begin{document}
\begin{tabbing}
    \hspace{1cm} \=  \kill
    FOV \> Field of View \\
    A \>  Half-Angle of FOV (subscripts apply)
 \end{tabbing}
\end{document}

A: You could use the eqlist package:
\documentclass{article}
\usepackage{eqlist}

\begin{document}
\begin{eqlist}[\eqlistinit \labelsep 2em]
    \item[FOV] Field of View
    \item[A] Half-Angle of FOV (subscripts apply)
    \item[LONGER] a slightly longer item
\end{eqlist}
\end{document}

It automatically aligns all definitions according to the longest term that you want to define. Additionally, use the value behind \labelsep to set the distance (the "gap") between the end of the longest term and the begin of its definition.
There are a lot of other options which you can find in the documentation of the package.


text:
Q: Is there an effective way to monitor the load on each switch? We have about 200 IP phones in our building and I realize we got more complaint about the phone quality after we switched our internet from 50Mbps to 200Mbps Up/Down.
I know there's a possibility that the switch gets overloaded easier than before cause obviously everyone is using more bandwidth. And most of our switches are still 100Base-T.
So is there a way I can monitoring the load on the switch or get a notice if the switches gets overloaded?
We're using Dell PowerConnect 3548 mostly.
Thanks.

A: You can monitor the statistics of every single port on the switch using SNMP. This will give you your individual throughput on each port, tally them all up at any given time and that gives you your total traffic.
If that traffic is higher than your switches backplane, then your switch is the bottleneck.
You should also monitor your uplink ports. If they are saturated, then they are the problem and you need faster or more uplinks.
If neither, then it's something else. If your computers are piggybacking off a built-in switch on the phones, then perhaps the computers are saturating the switch in the phones. You should also be able to monitor these via SNMP as well.
Ideally you should have your phones and your computers on seperate vlans. Then you can put QoS on your outbound internet connection to give priority to the phone vlans to ensure that theres always enough outbound bandwidth to satisfy the phone calls.


text:
Q: How do I stop ASP.net forms authentication / session from renewing in setInterval ajax web service call? I have a control that i've written that has a javascript component and a web service component.  The problem i'm having is that the javascript is set to do:
setInterval(this._checkAlertsHandler, this._messageCheckInterval * 1000);

This calls a function which makes a webservice call like so:
Alert.SiteAlertService.GetAlerts(this._receivedAlertsHandler, this._errorReceivedAlertsHandler);

So this is using the web service javascript proxy methods to access the web service.  The issue is that our application has forms authentication and a timeout value, so if the user is idle for too long it will log them out.
My webservice call apparently sends the cookie which includes the session and the forms authentication key to the web service.  The asp.net webservice then automatically renews the session AND the forms authentication. Everytime the javascript hits the web service it basically keeps the user alive.  I do not want this behavior, this should just circumvent that, so that even though this js is hitting the web service to check for new messages, if the user hasn't done a postback on our application (and is effectively idle) it will still log them out.  This isn't happening :(
What i would like to happen is this interval call to the web service does not renew any authentication (the session renewal i can get around by using an application level variable with dictionary key/value for the users session id, so i dont have to use any session level variables).
How do i do this / change my web service / or control to work like the way i want it?

A: I'm working on different approaches to this as well.  One way I'm doing it is by adding this to the Ajax service endpoint:
// Hide the cookie so this call doesn't extend the user's ticket
HttpContext ctx = HttpContext.Current;
ctx.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);

This way you can negate an Auth Ticket renewal, sine the updated cookie will never make it back to the client.
If you have multiple Ajax endpoints that you want to exclude, a module can be implemented to identify those endpoints and include the code to remove the cookie from the response.

A: @RyanW provided the answer I needed so here's my implementation for MVC using an attribute just to keep things DRY.
using System.Web.Mvc;
using System.Web.Security;

namespace Your.Web.Attributes
{
    public class RemoveAuthCookieAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            filterContext.HttpContext.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
            base.OnActionExecuted(filterContext);
        }
    }
}

Implementation:
[RemoveAuthCookie]
public ActionResult PollMe()
{
    return View();
}

A: You could exclude your webservice from forms authentication:
<location path="yourwebservice.asmx">
    <system.web>
        <authorization>
            <allow users="?"/>
        <authorization>
    </system.web>
</location>

But you probably need the information about the user, so you could configure the webservice to use forms authentication, but deactivate SlidingExpiration:
<location path="yourwebservice.asmx">
    <system.web>
        <authentication mode="Forms">
            <forms slidingExpiration="false"></forms>
        </authentication>
    </system.web>
</location>

Be sure to test what happens if the forms cookie is expired. Maybe you'll have to redefine the loginurl, too.

A: Could you put your webservice asmx file into its own separate project/solution/application?
That way it should use a different session id to your main application.


text:
Q: How to show an element and hide when click on another I have a series of div elements which i trigger with the code below.
$(".course_id").on("click", function(){
     var id = $(this).data("id");
     $("div#lessons_by_course_" + id).removeClass("hidden");
});

The divs have an id called lessons_by_course + id e.g

the id number is parsed dynamically using ruby on rails .each loop.
what i want is when i click on a div i want it to show and when i click on another div,i want jquery to hide the last one that was shown and show the one i clicked next.
Note that .course_id is a class for many elements so,each time i click on a certain one, a different div pops up because the id is different each time.

A: You could cache the id of the last shown element in a global variable:
var id;

Then in your loop:
$(".course_id").on("click", function(){
    if(id) {
        $("div#lessons_by_course_" + id).addClass("hidden");
    }
    id = $(this).id;
    $(this).removeClass("hidden");
});


text:
Q: DynamicReports remove row if column is null I am a little bit stuck with such an easy problem. I am using DynamicReports and I want to hide whole row if column value is null. As I know, DynamicReports is based on JasperReports and it's possible there to do that by checking TextField's option "Remove line when blank". How can I do that in Dynamic?
Components, which I use:
TextColumnBuilder, ColumnGroupBuilder, JasperReportBuilder

I want to hide whole row if any of my TextColumns would be null.

A: OK, after some thoughts, I found that this problem could be resolved in other way.
We gonna use column, group etc property setPrintWhenExpression(DRIExpression expression)
1.  Create class, which will handle, print or not to print the row. Dynamic has the abstract class for doing this:
    public class ShowExpressionDynamicReports extends AbstractSimpleExpression<Boolean> {

    private String fieldName;

    public ShowExpressionDynamicReports(String fieldName) {
        this.fieldName = fieldName;
    }

    @Override
    public Boolean evaluate(net.sf.dynamicreports.report.definition.ReportParameters reportParameters) {
        return reportParameters.getValue(fieldName) != null;
      }
    }

You should extend AbstractSimpleExpression in order to pass it as parameter to methods which are listed below.
So, the column value is printed if evaluate(ReportParameters rp) returns true.
I've also added field fieldName which allows me to print (or not) column due to other's column state.
2. Add property to your
column:
setPrintWhenExpression(DRIExpression expression)
group:
.setPrintSubtotalsWhenExpression(DRIExpression expression)
or
setFooterPrintWhenExpression(DRIExpression expression)
or
setHeaderPrintWhenExpression(DRIExpression expression)
Depends on what you want to hide.
Example:
We have 2 columns in our report: Product and ProductCount columns. I would like to hide Product column if ProductCount is null (we have no information for this Product).
So, to do that i will add property PrintWhenExpression to Product column
TextColumnBuilder<String> productColumn = col.column("Product", "Product", type.stringType())
.setPrintWhenExpression(new ShowExpressionDynamicReports("ProductCount"));


text:
Q: Store files in database as base64 encoded string I use following model to store files in database in django app:
class Data(BaseModel):
    _data = models.TextField(
            db_column='data',
            blank=True)

    def set_data(self, data):
        self._data = base64.encodestring(data)

    def get_data(self):
        return base64.decodestring(self._data)
    item = models.OneToOneField(Item)
    data = property(get_data, set_data)

I can save such objects easly without any issue :
form = ItemForm(request.POST)
if form.is_valid():
    try:
        file = request.FILES['file']
    except MultiValueDictKeyError:
        errors = form._errors.setdefault(forms.forms.NON_FIELD_ERRORS, forms.util.ErrorList())
        errors.append("select file")
    else:
        item = form.save()
        item.filename = file.name
        item.save()

        blob = Data(item=item)
        blob.data = file.read()
        blob.save()

However, I am not able to read such encoded data. I tried to save such file to filesystem with:
        #save test
        new_filename = 'new_%s'%(item.filename,)
        a = open(new_filename,'w')
        a.write(blob.data)
        a.close()

(I used an image as test file, when ran above code, I cannot open such image, its incorrect).
What did I wrong?


text:
Q: Cannot get Scanner to See File I cannot understand why I can't get scanner to read my .txt file. In the end I resorted to just storing the data as a String in my program. But I would still like to know why Scanner is not seeing this file.
Scanner scan = new Scanner(new File("Test.txt"));

I've also tried:
Scanner scan = new Scanner(new File("C:/Users/myusername/Desktop/Test.txt"));

Both result in FileNotFoundException being thrown.
The text file is located at the same directory where the class files and the source files are.
Does anyone know what's wrong??
Ok well this really sucks. I just don't know why this is happening. I know for a fact the file exists.
System.out.println(System.getProperty("user.dir"));

shows that the directory I'm in is the correct one.
Anyone else have any thoughts?

A: Check whether the file you are trying to access is read-only or not. If it is read-only then uncheck it. Or you can try this also:
FileInputStream fis=new FileInputStream(new File("C:/Users/myusername/Desktop/Test.txt"));
Scanner scan=new Scanner(fis);

A: Strip down the problem by omitting the Scanner and start with the file only:
File myFile = new File("Test.txt");
myFile.exists();
myFile.canRead();
...

Then continue with analyzing the path of the file:
myFile().getCanonicalPath();
...

The scanner wouldn't have any problem if the java process would be able to access the file.
If that does not lead anywhere, we'll need more infos: which version of java? How do you start the java process?

A: Ok well I fixed it. It seems Torgeist was right. It does help to strip down the problem. It was very useful to use exists() and canRead() since these were returning false.  Somewhere there must have been something wrong in the exact file path I was entering even though I copy and pasted. Weird...only other possible explanation is that something was blocking access to the desktop but that seems pretty unlikely.
The use of escaped backslashes or forward slashes made no difference.
File file = new File("C:/Users/UserName/Documents/Testing.txt");

vs.
File file = new File("C:\\Users\\OCB\\Documents\\Testing.txt");

Both worked.


text:
Q: Angular material : override css table inside a mat-menu I'm working on an application in Angular 7 and Angular Material cdk 6. It's my first time with Angular Material.
I have to override the css of my columns. None of my tries have worked.
* HTML *
<mat-menu #myMenu>
<ng-template myContentMenu>

        <ng-container matColumnDef="date">
            Date
            {{ item.date }}
        </ng-container>

</ng-template>

I don't know how to put padding, I've tried encapsulation: ViewEncapsulation.None in the .ts file and :
* CSS *
:host { /** With and without host */
   th.mat-column-date, td.mat-column-date {
      padding-left: 20px; /** With and without !important */
   }

   ::ng-deep mat-menu th.mat-column-date,
   ::ng-deep mat-menu td.mat-column-date {
     padding-left: 20px !important;
   }}

I don't know how to proceed. Does somebody have an idea ?

A: Why dont you just add your own class to the desired element. For example, I have added "col-padding" class to the th element.
HTML
Date
CSS
.col-padding {
    padding-left: 20px;
}


text:
Q: How to avoid the #DIV/0! while adding several values ok so I've this lil formula in excel
 =(J5/(G5*D5))+(J9/(G9*D9))+(J13/(G13*D13))+(J17/(G17*D17))+(J21/(G21*D21))
  +(J25/(G25*D25))+(J29/(G29*D29))+(J33/(G33*D33))+(J37/(G37*D37))
  +(J41/(G41*D41))

nothing hard but some of the denominators for the divsions will evalute to 0, for example...
= (9/3) + (5/4) + (2/0) + (0/4) + (2/3) + (5/1)
and I will end up with a #DIV/0! error. Now my question is, how do I have the formula avoid the parts where it divides by 0 and still return the rest of the sum to me.

A: You could add checks for zero:
=(J5/(IF(G5*D5=0,1,G5*D5))+...

This will check if G5*D5 evaluates to 0. If that's the case, the denominator becomes 1 which is a valid division by one.

A: Use the IFERROR function:
=IFERROR((J5/(G5*D5)),0)+...

Surround each part by this, if an error comes from it, it results in a 0 instead from the section enclosed within


text:
Q: My program is executing as expected but in the end I am an extra line called a segmentation fault near the output. Could someone see to it? Am not getting what is wrong with this
#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
int main()
{  // prints the initials of a name
    printf("Enter the name: ");
    string s = get_string();

    int n= 0;

    // prints the first letter of the name
    printf ("%c", toupper(s[0]));

    // rememnber the index of a string starts from 0 and it is counted till \0 and as \0 is the final one therefore it looks like it is counting from 1
    // but is actually starting at 0. The code accounts for that

    while(s[n] != '\0') // while we have not reached end of string
    {
        while(s[n] != ' ')
         {
            n = n +1 ;
         }

    printf("%c", toupper(s[n+1])); // prints the letter after the space in the uppercase order
    n = n+1;  // this sets the n at the letter just after the space

    }

   return 0;

}

input :
Rock Hilary

Expected output :
RH

What i am getting :
RHSegmentation fault

How do I fix this?

A: Problem is caused becouse you are touching memory which doesnt belong to you (undefined behavior). Usually SIGSEG is thrown, same as in your case.
Problem occurs here
while(s[n] != ' ')
{
    n = n +1 ;
}

Where you are going behind string null terminator, just simply check if you reached string end, and if you did so, get out of loop.
while(s[n] != ' ' && s[n])
{
    n = n +1 ;
}
if (!s[n]) break;

Or a smarter way in C++, just an example
int main(void)
{
    std::string s = "Rock Hilary test";
    char prevChar = 0;

    if (s.length() < 1)
    {
        return 1;
    }

    printf ("%c", toupper(s[0]));

    for(char c : s)
    {
        if (prevChar == ' ')
        {
            printf("%c", toupper(c));
        }
        prevChar = c;
    }

    return 0;
}

output
RHT

A: You've tagged this as c++ but it seems like you're using entirely c.. So I'll answer this as if it's c.
A segmentation fault occurs when you access memory that you don't own. In this case you're trying to print a character outside of the bounds of your string. (e.g. your string is len characters long but you try to print character len+1).
In your case this is happening because of your inner while loop. Consider the string abcd\0.
For your outer while loop the case s[n] != '\0' succeeds because s[n] is 'a'. We move then to your inner while loop. For all letters in your string abcd\0 the case s[n] != ' ' succeeds because none of the characters are a space. This means that your loop will continue to search for a byte that evaluates as a space character past the end of your string. Once you finally find one, if you finally find one you will try to print the character, which inevitably means that your program will segfault because it doesn't own the memory it's trying to access. If your program didn't segfault it would actually continue to do this, because your algorithm doesn't actually guarantee that you'll ever find a stopping point. The only time it would was if you had a character and then the end of the string (e.g. a\0 or abc d\0).
You have some correct ideas, but to fix this you need to re-evaluate how you want your loop to execute. For the outer loop, you're using an incrementing variable to determine when to end your loop, consider changing this to a for loop:
for (int i = 0; s[i] != '\0'; ++i) {
}

This is essentially the same as before, just cleaner. The real issue is your inside loop. Consider what you want to do here. You could do this with an inner loop, but you'd need to recheck the same outer condition. Let's try and find a solution that doesn't do that. Starting with we don't want to print spaces. This is a fairly simple addition:
for (int i = 0; s[i] != '\0'; ++i)
{
    if (s[i] == ' ')
    {
        continue;
    }
}

Using continue will ensure that we'll restart the loop without running any of the rest of the code in the loop. We've also learend something interesting in this if: we've recently print a space. We can use this info if we track it so that we can print the next character (the initial). So let's add a boolean to watch for that.
int printedSpace = 0; // In c++ this would be `bool printedSpace = false;`
for (int i = 0; s[i] != '\0'; ++i)
{
    if (s[i] == ' ')
    {
        printedSpace = 1; // In c++ this would be `printedSpace = true;`
        continue;
    }
}

Now that we know we're skipping space characters and that the next iteration we'll remember that we've printed a space we can use this info to print the character. Also, just to back-check our previous condition, that we'll stop at the end of the string ('\0') we only read one character at a time, and then restart the loop (continue) so even if the last character in the string is ' ' (e.g. "abcd    \0") we won't try to execute the loop again. Anyways, adding the print:
int printedSpace = 0; // In c++ this would be `bool printedSpace = false;`
for (int i = 0; s[i] != '\0'; ++i)
{
    if (s[i] == ' ')
    {
        printedSpace = 1; // In c++ this would be `printedSpace = true;`
        continue;
    }
    else if (printedSpace)
    {
        printf("%c", toupper(s[i])); // Note that we're printing this character and not the next one
        printedSpace = 0; // In c++ this would be `printedSpace = false;`
    }
}

Two important things to notice here: first is that we reset printedSpace back to false so that we don't keep printing character, second is that if we have multiple spaces in a row it won't break anything, we'll just keep executing continue until we find a non-space character.  And frankly that's it. We've guaranteed that our count will stop at '\0' and we're printing characters after spaces. As a bonus, since you already assume that the first character in the string is an initial, if you set printedSpace to true before the beginning of the loop you will print the first character. This means you can remove the print above the loop. Just remember that you're assuming this, but I could break it by inputting '     Rock Hilary'. Of course you'll just print ' RH', since the rest of the algorithm will work as intended.


text:
Q: For AngularJS web app: webpages don't remember their last scroll positions when navigating back to them with the back button. Why? How to fix? When navigating around the developer's guide for AngularJS, I noticed that I do not go back to my last scroll position when navigating back to a page using the back button. Instead, I go right back to the top. Since the developer's guide is built with AngularJS, I am afraid that, when I build my own web application with AngularJS, it will annoy my users if they have this same experience. Why is this happening, and how can it be fixed? Do I need to use HTML5's history API somehow?
Go to the developer's guide and see this behavior yourself: http://docs.angularjs.org/guide/directive

A: If you want to fix it, I can think of an idea of keeping the track of every route scroll position in a map (in service or on a rootScope) - when you are leaving the page ($routeChangeStart listener) just save the scroll position together with route path.
And when coming to any page, you can check if a record in a map exists for the route path and scroll window to desired position on $routeChangeSuccess event

A: You should look into the Angular $anchorScroll service.
http://docs.angularjs.org/api/ng.$anchorScroll
It is for exactly your scenario!
The sample code pretty much speaks for itself.


text:
Q: (Reference Request) Desingularization of Fibrations I am interested in morphisms from a projective surface to a projective curve $p: X \longrightarrow C$ such that the fibres are singular curves on $X$. In the best case scenario, I'd like to replace $X$, say, birationally such that the fibres become smooth.
I don't expect something like this to always exist, but I'd like to read up on some results in this direction (e.g., what happens if $X$ is smooth, all the fibres are of a given genus and only certain singularities appear). I couldn't come up with much in the classical literature that I know, so any pointers are highly appreciated.

A: @Paul The most simple example of a fibration with smooth fibres, which degenerate to singular curves, is an elliptic fibration $p: X \longrightarrow C$. The general fibre of $p$ is a smooth elliptic curve. Kodaira has classified the finitely many types of singular fibres in elliptic fibrations (Barth, W.; Hulek, K.; Peters, Ch.; van de Ven, A.: Compact Complex Surfaces. Chap. V.7). The reference gives an example for each type by constructing an elliptic fibration over the unit disc with the singular fibre over the origin.
Each Enriques surface has an elliptic fibration $p: X \longrightarrow \mathbb P^1$ with exactly 2 singular fibres. Both have a nilpotent strucure $2F$, see Chap. VIII, 17.

A: For a modern treatment of families of curves you can try taking a look at Chapter 8.3 of Liu's book on Algebraic Geometry.
To get a good feeling for these matters I suggest working with complex algebraic surfaces over curves and trying out some examples. For instance, consider the projective family of curves $X_n := \{x^n+y^n= tz^n\}$ over $\mathbb A^1$, where $n>0$ is an integer.
Check that $X_1$ is a smooth family of projective lines.
Check that $X_2$ is a family of conics with a singular fibre over $t=0$.
More generally, check that $X_n$ is a family of degree $n$ curves in $\mathbb P^2$ which (only) degenerates at $t=0$. (In particular, the genus of the smooth fibres of $X_n$ is $(n-1)(n-2)/2$.)
You can show that $X_n\to \mathbb A^1$ is "minimal" in the sense that $X_n$ is a nonsingular variety and the fibres of $X_n \to \mathbb A^1$ contain no (-1)-curves (this is easy in this case as the fibres are irreducible).
But you can improve the situation after a base-change. In fact, you can always achieve "semi-stable fibres" after a finite ramified base-change. In the example $X_2$ above, you just need to adjoint a square root of $t$ to $\mathbb A^1$ (this corresponds to the finite ramified morphism $\mathbb A^1 \to \mathbb A^1$ sending $z$ to $z^2$).
In general, after adjoining $t^{1/n}$ to $\mathbb A^1 = $Spec $\mathbb C[t]$, you see that $X_n$ is isomorphic to $x^n+y^n = (z^\prime)^n$, where $z^\prime = ( t^{1/n}z)$. This is a smooth family of curves, so the situation is now nicer. (Not every semi-stable family of curves is smooth; in the examples above the family of curves $X_n\to \mathbb A^1$ has "potentially good reduction".)
If I may suggest another example: consider the family of projective curves over $\mathbb A^1$ given by $$y^2z = x(x-z)(x-tz).$$ What are its singular fibres? Are they semi-stable?


text:
Q: Angular FormControl valueChanges not working using mat-autocomplete I don't know why my formControl valueChanges is not firing when I try to filter employees data by typing into mat-autocomplete. Here is my component.ts and HTML respectively
myForm: FormGroup;

constructor(
  private formBuilder: FormBuilder,
) {
  this.prepareForm();
}

ngOnInit(): void {
  this.myForm.get('employeeId') ? .valueChanges.subscribe((x) => {
    console.log('Detect changes', x); // Not showing any console messages
  });

  this.filteredEmployees = this.packageBenefitForm.controls.employeeId.valueChanges.pipe(
    startWith(''),
    map((value) => this._filter(value))
  );
}

prepareForm(packageBenefit ? : PackageBenefit): void {
  this.myForm = this.formBuilder.group({
    employeeId: [
      packageBenefit ? packageBenefit ? .employeeId : '',
      Validators.compose([Validators.required]),
    ],
  });
}

and the HTML
<div class="mt-3">
  <mat-form-field class="example-full-width">
    <mat-label>Employee</mat-label>
    <input type="text" matInput formControlName="employeeId" [matAutocomplete]="auto" />
    <mat-autocomplete #auto="matAutocomplete" (optionSelected)="onSelectEmployee($event)"
      [displayWith]="displayFnEmployee">
      <mat-option *ngFor="let employee of filteredEmployees | async" [value]="employee">
        {{ employee.firstName }}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</div>

I've also tried to use this.packageBenefitForm.get('employeeId').valueChanges and still same problem.
Funny thing it's working in Stackblitz but not in my application. Here's the stackblitz demo app


text:
Q: Is it possible to display color in the Java Console? (Eclipse) I'm currently working on a program that checks Id's. It prints everything in the console. If the Id is valid then I want it to be green else red. Is there code to do this? I am currently working in Eclipse.
I am not looking for Eclipse plugins, but more so maybe a library I can include or Java specific code. This has nothing to do with ANSI Scala or whatever it is.


text:
Q: How to backup statistics in sql? Let's just say I have a table A with some data on it in SSMS. There are sub tables such as columns, constraints,triggers,indexes and statistics etc.
I want to create a similar table with same properties as table A. I know I need to go to Script Table As-> Create To-> New Query Window to duplicate the table structure.
However, after doing that, I realized the statistics in my new table is empty when there are statistics in table A. Did I miss out something?

A: You can script the statistics blob only with the following bit of powershell (which I yoinked from an old blog post of mine):
pushd;
import-module sqlps -disablenamechecking;
popd;

$opts = new-object Microsoft.SqlServer.Management.SMO.ScriptingOptions;
$opts.OptimizerData = $true;

$server = new-object Microsoft.SqlServer.Management.SMO.Server ".";
$database = $server.Databases["AdventureWorks2008R2"];

foreach ($table in $database.Tables) {
    foreach ($stat in $table.Statistics) {
        $stat.Script($opts);
    }
}

The above will script out all statistics (including the histogram data) for all tables in the AdventureWorks2008R2 database. You should be able to tailor it to your needs.


text:
Q: Rails - Authlogic persistence_token question I am trying to implement reset password functionality using the tutorial at http://www.binarylogic.com/2008/11/16/tutorial-reset-passwords-with-authlogic/
and facing difficulties. The problems seem to be coming from persistence_token not matching with what is in the database.
When does persistence_token get set/updated?
My password reset code looks exactly like the tutorial and here it is:
class PasswordResetsController < ApplicationController
  before_filter :require_no_user
  before_filter :load_user_using_perishable_token, :only => [ :edit, :update ]

  def create
    @user = User.find_by_email_address(params[:email])
    if @user
      @user.deliver_password_reset_instructions!
      flash[:notice] = "Instructions to reset your password have been emailed to you"
      redirect_to login_path
    else
      flash.now[:error] = "No user was found with email address #{params[:email]}"
      render :action => :new
    end
  end

def update
  @user.password = params[:password]
  if @user.save
    flash[:success] = "Your password was successfully updated"
    redirect_to @user
  else
    render :action => :edit
  end
end

private

def load_user_using_perishable_token
  @user = User.find_using_perishable_token(params[:id])
  unless @user
    flash[:error] = "We're sorry, but we could not locate your account"
    redirect_to new_password_reset_path
  end
end

The method load_user_using_perishable_token is loading the value correctly from the database, however, the call to @user.password = params[:password] is modifying the peristence_token to a different one. The subsequent call, @user.save fails because it cannot find a record with the modified persistence_token.
Any ideas how to resolve this would be a great help.
Edit for clarification:
1) There is no error, @user.save returns false.
@user.save triggers the following SQL query:
SELECT `users`.id FROM `users` WHERE (`users`.`persistence_token` =
  BINARY '53a6fd82a1da50c299230afd2b7911e7774f6fd62a714909194d5d84e2094444d808a71992bb8b11bc572fd865e9956681dea61bf46e3f65d9d41c53a6b0ec90' AND `users`.id <> 7) LIMIT 1

The persistence_token value used in the query does not match the database value.
2) I am not sure if this is a clue, but in the debugger I notice that whenever
@user.password = params[:password] gets set, the persistence_token value changes in the @user object.

A: What htanata says. You aren't setting the password confirmation. Can you give us the error messages you are getting?
And firstly you do need to set the password_confirmation or you'll be getting validation errors.


text:
Q: JavaScript contenteditable I am creating a HTML rich text editor and I would like to use the contenteditable attribute on a div. I have a list of divs inside a div called editor. When the user hits enter I prevent the default action. I then insert a new div after the current div. The only problem is I cannot focus on the new div. Does anyone know how to do this?
The HTML

The JavaScript

 $(function(){

        var thisLine;

        $("#editor").bind("keydown", function(event){
            if(event.keyCode == 13){
                event.preventDefault();
                var newLine = $("

");
                        newLine.insertAfter(thisLine);
                        $("#2").focus();
                    }
                })

                $(".line").bind("click", function(){
                    thisLine = $(this);
                })

            });

A: This should work:
newLine.insertAfter(thisLine).focus();

Demo: http://jsfiddle.net/tymeJV/7xEXt/

A: Get the selection, and add a new collapsed range to it. See moveCaretToStartOf method in the example

function moveCaretToStartOf(element) {
  var selection = document.getSelection();
  selection.removeAllRanges();
  var range = document.createRange();
  range.setStart(element, 0);
  selection.addRange(range)
}

document.querySelector('div').focus();
window.setTimeout(function () {
 moveCaretToStartOf(document.querySelectorAll('p')[1])
}, 1000);

  Cursor will be placed into the second paragraph after 1 second

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Vel laboriosam nobis nam tempore sint adipisci, ullam perspiciatis placeat aliquid dolorem. Aliquid nisi, dicta sunt dolor qui voluptatem perferendis veniam ad!


text:
Q: When I read in a variable why does matlab return this? I have an excel data set that has one column which is a list of files paths that I would like to read into Matlab.  When I use the xlsread command I obtain the following result
raw =

'files'
[1x135 char]
[1x135 char]
[1x141 char]
[1x141 char]
[1x149 char]
[1x149 char]

Now I understand that the file path in element 1 was 135 characters, but what I don't understand is how to get Matlab to display the path.  Any suggestions?

A: You might want to take a look at cell arrays.  As the xlsread documentation states, the raw output argument is cell array.  Cell array elements are accessed as follows:
myPath = raw{2}

Note the curly braces rather than normal brackets.  When displaying cell array contents, MATLAB will only display the content of a matrix if is below a certain size, which is why all your paths are not showing in this format.


text:
Q: How to create a login module with two user levels in Yii I would like to make a login page with 2 different user levels, Doctor & Parent. How can I do it in Yii....
Two tables listed below....For both users email address is the username.
CREATE TABLE Doctor (
  doctor_email VARCHAR(50),
  password VARCHAR(50),
  doctor_name VARCHAR(50),
  doctor_phone INT(10),
  speciality VARCHAR(200),
  PRIMARY KEY  (doctor_email)
);
CREATE TABLE Parent (
  parent_email VARCHAR(50),
  parent_name VARCHAR(50),
  password VARCHAR(20),
  parent_address VARCHAR(100),
  parent_phone INT(10),
  PRIMARY KEY  (parent_email)
);
This is the authenticate() function in UserIdentity.php
public function authenticate() {
    $record1 = Doctor::model()->findByAttributes(array('doctor_email' => $this->username));
    $record2 = Parents::model()->findByAttributes(array('parent_email' => $this->username));

    if ($record1 !== NULL) {
        if ($record1->password == $this->password) {
            $this->errorCode = self::ERROR_NONE;

        } else {
            $this->errorCode = self::ERROR_PASSWORD_INVALID;
        }
    } else if ($record2 !== NULL) {
        if ($record2->password == $this->password) {
            $this->errorCode = self::ERROR_NONE;

        } else {
            $this->errorCode = self::ERROR_PASSWORD_INVALID;
        }
    }
    return !$this->errorCode;
}

This is my login() function in models/LoginForm.php
public function login() {
    if ($this->_identity === null) {
        $this->_identity = new UserIdentity($this->username, $this->password);

        $this->_identity->authenticate();
        if ($this->_identity->record1 !== NULL)
            $this->isDoc = TRUE;
        else if ($this->_identity->record2 !== NULL)
            $this->isDoc = FALSE;
    }
    if ($this->_identity->errorCode === UserIdentity::ERROR_NONE) {
        $duration = $this->rememberMe ? 3600 * 24 * 30 : 0; // 30 days
        Yii::app()->user->login($this->_identity, $duration);
        return true;
    }
    else
        return false;
}

And this is the actionLogin() in siteContoller.php
public function actionLogin() {
        $model = new LoginForm;
    // if it is ajax validation request
    if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
        echo CActiveForm::validate($model);
        Yii::app()->end();
    }

    // collect user input data
    if (isset($_POST['LoginForm'])) {
        $model->attributes = $_POST['LoginForm'];

        if ($model->validate() && $model->login()) {

            if ($model->isDoc) {
                $this->redirect(array('/doctor/index'));

            } elseif ($model->isDoc == FALSE) {
                $this->redirect(array('/parents/index'));

            }
        }
    }
    // display the login form
    $this->render('login', array('model' => $model));
}

When login for both users its redirect to '/parents/index'. Can anyone tell me what am I do wrong? or any idea.....Thanx in advance..

A: As I can see the problem is that $model->isDoc is Null. And as you have used $model->isDoc == FALSE
I Mean the double equal operator. so this condition is getting true.
Try with $model->isDoc === FALSE (triple equal operator)
I am pretty sure that it will take you to the login form again.
If I am not wrong above then the real problem persists here
if ($this->_identity->record1 !== NULL)
            $this->isDoc = TRUE;
        else if ($this->_identity->record2 !== NULL)
            $this->isDoc = FALSE;

Try to var_dump($this->_identity->record1) as well as var_dump($this->_identity->record2) and check whether any of them is not getting null in any case
Or you can try this
in your UserIdentity class you need to declare two variable s as
class UserIdentity extends CUserIdentity
{
public $record1;
public $record2;

}

Now in your authenticate()
change $record1 to $this->record1 and $record2 to $this->record2


text:
Q: grep command not filtering out , ; or ' This is the command I'm using:
grep '\bth.[aeiouy]*\b' filename.txt

It returns things as expected like the, thee, etc. but it also returns strings like o'th and with;
Any ideas as to why?


text:
Q: Can PCA generate a new random image? I read The Batch: GANs newsletter and Goodfellow said:

My colleague Bing Xu modeled face images from the Toronto Face Database, which were only 90 pixels square and grayscale. Because the faces were always centered and looking straight at the camera, even very simple algorithms like PCA could make pretty good faces.

I wonder how PCA can be used to make faces. As far as I know, it can be used to reconstruct image like in the article Facial Image Compression and Reconstruction with PCA. But can it generate a new random image?


text:
Q: Apparent GCC bug with comma operator in constant initializer I was messing around with C and discovered an apparent bug in GCC:
#include <stdio.h>

int y = (1, 2);
int main()
{
  return 0;
}

in gcc gives error: initializer element is not constant while it works fine in clang. And as expected, putting the declaration inside the main() function also works with both compilers.
The parentheses are necessary, as otherwise gcc would be correct in disallowing the comma operator.
Despite the gcc code snippet looking like this:
    3 | int y = (1, 2);
      |         ^

the parentheses are not the problem. int y = (1 + 2); works fine.
I know that the comma operator is never necessary in constant expressions, as there should never be any side effects, but it's still odd that GCC sees it as an error instead of just printing warning: expression result unused (which it also does).
Is this a bug?

A: Per the standard, comma operator is not allowed in constant expressions, but clang admits it in most (but not all) contexts. For example:
int a = (1,2); //accepts

int b[(1,2)]; // warns: VLA folded to constant size array

_Static_assert((1,2), "oops!"); // fails

struct
{
   int c : (1,2); // accepts
   int d [(1,2)]; // warns: VLA folded to constant size array

} e;

enum { FOO = (1,2) }; //accepts

int _Alignas((2,16)) f; // fails

int* g = (1,0); // warns: integer to pointer conversion
                // so this is not a null pointer constant,
                // but still a constant expression (because the
                // initialisation is accepted)!

Live
gcc rejects all of these constructs.
The standard does allow an implementation to accept other forms of constant expressions though, but it isn't clear if these other forms should be documented or how they should be admitted in different contexts.
There is a clang bug about clang sometimes treating comma as allowed in constant expressions.


text:
Q: Cannot ignore files for search with VSCode I have modified both UserSettings and WorkSpaceSettings like so:
{
    "search.exclude": {
        "**/node_modules": true,
        "**/bower_components": true,
        "**/public-coverage": true,
        "**/public/dist": true,
        "**/public/static": true,
        "**/public/lib": true
      }
}

when I search for "xyz" in the search bar, I am still getting hits from the public/dist directory and public-coverage directory, as you can see in the screenshot:

Does anyone know how to do this right?

A:
Make sure this is checked. This is common mistake.

A: try
 "search.exclude": {
    "node_modules": true,
    "bower_components": true,
    ...
 }


text:
Q: Translation comparison tools for PO format? I am using POEdit to modify the localization file of some projects.
Unfortunately it seems not able to do comparisons with different versions. Do you now if it does exists a comparison tool for Windows that support PO format?

A: Searching for basically the same in 2016, here is what I found:

*

*using podiff, as suggested in this SO question, did not work for me: POEdit apparently put some characters in the po file that podiff reported as errors

*I ended up using the standard gettext tools in Cygwin - this can be an overkill to install just for this task, but I already had Cygwin installed (it is handy for various tasks, eyspecially text editing and transformation). It is the package gettext-devel. Diffs can be then performed using the various msgxxx commands, for example:

msgcomm file1.po file2.po -o common.po

for strings with common msgids in two files, with translations taken from file1.po.
See the particular command help (e.g. msgcomm --help) for more information

A: I can suggest a tool as alternative to Poedit, it's http://poeditor.com/ in which you can create more projects and compare the translation files. It also has the option of setting a reference language from other translations you have on the project, which shows the other language under your original strings, so that you can compare.

A: You may want to try BeyondCompare. I don't know whether it is suitable for PO files, but it may also get "trained" for such files. I know that the strings are often split into multiple lines, which may cause some problems. Otherwise, as the PO files are plain text files (in UTF-8 usually), this should be easy.
You may also want to write some perl script for this. I remember I wrote something to take a PO file and produce a printable document with the joined lines.
The Beyond Compare software is available here: http://www.scootersoftware.com/moreinfo.php
I understand that plug-ins can be written for Beyond Compare.
Have a great day :-)


text:
Q: Is there more to the C# "as" keyword than simple casting? I'm working through Josh Smith's CommandSink code obviously do not understand something about the "as" keyword in C#.
I don't understand why he wrote the line:
IsValid = _fe != null || _fce != null;

since he only needed to write:
IsValid = depObj != null;

Since it would never be the case the _fe would be null and _fce not null, or visa versa, right?  Or am I missing something about how "as" casts variables?
class CommonElement
{
    readonly FrameworkElement _fe;
    readonly FrameworkContentElement _fce;

    public readonly bool IsValid;

    public CommonElement(DependencyObject depObj)
    {
        _fe = depObj as FrameworkElement;
        _fce = depObj as FrameworkContentElement;

        IsValid = _fe != null || _fce != null;
    }
    ...

ANSWER:
The answer is what Marc said in his comment "that is the whole point of "as" - it won't throw an exception - it just reports null."
and here is the proof:
using System;

namespace TestAs234
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer customer = new Customer();
            Employee employee = new Employee();

            Person.Test(customer);
            Person.Test(employee);
            Console.ReadLine();
        }

    }

    class Person
    {
        public static void Test(object obj)
        {
            Person person = obj as Customer;

            if (person == null)
            {
                Console.WriteLine("person is null");
            }
            else
            {
                Console.WriteLine("person is of type {0}", obj.GetType());
            }
        }
    }

    class Customer : Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    class Employee : Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

}

A: as does "cast, if it is", and equivalent to:
(X is TYPE) ? (TYPE) X : null
it is however, more efficient than is + cast.
depObj may implement either interface, none, or both.

A: IsValid = _fe != null || _fce != null;

and
IsValid = depObj != null;

are not the same tests because if depObj is not of type FrameworkElement nor FrameworkContentElement but is not null the second test will return true, while the first will return false.

A: as will return an object of the type you requested, if the operand is compatible. If it isn't, it will return null. If you use as and it is possible that the cast will fail, you need to check to make sure the reference is valid.
For example, if depObj was of type String, it would not be null, but it would also not be able to be converted to either of the requested types and both of those variables would become null.

A: What if depObj is neither a FrameworkElement or a FrameworkContentElement? I don't know the full scenario (i.e. what the types are likely to be), but this seems a reasonable defensive strategy.

A: First, the as keyword includes a is check.
if( o is A)
   a = (A) o;

is the same as
a = o as A;

Second, as does not convert the Type like a cast does, even if a conversion operator from Type A to B is defined.

A: What if the DependencyObject depObj was actually a  FrameworkOtherTypeOfElement
Then depObj would not be null
but the attempted as Casts would both evaluate to null and _fe & _fce would both be null
as is equivalent to doing
if(I Can Cast This Object)
   //Then cast it
else
   //Return null


text:
Q: Text chat only in TokBox? I found Tokbox is a great service for video chat. Is it possible to use text chat alone in tokbox? or text chat with video in Takbox?
Thanks

A:
You can use the OpenTok signaling API to send text and data between clients connected to an OpenTok session. These messages allow developers to build basic text chat, send instructions from one client to another, and create other valuable experiences.

Check the documentation about howto use signaling.
But maybe consider building a text chat with socket.io for example.

A: I've build a system with videostreams and text chats. You can use the tokbox signals for it.
function chat_post_message(){
    $.post(url,$('form').serialize(),function(data){
        session.signal({
            type: "livechat",
            data: data
        });
    });
}

$(function(){
    session.on("signal", function(event) {
        if(event.type == "signal:livechat"){
            //update a (chat)container with data
        }
    });
});

https://tokbox.com/developer/guides/signaling/js/
Hope it helps!


text:
Q: How to change colour of an element nested in other elements using javascript I have a list structured as such:

<button onclick="changeColour()"></button>

The css for my links are:
ul li a {
          color: red
        {

How do I change the colour of my links?? I know you can do this:
function changeColour() {
  var div = document.getElementsByTagName("ul");
  div.style.changeColour = "rgb(0, 212, 177)";
}

but I don't know how to the links within list item within the list.

A: You can change it with css. Your css is correct but you missed ; after red. And you can do it with javascript too or you can use both if you want to give it a color then change it at run time. For your javascript code you forgot to add the collection's index...
document.getElementsByTagName('a')[0].style.color='orange';

NB: I'm targeting the first anchor with [0]. To target all anchors loop through the collection.
Like this

function changeColour() {
  var div = document.getElementsByTagName("a");
  for(var i = 0; i < div.length; i++){
    div[i].style.color = "rgb(111, 112, 112)";
  }
}

changeColour();
ul li a {
  color: red;
{

        link 1

        link 2

A: Try document.querySelectorAll:

let links = document.querySelectorAll("ul.list li.list-element a");
for (let link of links) {
    link.style.color = "rgb(0, 212, 177)";
}
ul li a {
    color: red
{

        LINK 1

        LINK 2

A: HTML

        link 1

        link 2

Script
$('.list').each(function(){
        $(this).find('li a').css('color','rgb(111, 112, 112)');
 });

A: Below is Jquery model in case you are looking for it

// Jquery model if you want to use
$(document).ready(function(){
   $('#change').click(function(){

   var color=["blue","red","yellow","black","pink","green"];
    var prompts = prompt("please type your valid color");
   // checking if entered colored is registered
    for(x in color){
      if(color[x] ==prompts){
      //registered then set its value as color
        $("a").css({"color":prompts});
        return ;
      }
     }
     // deal with unregistered color
 var conf = confirm('not registered color entered , do you want to set the default color?');
        if(conf ==true ){
          $("a").css({"color":"black"});
        }
   });
});
ul li a {
  color: red;
{

        link 1

        link 2

 please click here to change link color


text:
Q: Unobtrusive validation warnings (not errors) How would I go about building a warning level notification on top of the built in unobtrusive validation?
Totally made up example:  I'm allowing people to specify how long they'd wait for a table from the start of their reservation.  It has to be between 0 and 12 hours (no negative waits, and nothing past closing time), but one might also want to ask "are you sure" about a 5 hour wait?
Obviously you could do this in a one-off fashion on a field by field basis, but I'd like to have it based on data model attributes, since that's where I'd have the "between 0 and 12" validation.
So, off the top of my head, I can see the need for something that extends ValidationAttribute and implements IClientValidatable.  I'd also need to add my validation method to validator in a custom JavaScript file.  Is that it?


text:
Q: No connection could be made because the target machine actively refused it (PHP / WAMP) Note: I realise this could be seen as a duplicate but i have looked at the other responses and they didn't fix the problem for me.

I have recently installed Zend Studio and Zend Server with the mysql plugin on Windows 7.
I am not a qualified server administrator but neither am i completely incompetent; i have dedicated my day trying to get a local development 'server' up to cut down on upload/download times.
When I say server/machine i mean my home computer
I have come to a grinding halt trying to get mysql to work with Zend Server.
The error I keep receiving is (or verbose):
#2002 Cannot log in to the MySQL server
or (if i change to 'config' authentication type)
#2002 - No connection could be made because the target machine actively refused it.

The server is not responding (or the local server's socket is not correctly configured).

I have tried:

*

*Change $cfg['Servers'][$i]['host'] from 'localhost' to '127.0.0.1'

*Add/Remove $cfg['Servers'][$i]['socket'] = '';

*Change from cookie to config auth type

*reinstall server and mysql

*Disable firewalls

*Restarting machine

Zend's approach was to 'configure the phpmyadmin setup screen'... done that i don't know how many times.
Can anyone on here lend a hand, or point me in a direction that I haven't tried yet?

A: You might need:

*

*In wamp\bin\mysql\mysqlX.X.XX\my.ini  find these lines:
[client]
...
port = 3308
...
[wampmysqld64]
...
port = 3308
As you see, the port number is 3308 (or maybe 3306). You should :

*

*use that port in applications, like WordPress: define('DB_HOST', 'localhost:3308')
or

*

*change it globally in wamp\bin\apache\apache2.X.XXX\bin\php.ini change
mysqli.default_port = ...   to 3308

A: *

*Go to C:\wamp\bin\mysql\mysql[your-version]\data

*Copy and save "ib_logfile0" and "ib_logfile1" anywhere else.

*delete "ib_logfile0" and ib_logfile1

Did the trick for me. hope it works for you too.
Its working fine.
But we will have to stop apache and mysql, We need to quit xampp and then delete file. when deleted successfully. now start xampp it will work properly..

A: Till yesterday I was able to connect to phpMyAdmin, but today I started getting this error:
2002-no-connection-could-be-made-because-the-target-machine-actively-refused
None of the answers here really helped me fix the problem, what helped me is shared below:
I looked at the mysql logs.[C:\wamp\logs\mysql.log]
It said
2015-09-18 01:16:30 5920 [Note] Plugin 'FEDERATED' is disabled.
2015-09-18 01:16:30 5920 [Note] InnoDB: Using atomics to ref count buffer pool pages
2015-09-18 01:16:30 5920 [Note] InnoDB: The InnoDB memory heap is disabled
2015-09-18 01:16:30 5920 [Note] InnoDB: Mutexes and rw_locks use Windows interlocked functions
2015-09-18 01:16:30 5920 [Note] InnoDB: Compressed tables use zlib 1.2.3
2015-09-18 01:16:30 5920 [Note] InnoDB: Not using CPU crc32 instructions
2015-09-18 01:16:30 5920 [Note] InnoDB: Initializing buffer pool, size = 128.0M
2015-09-18 01:16:30 5920 [Note] InnoDB: Completed initialization of buffer pool
2015-09-18 01:16:30 5920 [Note] InnoDB: Highest supported file format is Barracuda.
2015-09-18 01:16:30 5920 [Note] InnoDB: The log sequence numbers 1765410 and 1765410 in ibdata files do not match the log sequence number 2058233 in the ib_logfiles!
2015-09-18 01:16:30 5920 [Note] InnoDB: Database was not shutdown normally!
2015-09-18 01:16:30 5920 [Note] InnoDB: Starting crash recovery.
2015-09-18 01:16:30 5920 [Note] InnoDB: Reading tablespace information from the .ibd files...
2015-09-18 01:16:30 5920 [ERROR] InnoDB: Attempted to open a previously opened tablespace. Previous tablespace harley/login_confirm uses space ID: 6 at filepath: .\harley\login_confirm.ibd. Cannot open tablespace testdb/testtable which uses space ID: 6 at filepath: .\testdb\testtable.ibd
InnoDB: Error: could not open single-table tablespace file .\testdb\testtable.ibd
InnoDB: We do not continue the crash recovery, because the table may become
InnoDB: corrupt if we cannot apply the log records in the InnoDB log to it.
InnoDB: To fix the problem and start mysqld:
InnoDB: 1) If there is a permission problem in the file and mysqld cannot
InnoDB: open the file, you should modify the permissions.
InnoDB: 2) If the table is not needed, or you can restore it from a backup,
InnoDB: then you can remove the .ibd file, and InnoDB will do a normal
InnoDB: crash recovery and ignore that table.
InnoDB: 3) If the file system or the disk is broken, and you cannot remove
InnoDB: the .ibd file, you can set innodb_force_recovery > 0 in my.cnf
InnoDB: and force InnoDB to continue crash recovery here.

I got the clue that this guy is creating a problem - InnoDB: Error: could not open single-table tablespace file .\testdb\testtable.ibd
and this line 2015-09-18 01:16:30 5920 [Note] InnoDB: Database was not shutdown normally!
hmmm, For me the testdb was just a test-db! hence I decided to delete this file inside C:\wamp\bin\mysql\mysql5.6.17\data\testdb
and restarted all services, and went to phpMyAdmin, and this time no issues, phpMyAdmin opened :)

A: I'm having the same problem with Wampserver. It's worked for me:
You must change this file: "C:\wamp\bin\mysql[mysql_version]\my.ini"
For example: "C:\wamp\bin\mysql[mysql5.6.12]\my.ini"
And change default port 3306 to 80. (Lines 20 & 27, in both)
port        = 3306
To
port        = 80
I hope this is helpful.

A: All I have to do in order to get rid of that error was to restart my wamp server.

A: In my case i did the following and worked for me

*

*I clicked on the wamp icon.

*i went to MySQL > Service administration 'wampmysqld64' > install service

*Then click on wamp icon >  Restart all service.

A: Just Go to your Control-panel and start Apache & MySQL Services.

A: Please check your hosts file in etc folder and add below comments then run wamp server.
127.0.0.1       localhost
Path : C:\Windows\System32\drivers\etc

A: I have just removed the mysql service and installed it again. It works for me

A: Kindly check is your mysql-service is running.
for windows user: check the services - mysql service
for Linux user: Check the mysql service/demon is running (services mysql status)
Thanks & Regards
Jaiswar Vipin Kumar R

A: following steps worked for me.

*

*Go to wamp\apps\phpmyadmin

*search config.inc.php

*search 127.0.0.1 and replace with "localhost".


text:
Q: Image Not Loading (WordPress Template) Im adding an image to my wordpress theme through dreamweaver cs4 and themedreamer. The image will go in the sidebar.php. When I inserted an image it doesnt shows in firefox and explorer. With safari, the image only shows an empty box with a question sign in the middle.
Is there a special way to add image in a wordpress template?

A: Prepend below line to images's src:
<?php echo get_bloginfo('template_url'); ?>

Making your src something like this:
<img src="<?php echo get_bloginfo('template_url'); ?>/images/yourimage.gif" alt="" />

A: No, but you have to get the value of the src attribute correct.


text:
Q: How to include (print) Latex source code in generated pdf? I want to include the source code of my latex generated pdf file in the pdf file itself as printed text. Is there any way to do this?

A: Use the package attachfile and put \expandafter\attachfile\expandafter{\jobname.tex} in your file. This will attach the *.tex-file to the pdf (thanks to Heiko Oberdiek, who answered this question years ago).

A: [OPs answer moved from question]
I found a way to do this. You have to use listings as follows.
\usepackage{listings}
\lstset{breaklines=true}

% optional ˇ
\lstset{literate=%
{Ć}{{\'C}}1
{ć}{{\'c}}1
{Č}{{\v{C}}}1
{č}{{\v{c}}}1
{Š}{{\v{S}}}1
{š}{{\v{s}}}1
{Đ}{{\DJ}}1
{đ}{{\dj}}1
{Ž}{{\v{Z}}}1
{ž}{{\v{z}}}1
}
% optional ^

\begin{document}

%text

\lstinputlisting{SourceCodeFile.tex}

\end{document}

In the \lntinputlisting{} goes the file path.
I used \lstset{literate=% ... for special characters that you have to define.I tried to find a way without using literate but nothing worked.

A: if the purpose of this exercise is to make the source code visible to readers of the
pdf file, say to document self-contained code examples, i've had excellent results
with this simple approach.
\documentclass{article}
\usepackage{verbatim}

% your preamble

\begin{document}

% your text

\newpage
\verbatiminput{\jobname.tex}
\end{document}

A: Here is what you can do if you want to print an example.tex code in a PDF file.
\documentclass{article}
\usepackage{verbatim}
% Rest of preamble

\begin{document}
    \begin{verbatim}
        % Enter your .tex code here
    \end{verbatim}
\end{document}


text:
Q: Fairly distribute predefined value using binary array as mask While answering this question, I was wondering what is the most efficient/simple way to distribute a predefined value across the 1 values of a binary array. The value should be distributed as fairly as possible (the remainder is distributed randomly so that each cell can eventually get one extra).
For instance, distributing 4 in [1, 0, 1] would result in [2, 0, 2], while distributing 5 could give either [3, 0, 2] or [2, 0, 3]. The distribution should work on an array of arbitrary dimensions.
Let's call distribute the function. It should take as parameters value the value to be distributed and array the binary array and return an array of same shape with the distributed value.
def distribute(value, array):
    ...
    return # array of same shape with fairly distributed value

>>> distribute(10, np.array([0,1]))
array([ 0, 10])

>>> distribute(10, np.array([1,0,1]))
array([5, 0, 5])

>>> distribute(9, np.array([1,0,1]))
array([4, 0, 5]) # could also be array([5, 0, 4])

>>> distribute(9, np.array([[1,0],[0,1]]))
array([[5, 0],
       [0, 4]])

>>> distribute(10, np.diag(np.ones(4)).reshape(2,2,-1))
array([[[3., 0., 0., 0.],
        [0., 2., 0., 0.]],

       [[0., 0., 3., 0.],
        [0., 0., 0., 2.]]])

See my proposed solution in the answers.  Please propose alternative approaches, the goal is to find the most efficient and/or simple.

A: def distribute(value, array):
    shape = array.shape # save the original shape of the array
    div, mod = map(int, divmod(value, np.sum(array))) # calculate equal split and remainder, ensuring int type
    array = (array*div).flatten() # distribute evenly and flatten
    array[np.random.choice(np.flatnonzero(array), mod, replace=False)] += 1 # allocate remainder randomly
    return array.reshape(shape) # return the array reshaped as original


text:
Q: How to give json response dynamically..? Here is the json response
[{"lat": "36.15900011", "lon": "-115.17205183"}, {"lat": "36.15899561", "lon": "-115.17276155"}]

And below code given this error:
TypeError: item is undefined
...: new ol.geom.Point(ol.proj.transform([item.lon , item.lat], 'EPSG:4326', 'EPSG:...

below the code inside the <script>
    $.ajax({
     url:'parser', success:function(response){
      $(document).ready(function(){
      var jsonlen = response.length;
      for (var i=0; i<=jsonlen; i++){
        var item = response[i];
        var iconFeature = new ol.Feature({
        geometry: new ol.geom.Point(ol.proj.transform([item.lon , item.lat], 'EPSG:4326', 'EPSG:3857')),
        name:'Null Island',
        rainfall:500
      })
        var vectorSource = new ol.source.Vector({
        // empty vector
      })
      vectorSource.addFeature(iconFeature);
      }

I don't know how to give json response continuously to iconFeature

A: First of all, unwrap your code from the handler, it makes no sense here.  I've amended it in the code.
Second, your for loop will run even if the length is empty. That's why you're getting undefined.
You need to use just less than, not less than or equal.
Because, if the length is zero, and i initiates at zero, then the conditional will be true and response[0] will be called, even though the response is an empty array.  Returning undefined
Third (and I can't help you with this), you have to check the response to make sure the data is present.  It doesn't seem like it is.
  $.ajax({
     url: 'parser',
     success: function (response) {
         var jsonlen = response.length - 1;
         for (var i = 0; i < jsonlen; i++) {
             var item = response[i];
             var iconFeature = new ol.Feature({
                 geometry: new ol.geom.Point(ol.proj.transform([item.lon, item.lat], 'EPSG:4326', 'EPSG:3857')),
                 name: 'Null Island',
                 rainfall: 500
             });
             var vectorSource = new ol.source.Vector({
                 // empty vector
             })
             vectorSource.addFeature(iconFeature);
         }
     }
 });


text:
Q: How can I create a relation between 2 classes on different datasources? I'm working on a web-app, that has 3 datasources: we can call them DS1, DS2 and DS3. Each of them is a physical database.
So I added a configuration for each of these datasources, with a different entity manager and so on.
Inside the DS1 I have the entity E1, while inside the second datasource I have E2.
Now I need to create a relation between these 2 entities.
So I added something like:
public class E1 {
...

@OneToOne
private E2 e2;

...
}

But I have the following error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManager' defined in class path resource [it/mux/config/datasource/DataSourceMuxConfig.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: @OneToOne or @ManyToOne on it.mux.domain.amministrazione.Bo.e2 references an unknown entity: it.mux.cliente.domain.E2
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1080) ~[spring-context-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:857) ~[spring-context-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    at it.mux.MuxApplication.main(MuxApplication.java:21) [classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_161]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_161]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_161]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_161]
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-1.5.10.RELEASE.jar:1.5.10.RELEASE]
Caused by: org.hibernate.AnnotationException: @OneToOne or @ManyToOne on it.mux.domain.amministrazione.E1.e2 references an unknown entity: it.mux.cliente.domain.E2
    at org.hibernate.cfg.ToOneFkSecondPass.doSecondPass(ToOneFkSecondPass.java:97) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processEndOfQueue(InFlightMetadataCollectorImpl.java:1786) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processFkSecondPassesInOrder(InFlightMetadataCollectorImpl.java:1730) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1617) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:278) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:847) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:874) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:360) ~[spring-orm-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:382) ~[spring-orm-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:371) ~[spring-orm-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:336) ~[spring-orm-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    ... 21 common frames omitted

First of all, is it possible to do it??
If yes, how can I fix it?

A: That would not be possible out of the box as those entities are in a separate persistence contexts.
Creating custom composite persistence context and keeping it in synch with Hibernate will be a lot of effort.
For one-to-one (or any other) relationship, you could implement something like:
List<E1> e1s = repositoryDS1.findAllE1();
List<E2> e2s = repositoryDS2.findAllE2();
List<E1E2Aggregate> = mapper.map(e1s, e2s);


text:
Q: Size of Python IO Stream import io
string_out = io.StringIO()
string_out.write("hello")
print(string_out.lenght())

I want to know size of string_out StringIO. Is there any method in StringIO that support this?

A: The return value of the write() is the number of the written characters.
import io
string_out = io.StringIO()
length = string_out.write("hello")
print(length)

A: StringIO.write returns the count of what it wrote:
import io
string_out = io.StringIO()
n = string_out.write("hello")
m = string_out.write("helloagain")
print(f'hello is: {n}')
print(f'helloagain is: {m}')

outputs:
hello is: 5
helloagain is: 10


text:
Q: GDB help to analyse core One of our code is generating a core file
While trying to analyse core using gdb with below commands
gdb programe_name core
I am unable to retrieve the tarce with backtrace command getting below
  #4  0x20202020 in ?? ()
  #5  0x20202020 in ?? ()
  #6  0x20202020 in ?? ()
  #7  0x20202020 in ?? ()
  #8  0x20202020 in ?? ()
  #9  0x20202020 in ?? ()
  #10 0x20202020 in ?? ()
  #11 0x20202020 in ?? ()
  #12 0x20202020 in ?? ()
  #13 0x20202020 in ?? ()
  #14 0x20202020 in ?? ()
  #15 0x20202020 in ?? ()
  #16 0x20202020 in ?? ()
  #17 0x20202020 in ?? ()
  #18 0x20202020 in ?? ()
  #19 0x20202020 in ?? ()

do we have a command which I can use to get trace with function name and arguments

A: It looks like your stack has been "crunched" -- that is, overwritten with some data that shouldn't be there.
0x20202020 is four spaces in ASCII, so the stack has been overwritten by a string of characters with a lot of spaces.
Look for an array (or variable) that you are reading into (or copying characters into); the chances are you are reading/copying more data than you expected into that array/variable.
To avoid this sort of thing in the future, use one of the forms that allows you to limit the amount read/copied to the size of the target area:
fread
fgets
strncpy

You might want to also take a  look at the answers to
Reading in a variable length string user input in C
As relatively safe ways to protect yourself when reading data of unknown length into a buffer.


text:
Q: jQuery change css right align when td data numeric (dynamic table) $('tr > td:gt(0)').filter(function() {
                        return this.innerHTML.match(/^[0-9\s\.,]+$/);
                        }).css('text-align','right');

I am trying to loop through a dynamic table and right align every td that contains numeric data on each row EXCEPT the first td on each row.
It works on the first tr but not each subsequent row...

A: The reason this isn't working is that your jQuery selector is collecting all td elements (that are children of trs), and then sub-selecting all but the first one. To avoid this, you can iterate over the rows of the table, applying your filter to the td elements of each one:
$('tr').each( function () {
    $(this).children('td:gt(0)').filter(function() {
        return this.innerHTML.match(/^[0-9\s\.,]+$/);
    }).css('text-align','right')
});

If you only want to apply this to a certain table, change the selector in the first line to '#table-id tr'.
Here it is in action: http://jsfiddle.net/munderwood/d48Q4/1/


text:
Q: Firebase rules: dynamically give access to a specific user I'm building an Android app which requires me to store some pictures for the user.
Let's say I have 2 users: A and B. They should be able to read / write on their specific folders: user A can read and write to bucket/images/userA and user B can read and write to bucket/images/userB. They should not have access to anything else.
Now let's say user A uploaded picture1.jpg and picture2.jpg. How can user A grant access to bucket/images/userA/picture1.jpg to user B? User B should not have access to picture2.jpg though.
I'm looking for a solution that scales for many users (~100.000+). I suppose it's not a great idea to add a rule to the storage rules every time I want to give access to a file.
The solution I use right now is anyone logged in can read anything if they have the full path to it. The path is not easy to guess and when I want to give access I provide the link. Is that a secure enough solution? I don't think so.

A: On the client side
You can use custom File Metadata for that. What it does it is adds a Map<String, String> to the file's metadata. And since keys in a Map are unique, you can store the user B's id as a key and use an empty string as value:
StorageMetadata metadata = new StorageMetadata.Builder()
                        .setCustomMetadata(userId,"") //User B's id
                        .build();

Then use the updateMetadata() method to share the file:
picture1Ref.updateMetadata(metadata)
        .addOnSuccessListener(new OnSuccessListener<StorageMetadata>() {
            @Override
            public void onSuccess(StorageMetadata storageMetadata) {
                // Updated metadata is in storageMetadata
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
                // Uh-oh, an error occurred!
            }
        });

On the Firebase Console
Then in order to validate this on the Firebase side, you can set your rules as following:
service firebase.storage {
  match /b/{bucket}/o {
    match /images/{userId}/{pictureName}{
      allow write: if request.auth.uid == userId;
      allow read: if request.auth.uid == userId || request.auth.uid in resource.metadata.keys();
    }
  }
}

Share with more users
If you want to share this same file with more users (let's say user C and D), you can repeat the same steps passing their ids to the custom metadata, because only the properties specified in the metadata are updated and all others are left unmodified.
Revoke user access
If you want to revoke access from a specific user, you can set a null value to the custom metadata and call the updateMetadata() once again.
StorageMetadata metadata = new StorageMetadata.Builder()
                        .setCustomMetadata(userId, null)
                        .build();


text:
Q: How do I create my docker image from a forked GITHUB repo? I forked Grafana into my repo and I made some changes to it, I want to test this in docker.
How do I build this as a docker image?
PS: Am new to this.
Thank you

A: Grafana has a Dockerfile, so you can build a Docker image using that file.
In your forked directory, run the following to build the image.
docker build --tag grafana .

This will create a Docker image named grafana with your changes.
Then follow Grafana's instructions on running from a Docker image:
docker run -d -p 3000:3000 --name grafana-dev grafana

and open localhost:3000 in a browser.
You might consider looking at the documentation for docker run and docker build.


text:
Q: Prove that $\coth ^2(x)-1\equiv \mathrm{cosech}^2 (x)$ Prove that $\coth ^2(x)-1\equiv \mathrm{cosech}^2 (x)$
My attempts,
$\coth^2 (x)-1\equiv(\frac{e^x+e^{-x}}{e^x-e^{-x}})^2-1$
$\equiv \frac{e^{2x}+e^{-2x}+2}{e^{2x}+e^{-2x}-2}-1$
$\equiv \frac{e^{2x}+e^{-2x}+2}{e^{2x}+e^{-2x}-2}-\frac{e^{2x}+e^{-2x}-2}{e^{2x}+e^{-2x}-2}$
$\equiv \frac{e^{2x}+e^{-2x}+2-e^{2x}-e^{-2x}+2}{e^{2x}+e^{-2x}-2}$
$\equiv \frac{4}{e^{2x}+e^{-2x}-2}$
$\equiv (\frac{2}{e^x-e^{-x}})^2 $
$\equiv \mathrm{cosech}^2x$
Am I correct?