text:
Q: Passing an image when taped on uicollectionview to a detail view controller in swift Ive been at this for a while but cant seem to crack it in swift
I want a user to be able to select an image in uicollectionView and for that image to appear in a detailed view controller, i can do this quite easily with a peice of text,
and i can do this when there is a static array of images preloaded. but i cant seem to get anywhere with a collectionview which is loaded with images from a camera.
I understand i need to use
override func performSegueWithIdentifier(identifier: String, sender: AnyObject?) {
  }

and this function to isolated selected cell.
  func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
  }

I do have these outlets
      @IBOutlet weak var collectionView: UICollectionView!
  var images = [UIImage]()

image picker stores all images to this array by
  images.insert(newImage, atIndex: 0)

when the array would be passed to the detailviewcontroller, i understand that would have to be copied into another local array and then how would i get the current image that was highlighted to be shown first, perhaps using indexPath.Row
Regards

A: I'm not using segues, and actually I don't quite understand what your problem is, but I'll try to show you how it could be achieved.
First of all, you have an array with images, so I believe your image should be accessed as images[indexPath.row]
let's suppose that you already have UIViewController class with UIImageView in it.
if so, you can write something like that:
func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
    let myVC = MyViewController()
    myVC.imageView.image = images[indexPath.row]
    self.presentViewController(myVC, animated: true, completion: nil)
}

for modal or
func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
    let myVC = MyViewController()
    myVC.imageView.image = images[indexPath.row]
    self.navigationController?.pushViewController(myVC, animated: true)
}

if you want to show it as navigational.
I believe that with segues it's basically the same but I think you have to use func prepareForSegue for, you know, preparing the segue (func performSegueWithIdentifier will just perform it). In prepareForSegue you should check identifier of your segue
if segue.identifier == "myIdentifier" {
  //your code here
}

and if this identifier is right, put your commands to your myVC there.


text:
Q: Chrome Service Worker iOS Support As Apple announced Service Worker support for iOS 11.3 a few months ago, I recently started trying to get a service worker to work on iOS. On Safari it works as expected, after vising the website, it works offline. However, when trying to use the same feature in Chrome, I had intermittent results. Specifically, the service worker would only work every other page refresh, with the original refresh after going offline being one of the ones not working.
I know that Chrome on iOS is built on a version of Safari, therefore I am confused about this behavior.
Is this due to incomplete support from Chrome iOS for Service Workers? Because it is Chrome on iOS, I'm not sure of any easy way to debug it either, so any other tips to help track down the problem would be appreciated. Thank you!

A: Chrome for iOS do not support service workers currently(as of Apr-2020) and also the "Add to home screen" option is not available, if you are interested in that. Any offline page loading that you are experiencing should be from regular browser cache.
Here is an official documentation from Apple's web-kit page.

Update: A previous version of this post stated the Service Worker API
  is available in all applications using WKWebView. At this time it is
  only available in Safari, applications that use
  SFSafariViewController, and web applications saved to your home
  screen.

Notably, Chrome uses WKWebView as its browser engine in iOS, which don't have service worker support yet as per the above statement(which you can find in the link provided above). So the only way you can use Service worker in iOS is to use Safari browser or use one of the above supported web-views inside a native app.
Here is an article on what all PWA features iOS is still missing. Remember, this is a fast growing area. Always check if what is applicable now, especially if the documentation/article is getting older.
Here is an adapter to help debug in Chrome dev tools for pages loaded iOS - webkit/safari. Hope it becomes as easy as Android Chrome debugging one day!

A: Chrome for iOS is open source (https://blog.chromium.org/2017/01/open-sourcing-chrome-on-ios.html)
We can install the Chrome app with our developer signed certificate on an iOS device, launch the Chrome App, and start testing.
It is technically feasible.

A: As an update in January 2021: the official documentation from Apple's web-kit page still says the same thing, and I just battled a very difficult to debug issue in Chrome iOS - posting here in case it helps someone.
I had an iFrame containing a cross-origin Angular 10 PWA with Service Worker enabled, and the iFrame content would not show after an initial load - no errors, no server logs, just blank. The only solution that worked was to self-destruct the Service Worker per Angular's docs, and now the iFrame loads fine.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Connect SafeNet HSM using Java remotely Our application needs to interact with SafeNet HSM through Luna JSP api using java. We tried the following and were able to connect
     LunaSlotManager slotManager = LunaSlotManager.getInstance();
     slotManager.login(password);

But my question is that in my program I didn't give any IP Address of the HSM device. Then how does it detect and connect?

A: Any API calls to the Safenet Luna API will interact with the Safenet client software which is installed on your local machine.  This client software handles the actual network connection to the HSM.  The details for which HSM(s) the client software can communicate with are stored in the following locations:

*

*Windows:  C:\Program Files\LunaSA\crystoki.ini

*Linux, Solaris and AIX:   /etc/Chrystoki.conf

A simple way of listing the active servers is using the vtl command that is part of the Safenet software:
$ vtl listservers
Server: 10.10.10.10

The vtl command can also be used to make changes to the config files using the addServer and deleteServer commands.


text:
Q: Web Forms - Session object is null when going through custom IRouteHandler I'm having an issue in ASP WebForms where HttpContext.Current.Session is null if my request goes through a custom IRouteHandler.
I have seen many answers where people are giving advices on how to access the Session object inside a custom IRouteHandler but this is not my issue. I don't need to access the session object in the handler, I just don't want it to be null when using that handler.
This is the code for the custom handler:
public class LanguageRouteHandler : IRouteHandler
{
    private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        Logger.Debug("GetHttpHandler");

        //return new LanguageHttpHandler(this, requestContext);

        string rest = requestContext.RouteData.Values["rest"] as string;
        string destinationPath = "";

        string language = requestContext.RouteData.Values["language"] as string;

        string queryString = "?";
        NameValueCollection queries = HttpContext.Current.Request.QueryString;

        foreach (string myKey in queries.AllKeys)
        {
            queryString += (myKey + "=" + queries[myKey] + "&");
        }
        HttpContext.Current.Items["qs"] = queryString.Substring(0, queryString.Length - 1);
        if (rest == null || rest == "")
        {
            HttpContext.Current.Items["lng"] = language;

            destinationPath = "~/Content.aspx";
            EasyUrlHelper.Current.OriginalPath = destinationPath.Replace("~/", "");

            HttpContext.Current.RewritePath(string.Concat("~/Content.aspx", queryString == "?"));
            return BuildManager.CreateInstanceFromVirtualPath("~/Content.aspx", typeof(Page)) as Page;
        }
        else
        {
            if (rest.EndsWith("aspx"))
            {
                HttpContext.Current.Items["lng"] = language;

                if (!rest.StartsWith("~/"))
                    destinationPath = "~/" + rest;
                else
                    destinationPath = rest;

                EasyUrlHelper.Current.OriginalPath = destinationPath.Replace("~/", "");

                HttpContext.Current.RewritePath(string.Concat(destinationPath, queryString == "?" ? "" : queryString));
                return BuildManager.CreateInstanceFromVirtualPath(destinationPath, typeof(Page)) as Page;
            }

        }

        return BuildManager.CreateInstanceFromVirtualPath("~/404.aspx", typeof(Page)) as Page;
    }
}

Does anyone have an idea ?
Thanks

A: It was a configuration issue. The AppPool was set as v4.0 Integrated while it should have been v2.0 Classic.


text:
Q: Android - chronometer start and stop I want to create a chronometer which I can start and stop with one button. With my code below I just get a nullpointer exception. How can I avoid it, or set the two functions to the button anyway?
public class MainActivity extends ActionBarActivity {
  Chronometer focus;
  Button start, stop, reset;
  long timeElapsed = SystemClock.elapsedRealtime() - focus.getBase();
  int x;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    timeElapsed = x;
    start = (Button) findViewById(R.id.button1);
    focus = (Chronometer) findViewById(R.id.chronometer1);

    start.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if(x == 0){
            focus.start();
            }

            if(x != 0){
            focus.stop();
            }
        }
    });

}

}

A: The problem with your code is this line:
long timeElapsed = SystemClock.elapsedRealtime() - focus.getBase();

Since focus variable has not been initialized you get NullPointer.
You should call getBase() after initialization.
Also, you should use ToggleButton instead of Button for this App.

A: You are using variables before they are initialized. 'focus' and 'x' are used before they are initialized. Use this code instead to avoid nullpointer exception:
     public class MainActivity extends ActionBarActivity {
  Chronometer focus;
  Button start, stop, reset;
  long timeElapsed = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    start = (Button) findViewById(R.id.button1);
    focus = (Chronometer) findViewById(R.id.chronometer1);
    // to get the elapsed time use setonChronometerTickListener
    focus.setOnChronometerTickListener(new OnChronometerTickListener() {
         @Override
         public void onChronometerTick(Chronometer chronometer) {
             timeElapsed = SystemClock.elapsedRealtime() - focus.getBase();
         }
    });
    start.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if(timeElapsed == 0){
            focus.setBase(SystemClock.elapsedRealtime());
            focus.start();
            }

            if(timeElapsed != 0){
        timeElapsed = 0;
            focus.stop();
            }
        }
    });

}


text:
Q: Connect to Azure Analysis Service with Adomd Client via Microsoft Account I'm trying to connect to Azure Analysis Service databases (which isn't owned and managed by me) with Adomd client library.
I can connect to them with Power Query connector using Microsoft account, but I couldn't find the correct connection string to prompt me to login with my Microsoft account then use that credential to connect in Adomd. Using the connection string in here https://learn.microsoft.com/en-us/azure/analysis-services/analysis-services-connect
"Provider=MSOLAP;Data Source=<Azure AS instance name>;"

leads to this error
Authentication failed: User ID and Password are required when user interface is not available?

Is it doable with Adomd client?

A: Turn out pythonnet prevents interactive login. I makes it work by using the client library in C#.


text:
Q: Difference between harmonic mean of arithmetic means and arithmetic mean of harmonic means Let $S=\{(x_i, y_i)\}_{i=1...n} \in [0,1]^{2n}$ bet a tuple of ordered pairs, and let $A, H$ denote the arithmetic and harmonic mean. Then
$$
\sup_S (H(\underset{i}{A}(x_i),\underset{i}{A}(y_i)) - \underset{i}{A}(H(x_i, y_i))) =
  \begin{cases}
   0.5,n\text{ is even}\\
      0.5 - \frac{1}{2n^2},\text{else}
     \end{cases}
$$
We found a proof (Opitz and Burst, 2019: Macro F1 and Macro F1) by showing that the difference can be increased by intelligently swapping variables and then setting them to either 0 or 1.
The proof is fairly long, and we are wondering: Is there a simple way to show this bound?

A: $
\newcommand{\R}{\mathbb{R}}
\newcommand{\la}{\lambda}
\newcommand{\p}{\partial}
\newcommand{\PP}{\mathcal{P}}$
Let $x:=(x_1,\dots,x_n)\in[0,1]^n$, $y:=(y_1,\dots,y_n)\in[0,1]^n$, $h:=(h_1,\dots,h_n)$,
\begin{equation*}
 h_i:=H(x_i,y_i),\quad H(u,v):=\frac2{\frac1u+\frac1v}=\frac{2uv}{u+v}
\end{equation*}
for $u>0$ and $v>0$, and, by continuity, $H(u,v):=0$ for $u\ge0$ and $v\ge0$ with $u v=0$. Let $Az:=\frac1n\sum_1^n z_i$ for $z:=(z_1,\dots,z_n)$. Then the result in question can written as
\begin{equation*}
 L:=L(x,y):=H(Ax,Ay)-Ah\le L^*_n:=
 \left\{
   \begin{alignedat}{2}
   &\frac12&&\text{ if $n$ is even}\\
  & \frac12-\frac1{2n^2}&&\text{ if $n$ is odd},
     \end{alignedat}
     \right. \tag{0}
\end{equation*}
with equality for some $x,y$ in $[0,1]^n$.
The maximum of $L(x,y)$ over all $(x,y)\in[0,1]^n\times[0,1]^n$ is attained. In what follows, let $(x,y)$ be such a maximizer.
With $[n]:=\{1,\dots,n\}$, $p$ and $q$ in $\{0,1\}$, and $|K|:=(\text{cardinality of $K$)}$, let
\begin{gather*}
 I:=\{i\in[n]\colon 0<x_i<1\},\quad J:=\{i\in[n]\colon 0<y_i<1\},\\
 I_p:=\{i\in[n]\colon x_i=p\},\quad J_q:=\{i\in[n]\colon y_i=q\},\\
s_{pq}:=\tfrac1n|I_p\cap J_q|,
\end{gather*}
so that $s_{00}+s_{01}+s_{10}+s_{11}\le1$.
If $Ax=0$, then $x=0$ and hence $h=0$ and $L=0$, which makes the inequality in (0) trivial. So, without loss of generality (wlog), $Ax>0$. Similarly, wlog $Ay>0$. So,
\begin{equation*}
 r:=Ay/Ax\in(0,\infty). \tag{1}
\end{equation*}
Let $\p_u$ denote the partial derivative with respect to a variable $u$.
Then
\begin{equation*}
 \p_u H(u,v)=2\Big(\frac v{u+v}\Big)^2
\end{equation*}
for $u>0$ and $v>0$.
So, for any $i\in I$
\begin{equation*}
 \frac n2\,\p_{x_i}L
 =\Big(\frac r{r+1}\Big)^2-\Big(\frac{y_i}{x_i+y_i}\Big)^2=0,
\end{equation*}
because $(x,y)$ is a maximizer of $L$. So, $y=rx>0$ on $I$. Similarly, $y=rx>0$ on $J$, and hence $y=rx>0$ on $I\cup J$.
So, with $\xi:=\frac1n\,\sum_{i\in I\cup J}x_i$,
\begin{alignat*}{5}
&Ax=&&    &&s_{10}&+&s_{11}&&+\xi, \tag{Ax}\\
&Ay=&&s_{01}&&    &+&s_{11}&&+\xi r, \tag{Ay}\\
&Ah=&&    &&   &&s_{11}&&+\xi\frac{2r}{1+r}.
\end{alignat*}
So,
\begin{align*}
 L&=\frac{2 Ax\,Ay}{Ax+Ay}-Ah \\
 &=Ax\frac{2r}{1+r}-\Big(s_{11}+\xi\frac{2r}{1+r}\Big) \\
 &=(s_{10}+s_{11})\frac{2r}{1+r}-s_{11}. \tag{2}
\end{align*}
It also follows from (Ax) and (Ay) that the equality in (1) can be rewritten as
\begin{equation*}
s_{01}+s_{11}=r(s_{10}+s_{11}).
\end{equation*}
So, if $s_{10}+s_{11}=0$, then $s_{11}=0$ and hence, by (2), $L=0$. So, wlog $s_{10}+s_{11}>0$ and hence
$r=\frac{s_{01}+s_{11}}{s_{10}+s_{11}}$. Using this expression for $r$, we get from (2):
\begin{align*}
 L=M:=\frac{2 s_{01} s_{10} + (s_{01}+ s_{10})s_{11}}{s_{01} + s_{10} + 2 s_{11}}.
\end{align*}
Next,
\begin{equation*}
 \p_{s_{11}}M:=\frac{(s_{01}-s_{10})^2}{(s_{01} + s_{10} + 2 s_{11})^2}\ge0.
\end{equation*}
So, wlog one may replace $s_{11}$ by its largest possible value, $1-s_{01}-s_{10}$:
\begin{equation*}
 L=M\le N:=M|_{s_{11}=1-s_{01}-s_{10}}=
 \frac{(1-s_{01})s_{01}+(1-s_{10})s_{10}}{2-s_{01}- s_{10}}.
\end{equation*}
Further,
\begin{equation*}
 (\p_{s_{01}}+\p_{s_{10}})N=
 \frac{4(1-s_{01})(1-s_{10})}{(2-s_{01}-s_{10})^2}\ge0.
\end{equation*}
So, if we increase $s_{01}$ and $s_{10}$ by the same amount, while keeping $s_{01}+s_{10}\le1$, the value of $N$ may only increase. So,
\begin{equation*}
 L\le N|_{s_{10}=1-s_{01}}=2(1-s_{10})s_{10}
 \le2(1-\tfrac mn)\tfrac mn=L^*_n,
\end{equation*}
where $m:=\lfloor n/2\rfloor$; the latter inequality follows because $(1-u)u$ is decreasing in $|u-1/2|$ for $u\in[0,1]$.
The inequality in (0) turns into the equality if $(x_i,y_i)=(1,0)$ for $i=1,\dots,m$ and $(x_i,y_i)=(0,1)$ for $i=m+1,\dots,n$.
The entire proof is now complete.

A: I will give you a short proof for the even case. I think it may be possible to imitate the steps for $n$ odd.
Restating your problem in a math-olympiad fashion, one has to prove that for $0< x_i,y_i\leq 1$, $1\leq i\leq n$, the following holds:
$$ \frac{1}{n} \cdot \frac{2\left(\sum_{i=1}^n x_i\right) \left(\sum_{i=1}^n y_i\right)}{\left(\sum_{i=1}^n x_i\right) + \left(\sum_{i=1}^n y_i\right)} - \frac{2}{n} \sum_{i=1}^n \frac{x_iy_i}{x_i+y_i} \leq \frac{1}{2}$$
Which in turn, using the inequalities between harmonic and arithmetic means in the first summand, means that it is enough to prove:
$$ \frac{1}{2n} \left(\sum_{i=1}^n x_i + \sum_{i=1}^n y_i\right) - \frac{2}{n} \sum_{i=1}^n \frac{x_iy_i}{x_i+y_i} \leq \frac{1}{2}$$
And this is equivalent to this:
$$ \sum_{i=1}^n (x_i + y_i) - 4 \sum_{i=1}^n \frac{x_iy_i}{x_i+y_i} \leq n$$
Which, rewriting is just to prove:
$$ \sum_{i=1}^n \frac{(x_i-y_i)^2}{x_i+y_i} \leq n$$
And it is sufficient to verify that each summand is $\leq 1$, which is pretty simple given that $(x_i-y_i)^2\leq x_i+y_i$, since this is just equivalent to $x_i^2+y_i^2 \leq x_i+y_i + 2x_iy_i$, and the last inequality follows directly from the fact that $x_i^2\leq x_i$ and $y_i^2\leq y_i$, for $x_i,y_i\in [0,1]$.
Interestingly, the case of equality is straightforward to construct, since we only need that $(x_i-y_i)^2= x_i+y_i$ which is easy to see only can happen for $x_i=1$ and $y_i=0$ or viceversa, and that $\sum x_i = \sum y_i$.


text:
Q: Problems with overflow-x:hidden; in Chrome & Firefox I'm having issues with overflow-x:hidden. I realize there are quite a few posts about this topic, but none of them quite address my issue specifically, and none of the solutions from the already-posted issues have worked. So, I'm posting yet another "overflow:hidden;" question ...
I have a full-width (fixed) nav bar, and a full-screen slideshow at the top of my page. The rest of the content follows in a pretty straightforward manner (or so I think). There are fixed elements elsewhere on the page, and I've set the body to overflow-x:hidden; to prevent awkward overlapping on page resize.
The thing is, in Chrome and Firefox, I am still able to scroll L and R with the trackpad. No good.
I have rebuilt my page, as well as spent loads of time with developer tools, hiding, removing, and changing the position of various elements. I've tried adding overflow-x:hidden; to my .wrapper; this works OK, but still allows for some amount of sideways scrolling. I have also tried setting scrollLeft(0), as was suggested in this post here. I cannot figure out:
A) why overflow-x isn't working, and
B) where my overflowing content is coming from (at glance and with dev. tools, everything appears to be well-contained).
As I'm not sure precisely what's causing this issue, I can't include a neat JSFiddle snippet. The full (static) site is here: [edited, no longer necessary]

A: You would have to rebuild your page with a boxmodel, using css classes or a library to achieve a good grid system. Fixed elements are never a good option.  The mentioned boxmodel grid can be customized for mobile usage depending on the min-width and max-width using media queries in css.

A: This isn't the most attractive option, but if the overflow-x: hidden; isn't working, it may do for a temporary fix while you work out the real problem:
http://jsfiddle.net/YWnpM/
$(window).on('scroll', function() {
    $(this).scrollLeft(0); //sets left scroll to 0px
});
(I see that you said that you tried this, but it depends how you implemented it - if you did so out side of the event handler then it won't have worked.)

A: I would just expand upon @advert2013's answer with trying to prevent excess scrolling:
$(window).scroll(function (e) {
    var $target = $(e.target);
    if ($target.scrollLeft() != 0) {
        $target.scrollLeft(0);
    }
});


text:
Q: Dynamic Tabs Using Treeview I am Developing a Web Application. I need Help i have Split the Page into to Two Parts one for TreeView(Menu) and other part to display Menu Pages in Tabs.
So I need help in creating a Treeview Menu with Dynamic Tabs based on the Tree Node Selected. Please Help


text:
Q: How to get some CAN address messages with ELM327 I'm trying to get some CAN messages with ELM327.
But I couldn't handle it.
Please let me know about ELM327's AT command.
For example, How can I get only 1AA and 2BB address messages?
I coudn't understand AT CF & CM command.
I tried below command but ELM327 recieved many other address data.
"AT CF 1AA"
"AT CF 2BB"
"AT MA"

A: All of this is documented in the ELM327 AT command manual. You will need to figure out the bit mask and the filter of addresses you want to allow and set those with ATCF and ATCM respectively. For example:
Mask Value: 0b11111111110 (0x03FE)
Filter Value: 0b11111111111 (0x03FF)
The Rx buffer will receive CAN frames with an Id of 0x03FE or 0x03FF as bit 0 of the filter bit is disabled.

More examples can be found at https://www.microchip.com/forums/m318430.aspx.


text:
Q: Align all the strings in proper way using String.format java I am creating a file by appending all the strings in StringBuilder and then dumping it in a file. But when I check the file (which is obvious) all my strings in each line is not properly align..
Below is the code called by upper layer by passing all the necessary stuff.
  private static StringBuilder appendStrings(String pro, List<ProcConfig> list,
      StringBuilder sb) {
    for (ProcConfig pc : list) {
      sb.append(pro).append(" ").append(pc.getNo()).append(" ").append(pc.getId())
          .append(" ").append(pc.getAddress()).append(" ").append(pc.getPort()).append(" ")
          .append(pc.getNumPorts()).append(" ").append(pc.getName())
          .append(System.getProperty("line.separator"));
    }
    sb.append(System.getProperty("line.separator"));
    return sb;
  }

And here is how sample lines look like from the above code. After each new line, there is a new set so I want to align all the lines properly in each set before each new line.
config 51 106 10.178.151.25 8095 5 tyt_87612nsas_woqa_7y2_0
config 51 104 10.124.192.124 8080 5 tyt_abc_pz1_rn03c-7vb_01

if_hello_abc_tree tyt.* then process_is_not_necessary 32 80 10.86.25.29 9091 5 tyt_goldenuserappslc22
if_hello_abc_tree tyt.* then process_is_not_necessary 51 50 10.174.192.209 9091 5 tyt_goldenuserapprno01

if_hello_abc_tree tyt.* then config 4 140 10.914.198.26 10001 1 silos_lvskafka-1702600
if_hello_abc_tree tyt.* then config 4 184 10.444.289.138 10001 1 silos_lvskafka-1887568

Is there any way I can align each of the above line properly? So output should be like this:
config 51 106 10.178.151.25  8095 5 tyt_87612nsas_woqa_7y2_0
config 51 104 10.124.192.124 8080 5 tyt_abc_pz1_rn03c-7vb_01

if_hello_abc_tree tyt.* then process_is_not_necessary 32 80 10.86.25.29    9091 5 tyt_goldenuserappslc22
if_hello_abc_tree tyt.* then process_is_not_necessary 51 50 10.174.192.209 9091 5 tyt_goldenuserapprno01

if_hello_abc_tree tyt.* then config 4 140 10.914.198.26  10001 1 silos_lvskafka-1702600
if_hello_abc_tree tyt.* then config 4 184 10.444.289.138 10001 1 silos_lvskafka-1887568

Update:
Below is how it is getting generated now. As you can see on IP Address it is slightly off if you compare the two lines.
config 51 106   97.143.765.65 8095 5 abc_tyewaz1_rna03c-7nhl_02
config 51 104  97.143.162.184 8080 5 abc_tyewaz1_rna03c-7vjb_01

Instead can we generate like below? Basically making each column straight. Is this possible to do?
config 51 106  97.143.765.65  8095 5 abc_tyewaz1_rna03c-7nhl_02
config 51 104  97.143.162.184 8080 5 abc_tyewaz1_rna03c-7vjb_01

A: First of all: I'm not a java developer, but I know a little about it. I know this is not the best way to solve your problem but you'll get the point.
Instead of calling append method multiple times use a Formatter and loop through it like this:
private static StringBuilder appendStrings(String pro, List<ProcConfig> list, StringBuilder sb) {
    Formatter formatter = new Formatter(sb);
    String template ="";
    for (ProcConfig pc : list) {
        if (pro.length() == 6)
            template = "%-6s %d %3d %-15s %d %d %s %n";
        else if (pro.length() > 35)
            template = "%-53s %d %3d %-15s %d %d %s %n";
        else
            template = "%-35s %d %3d %-15s %d %d %s %n";
        formatter.format(template, pro, pc.getNo(), pc.getId(), pc.getAddress(), pc.getPort(), pc.getNumPorts(), pc.getName());
    }
    formatter.close();
    return sb;
}

Because pro is in different length you could change the template to a proper one for each pro.
Note: Don't forget to import java.util.Formatter.
You can use format specifiers to specify the way the data is formatted. This is a list of common formatters:
%S or %s: Specifies String
%X or %x: Specifies hexadecimal integer
%o: Specifies Octal integer
%d: Specifies Decimal integer
%c: Specifies character
%T or %t: Specifies Time and date
%n: Inserts newline character
%B or %b: Specifies Boolean
%A or %a: Specifies floating point hexadecimal
%f: Specifies Decimal floating point

As I said before in comments The dash means the first string is left justified and every string will append after number of chars defined in template, so try to find the best number that suites your needs.
To learn more about formatter take a look at here and here.


text:
Q: Chrome (and Chromium) on Ubuntu 16.04 isn't opening downloads and doesn't show upload prompt I'm using Chrome (but Chromium has the same issue). I'm not a power user, so don't know how to debug this.
When I click on any link to download anything it updates the launchbar icon (I have a number in circle indicating how many files it's "downloading", and I have a progress bar for it) but nothing else happens.. for a time.
After some time (sometimes 2h sometimes 5h, sometimes never tho..) it downloads it all.
The same with uploads - I click on the upload button.. nothing happens, then it happens all in same time - both downloads are ready, and I have n number of open upload prompts (where n ==  the number of times I clicked upload button somewhere ;-) even when the tabs are already closed ).
I have a SLI conf, with 2x 980Ti. I have 3 monitors. I have some other issues, that may be related, like: when I log in I have wrong desktops configuration, after 10-15s it flickers and it's how I set it up.
I'm using nVidia proprietary 375.39 drivers now (changed couple of days ago from Nouveau - where I had the same problem).
Sometimes when the system loads I have compiz error popping up.

*

*As I wrote above, I'm not a power user, so please let me know how can
I get you more info on this problem to debug it.

Weird thing is that I have an Intel Stick Media Center with Ubuntu 16.04 and it has the same problem. I've tried deleting/changing extensions - now I only have OneTab, GetPocket, RescueTime.
I think it's something on the connection between triggering and event and unity reacting to it? Been dealing with it for couple of weeks.
TIA!


text:
Q: Join query on Mongo I have the following collections:
Patterns: {idPattern, name, description}
SelectedPatterns: {user, idPatterns}

I am trying to do a query that retrieves all the pattern info (idPattern, name, description) for a given set of users. For instance, imagine the database info is as follows:
Patterns:

{"idPattern":1, "name":"name1","description":"desc1"}
{"idPattern":2, "name":"name2","description":"desc2"}
{"idPattern":3, "name":"name3","description":"desc3"}
{"idPattern":4, "name":"name4","description":"desc4"}

SelectedPatterns:

{"user":"user1", "idPatterns":[1,2]}
{"user":"user2", "idPatterns":[2,3]}

The result of the query for user1 should look something like this this:
[{"idPattern":1, "name":"name1","description":"desc1"},
{"idPattern":2, "name":"name2","description":"desc2"}]

I know how to do this with some Python logic and two Mongo queries but this is quite inefficient, so my question is, could this information be retrieved with a single Mongo query?

A: You should use the $lookup operator to achieve this.
Below query will be helpful:
db.SelectedPatterns.aggregate([
  {
    $match: {
      user: "user1"
    }
  },
  {
    $lookup: {
      from: "Patterns",
      localField: "idPatterns",
      foreignField: "idPattern",
      as: "pattern_details"
    }
  },
  {
    $unwind: "$pattern_details"
  },
  {
    $replaceRoot: {
      newRoot: "$pattern_details"
    }
  },
  {
    $project: {
      _id: 0
    }
  }
])

MongoPlayGroundLink


text:
Q: Dropdown menu Isnt Working when i click a button

<button class="dropdownbutton">Select Algorithm

Link 1

Link 2

Link 3

              </button>

I'm Trying to Use a button and when i click the button it should open a dropdown menu but I'm Unable to Do it. Button Click is Happening but the Dropdown menu is not working.
Help Needed

A: you can use a simole code with js and css like this :
------------------------- Css Code-----------------------
    .dropdown-content {
        display: none;
    }

    .dropdown-content.show {
        display: block;
    }

------------------------ HTML Code ------------------------

    <button class="dropdownbutton" onclick="showDropDown()">Select Algorithm
    </button>

Link 1

Link 2

Link 3

------------------------- JS Code-----------------------
    function showDropDown() {
        let drp = document.querySelector('.dropdown-content');
        drp.classList.contains('show') ?
            document.querySelector('.dropdown-content').classList.remove("show") :
            document.querySelector(
                '.dropdown-content').classList.add("show")
    }


text:
Q: Foreign keys vs partitioning Since foreign keys are not supported by partitioned mySQL databases for the moment, I would like to hear some pro's and con's for a read-heavy application that will handle around 1-400 000 rows per table. Unfortunately, I dont have enough experience yet in this area to make the conclusion by myself...
Thanks a lot!
References:
How to handle foreign key while partitioning
Partitioning mySQL tables that has foreign keys?

A: Well, if you need partitioning for a table as small as 400.000 rows get another database than MySQL. Seriously. By modern standards any table below 1.000.000 rows is normally neglegible in size (not even small), unless you also dont have any index etc. And modern standards are about 10 years old in this regard.

A: Well, partition is not a good solution for complicate data model.  If you only have 2 to 3 tables depending on each other, you may be able to do it but it is not pretty.  Each table must have an column that determine the partition.  Then, each table must have a trigger to create the new table, set the foreign key and unique constraint.
For example,
audittransaction<- auditentry
Each audittransactionhas 0 to n auditentry.  table auditentry contains the foreign key of transaction.  Both table have to have column creationDate since it is used for partition both tables.
------ create a trigger to insert audittransaction within the trigger
create or replace function audittransaction_insert_function()
returns trigger as $$
DECLARE

    tablepartition varchar;
    tablename varchar;
    startbounds timestamp;
    endbounds timestamp;

BEGIN
    tablepartition :=  to_char(date_trunc('month', NEW.whendone), 'YYYYMMDD');
    tablename := 'audittransaction_' || tablepartition ;

    if not exists(select * from information_schema.tables where table_name = tablename) then
        startbounds := date_trunc('month', NEW.whendone);
        endbounds := startbounds + cast('1 months' as interval);
        execute 'create table ' || tablename || ' ( CHECK (whendone >= ' || quote_literal(startbounds) || ' and whendone < ' || quote_literal(endbounds)|| ') ) inherits (audittransaction)';
        execute 'ALTER TABLE '||  tablename ||' ADD CONSTRAINT '||tablename||'_unique_id UNIQUE (id)';
    end if;
    execute 'insert into ' || tablename || ' (id, operationid, whendone, "comment", ticketid ,transactionid, userid )  values (' || quote_literal(NEW.id) || ',' || quote_literal(NEW.operationid) || ',' || quote_literal(NEW.whendone) || ')';
    return null;
END; $$
LANGUAGE plpgsql;

create trigger insert_audittrans

----- then, create a trigger for autientry
create or replace function auditentry_insert_function()
returns trigger as $$
DECLARE
    tablepartition varchar;
    tablename varchar;
    startbounds timestamp;
    endbounds timestamp;

BEGIN
    tablepartition :=  to_char(date_trunc('month', NEW.transactiontimestampgmt), 'YYYYMMDD');
    tablename := 'auditentry_' || tablepartition ;

    if not exists(select * from information_schema.tables where table_name = tablename) then
        startbounds := date_trunc('month', NEW.transactiontimestampgmt);
        endbounds := startbounds + cast('1 months' as interval);
        execute 'create table ' || tablename || ' ( CHECK (transactiontimestampgmt >= ' || quote_literal(startbounds) || ' and transactiontimestampgmt < ' || quote_literal(endbounds)|| ') ) inherits (auditentry)';
        execute 'ALTER TABLE '||  tablename ||' ADD CONSTRAINT '||tablename||'_unique_id UNIQUE (id)';
        execute 'ALTER TABLE ' || tablename ||' ADD CONSTRAINT auditentry FOREIGN KEY (audit_transaction_id) REFERENCES audittransaction_'||tablepartition ||'(id)';
    end if;
    execute 'insert into ' || tablename || ' (id, audit_transaction_id, eventid, transactiontimestampgmt,timestampgmt, acknowledged, resolved, acknowledgedbyusername, acknowledgeddate,  notificationlevel, resolvedbyusername, resolveddate, severity,  parentauditentry_id )  values (' || quote_literal(NEW.id) || ',' || quote_literal(NEW.audit_transaction_id) || ',' || quote_literal(NEW.eventid) || ','||quote_literal(NEW.transactiontimestampgmt)||')';
    return null;
END; $$
LANGUAGE plpgsql;

create trigger insert_auditentry before insert on auditentry for each row execute procedure auditentry_insert_function();


text:
Q: Search form to submit query to external site I would like to be able to type a search phrase into an input box, click send, and have a tab open to a new site where the address is something like http://externalsite.com/?q=SEARCH_PHRASE.
Is there a way to provide this functionality using PHP? I'm trying to avoid using javascript.

A: Don't even need PHP, just standard HTML.
<form method=get action="http://externalsite.com" target="_blank">
<input type=text name=q value="">
<input type=submit value="lets go">
</form>

A: <form  action="http://www.externalsite.com" target="_blank">
<input type=text name=q value="">
<input type=submit value="lets go">
</form>


text:
Q: How to store the value of index not the array itself in mysql query? I need to be able to check if certain values are present in title_id, but as title_id's are index's it won't allow me to do this. Is there a way to store the values of the index without storing the array itself?
I have been searching for this answer for a long time but anything I search pulls up answers to different questions.
$selects = (array) null;
$res = mysqli_query($datab, "SELECT title_id FROM selects") or die($datab->error);

while ($datab = mysqli_fetch_assoc($res)) {
    $selects[] = $datab;
}

///////////// part of a later query
  if (!in_array($thisid, $selects)) {
            $title[] = $datab;
            $j++;
        }

A: $selects is array of arrays, not array of title_id.
Try something like that:
while ($datab = mysqli_fetch_assoc($res)) {
    $selects[] = $datab['title_id'];
}


text:
Q: Proguard, library class depends on program class I'm running proguard to release an Android project, there are tons of warning about library class depends on program class. However, they seems not correctly spotted.
For example, the first one on the below list: both classes are library classes. I already specified
-injars  myproject/libs

Any tip to solve this? Thanks.
Warning: library class org.apache.http.impl.client.AbstractHttpClient depends on program class org.apache.http.HttpRequest
Warning: library class org.apache.http.impl.client.AbstractHttpClient depends on program class org.apache.http.HttpResponse
Warning: library class org.apache.http.impl.client.AbstractHttpClient depends on program class org.apache.http.HttpHost
Warning: library class org.apache.http.impl.client.AbstractHttpClient depends on program class org.apache.http.HttpRequest
Warning: library class org.apache.http.impl.client.AbstractHttpClient depends on program class org.apache.http.protocol.HttpContext
Warning: library class org.apache.http.impl.client.AbstractHttpClient depends on program class org.apache.http.HttpResponse
Warning: library class org.apache.http.impl.client.AbstractHttpClient depends on program class org.apache.http.protocol.HttpRequestExecutor
Warning: library class org.apache.http.impl.client.AbstractHttpClient depends on program class org.apache.http.ConnectionReuseStrategy
Warning: library class org.apache.http.impl.client.AbstractHttpClient depends on program class org.apache.http.protocol.HttpProcessor
Warning: library class org.apache.http.impl.client.AbstractHttpClient depends on program class org.apache.http.params.HttpParams
Warning: library class org.apache.http.impl.client.AbstractHttpClient depends on program class org.apache.http.HttpRequest
Warning: library class org.apache.http.impl.client.AbstractHttpClient depends on program class org.apache.http.params.HttpParams
Warning: library class org.apache.http.impl.client.AbstractHttpClient depends on program class org.apache.http.protocol.HttpContext
Warning: library class org.apache.http.impl.client.AbstractHttpClient depends on program class org.apache.http.HttpHost
Warning: library class org.apache.http.impl.client.AbstractHttpClient depends on program class org.apache.http.HttpRequest
Warning: library class org.apache.http.impl.client.AbstractHttpClient depends on program class org.apache.http.HttpHost
Warning: library class org.apache.http.impl.client.AbstractHttpClient depends on program class org.apache.http.HttpRequest
Warning: library class org.apache.http.impl.client.AbstractHttpClient depends on program class org.apache.http.protocol.HttpContext
Warning: library class org.apache.http.impl.client.DefaultHttpClient depends on program class org.apache.http.params.HttpParams
Warning: library class org.apache.http.impl.client.DefaultHttpClient depends on program class org.apache.http.params.HttpParams
Warning: library class org.apache.http.impl.client.DefaultHttpClient depends on program class org.apache.http.params.HttpParams
Warning: library class org.apache.http.impl.client.DefaultHttpClient depends on program class org.apache.http.protocol.HttpRequestExecutor
Warning: library class org.apache.http.impl.client.DefaultHttpClient depends on program class org.apache.http.protocol.HttpContext
Warning: library class org.apache.http.impl.client.DefaultHttpClient depends on program class org.apache.http.ConnectionReuseStrategy
Warning: library class org.apache.http.impl.client.DefaultHttpClient depends on program class org.apache.http.protocol.BasicHttpProcessor


text:
Q: Simple $S$-matrix example in Coleman's lectures on QFT In Coleman's QFT lectures, I'm confused by equation 7.57. To give the background, Coleman is trying to calculate the scattering matrix (S matrix) for a situation in which the Hamiltonian is given by
$$H=H_{0}+f\left(t,T,\Delta\right)H_{I}\left(t\right)$$
where $H_{0}$ is the free Hamiltonian, $H_{I}$ is the interaction, and $f$ is a function that turns the interaction on only for a time interval $T$ around $t=0$. $\Delta$ determines the rate at which the interaction is switched on and off.
Since the interaction is off for times in the distant past and future, the state at these times will be the exact state determined by the free Hamiltonian $H_{0}$. Coleman calls this state (for the distant past) $\left|\psi\left(-\infty\right)\right\rangle ^{\text{in}}$ and claims that it is given by
$$\left|\psi\left(-\infty\right)\right\rangle ^{\text{in}}=\lim_{t^{\prime}\rightarrow-\infty}e^{iH_{0}t^{\prime}}e^{-iHt^{\prime}}\left|\psi\right\rangle =\lim_{t^{\prime}\rightarrow-\infty}U_{I}\left(0,t^{\prime}\right)\left|\psi\right\rangle $$
where $U_{I}$ is the evolution operator in the interaction picture. He doesn't specify what the state $\left|\psi\right\rangle$ is, but I can't make sense of this equation no matter what I assume about it. Is it the state in the Schrodinger picture or the interaction picture? What time is the state supposed to be at?
If it's the Schrodinger picture (as seems to be the case, as he says this when calculating $S$ in equation 7.59) and the time is $t=0$, then the $e^{-iHt^{\prime}}$ operator would evolve the state to time $t^{\prime}$, but then what is the additional $e^{iH_{0}t^{\prime}}$ for?
Finally, how does he get the last equality above? According to Coleman's definition of $U_{I}$ (his equation 7.31) we should have
$$U_{I}\left(t,0\right)=e^{iH_{0}t}e^{-iHt}$$
where the $t$ and the 0 are swapped from its occurrence in the above equation.
Anyone have any thoughts?


text:
Q: When is a started service not a started service? (SQL Express) We require programmatic access to a SQL Server Express service as part of our application. Depending on what the user is trying to do, we may have to attach a database, detach a database, back one up, etc. Sometimes the service might not be started before we attempt these operations. So we need to ensure the service is started. Here is where we are running into problems. Apparently the ServiceController.WaitForStatus(ServiceControllerStatus.Running) returns prematurely for SQL Server Express. What is really puzzling is that the master database seems to be immediately available, but not other databases. Here is a console application to demonstrate what I am talking about:
namespace ServiceTest
{
    using System;
    using System.Data.SqlClient;
    using System.Diagnostics;
    using System.ServiceProcess;
    using System.Threading;

    class Program
    {
        private static readonly ServiceController controller = new ServiceController("MSSQL$SQLEXPRESS");
        private static readonly Stopwatch stopWatch = new Stopwatch();

        static void Main(string[] args)
        {
            stopWatch.Start();

            EnsureStop();
            Start();
            OpenAndClose("master");

            EnsureStop();
            Start();
            OpenAndClose("AdventureWorksLT");

            Console.ReadLine();
        }

        private static void EnsureStop()
        {
            Console.WriteLine("EnsureStop enter, {0:N0}", stopWatch.ElapsedMilliseconds);

            if (controller.Status != ServiceControllerStatus.Stopped)
            {
                controller.Stop();
                controller.WaitForStatus(ServiceControllerStatus.Stopped);
                Thread.Sleep(5000); // really, really make sure it stopped ... this has a problem too.
            }

            Console.WriteLine("EnsureStop exit, {0:N0}", stopWatch.ElapsedMilliseconds);
        }

        private static void Start()
        {
            Console.WriteLine("Start enter, {0:N0}", stopWatch.ElapsedMilliseconds);
            controller.Start();
            controller.WaitForStatus(ServiceControllerStatus.Running);
            // Thread.Sleep(5000);
            Console.WriteLine("Start exit, {0:N0}", stopWatch.ElapsedMilliseconds);
        }

        private static void OpenAndClose(string database)
        {
            Console.WriteLine("OpenAndClose enter, {0:N0}", stopWatch.ElapsedMilliseconds);
            var connection = new SqlConnection(string.Format(@"Data Source=.\SQLEXPRESS;initial catalog={0};integrated security=SSPI", database));
            connection.Open();
            connection.Close();
            Console.WriteLine("OpenAndClose exit, {0:N0}", stopWatch.ElapsedMilliseconds);
        }
    }
}

On my machine, this will consistently fail as written. Notice that the connection to "master" has no problems; only the connection to the other database. (You can reverse the order of the connections to verify this.) If you uncomment the Thread.Sleep in the Start() method, it will work fine.
Obviously I want to avoid an arbitrary Thread.Sleep(). Besides the rank code smell, what arbitary value would I put there? The only thing we can think of is to put some dummy connections to our target database in a while loop, catching the SqlException thrown and trying again until it works. But I'm thinking there must be a more elegant solution out there to know when the service is really ready to be used. Any ideas?
EDIT: Based on feedback provided below, I added a check on the status of the database. However, it is still failing. It looks like even the state is not reliable. Here is the function I am calling before OpenAndClose(string):
private static void WaitForOnline(string database)
{
    Console.WriteLine("WaitForOnline start, {0:N0}", stopWatch.ElapsedMilliseconds);

    using (var connection = new SqlConnection(string.Format(@"Data Source=.\SQLEXPRESS;initial catal
    using (var command = connection.CreateCommand())
    {
        connection.Open();

        try
        {
            command.CommandText = "SELECT [state] FROM sys.databases WHERE [name] = @DatabaseName";
            command.Parameters.AddWithValue("@DatabaseName", database);

            byte databaseState = (byte)command.ExecuteScalar();
            Console.WriteLine("databaseState = {0}", databaseState);
            while (databaseState != OnlineState)
            {
                Thread.Sleep(500);
                databaseState = (byte)command.ExecuteScalar();
                Console.WriteLine("databaseState = {0}", databaseState);
            }
        }
        finally
        {
            connection.Close();
        }
    }

    Console.WriteLine("WaitForOnline exit, {0:N0}", stopWatch.ElapsedMilliseconds);
}

I found another discussion dealing with a similar problem. Apparently the solution is to check the sys.database_files of the database in question. But that, of course, is a chicken-and-egg problem. Any other ideas?

A: Service start != database start.
Service is started when the SQL Server process is running and responded to the SCM that is 'alive'. After that the server will start putting user databases online. As part of this process, it runs the recovery process on each database, to ensure transactional consistency. Recovery of a database can last anywhere from microseconds to whole days, it depends on the ammount of log to be redone and the speed of the disk(s).
After the SCM returns that the service is running, you should connect to 'master' and check your database status in sys.databases. Only when the status is ONLINE can you proceed to open it.


text:
Q: RUN command not called in Dockerfile Here is my Dockerfile:
# Pull base image (Ubuntu)
FROM dockerfile/python

# Install socat
RUN \
  cd /opt && \
  wget http://www.dest-unreach.org/socat/download/socat-1.7.2.4.tar.gz && \
  tar xvzf socat-1.7.2.4.tar.gz && \
  rm -f socat-1.7.2.4.tar.gz && \
  cd socat-1.7.2.4 && \
  ./configure && \
  make && \
  make install

RUN \
  start-stop-daemon --quiet --oknodo --start --pidfile /run/my.pid --background --make-pidfile \
  --exec /opt/socat-1.7.2.4/socat PTY,link=/dev/ttyMY,echo=0,raw,unlink-close=0 \
  TCP-LISTEN:9334,reuseaddr,fork

# Define working directory.
WORKDIR /data

# Define default command.
CMD ["bash"]

I build an image from this Dockerfile and run it like this:
docker run -d -t -i myaccount/socat_test

After this I login into the container and check if socat daemon is running. But it is not. I just started playing around with docker. Am I misunderstanding the concept of Dockerfile? I would expect docker to run the socat command when the container starts.

A: You are confusing RUN and CMD. The RUN command is meant to build up the docker container, as you correctly did with the first one. The second command will also executed when building the container, but not when running it. If you want to execute commands when the docker container is started, you ought to use the CMD command.
More information can be found in the Dockerfile reference. For instance, you could also use ENTRYPOINT in stead of CMD.


text:
Q: Why does autorouter revert to 98% after reaching 100%? I managed to route an entire complex board with eagle, or so I thought. At first it worked. Then I began adding large fills (ground planes and VCC planes) in order to minimize impedance.
I now added extra circuitry to my board and manually routed those parts in place.
I now run the autorouter one more time and watched the progress. In all optimize stages, it showed 100% which made me think everything went perfectly. Then after it was done, it reverted back to 98% (1 unrouted wire left).
I turned off the copper layer on the board as well as the grid and I couldn't see where this unrouted wire is and I even zoomed in.
Is this a bug that exists in eagle when I define multiple planes close to each other? or is there some other trick I can use so eagle can stay at 100% instead of reverting to 98%?

A: Ok so I figured crazy eagle. Yes I'm using 4.16 which is old, but I found the trick.
Even though the part pad is on the correct track, there is a bug in Eagle which won't correctly autoroute the part is the track is previously made.
So the answer is to move the part so the pads do NOT touch any of the existing tracks then run the autorouter then it will complete that track.


text:
Q: Editing "In:" expression in references Overleaf I'm trying to put in italic the expression "In:" in references, regarding "@incollection" e "@inbook" reference types, but I have no idea how to do this. Does anyone have a guess about how to do this? I'm using the abntex2cite package to manage my references, and Overleaf to edit my work.
Thank you


text:
Q: Split end-of-month data into weeks Would like to split monthly data into weeks. Here is the code tried:
import pandas as pd
import datetime

d = {'By' : pd.Series(pd.date_range('20171030', periods=2, freq='M')),
     'Qty': pd.Series([100,200], index=range(2))}
df = pd.DataFrame(d)
df.resample('W').sum()

...gives me

Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex' error.

Looking to split the _Qty_ value by _Sundays_
Know how to get a date_range by using:
dates = pd.DataFrame(pd.date_range(min(df.By), max(df.By), freq="W-Sun"), columns=['Week'])

...but don't know how to generate the split.

A: As indicated in the exception, pd.DataFrame.resample requires that you have some type of a datetime index; currently, your datetime values are in your column 'By'. Move said column to your DataFrame's index, and the resampling works as expected:
df.set_index('By').resample('W-Sun').sum()
#               Qty
# By
# 2017-11-05  100.0
# 2017-11-12    NaN
# 2017-11-19    NaN
# 2017-11-26    NaN
# 2017-12-03  200.0

A: Question was answered in the following #46579271


text:
Q: Object is a field but used like a type? I'm trying to bind data to a form, but I keep getting the following error:
AbDesktop.FrmCreditCards.tmpData is a 'field' but is used like a 'type'.
this is the code causing the error, any and all help would be appreciated.
public partial class FrmCreditCards : Form
    {
        tmpCreditCardData tmpData = new tmpCreditCardData() { CreditCardName = "Reece" };
        private HotelConferenceEntities db = new HotelConferenceEntities();
        private tblCreditCard databaseAccessObject;
        private tmpData dataTransferObject;

        public void databinding()
        {
            // Create forward map using AutoMapper - from database to dataTransfer
            AutoMapper.Mapper.CreateMap<tblCreditCard, tmpData>()
                .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.CreditCardName));

            // Create reverse map using AutoMapper - from dataTransfer to database
            AutoMapper.Mapper.CreateMap<tmpData, tblCreditCard>()
                .ForMember(dest => dest.CreditCardName, opt => opt.MapFrom(src => src.Name));

        }

A: The generic parameters of CreateMap are the problem.
You have to use the type tmpCreditCardData instead of the variable name tmpData as the compilation error says.
        // Create forward map using AutoMapper - from database to dataTransfer
        AutoMapper.Mapper.CreateMap<tblCreditCard, tmpCreditCardData>()
            .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.CreditCardName));

        // Create reverse map using AutoMapper - from dataTransfer to database
        AutoMapper.Mapper.CreateMap<tmpCreditCardData, tblCreditCard>()
            .ForMember(dest => dest.CreditCardName, opt => opt.MapFrom(src => src.Name));

A: You're using the same name for type and field - rename the field tmpData to something else - ie:
    tmpCreditCardData tmpData2 = new tmpCreditCardData
      { CreditCardName = "Reece" };

There were some comments about conventions - convention specifies classes should start with upper case letter and be named like
MyFavouriteClass

and fields should be named like
myFavouriteField

(it starts with lower case letter)
Someone also distinguish private fields with underscore
private MyFavouriteClass _myFavouriteField

If you stick with them you shouldn't run into this problem.


text:
Q: Computing array values based on their index using Julia Broadcasting in julia I want to compute an array such that a[i,1] = (l*i)/k where l and k are constant scalar values and i is the row number. Obvious solution would be to loop through all the i values and add the values, but I want to use Julia Broadcasting on this and I cannot find any documentation on this.
EDIT: a is a two-dimensional array of zeros.

A: Initializing:
jl> a = zeros(5, 2);

jl> k, l = 3, 2π;

You have several choices here. For ordinary arrays, this will work:
jl> a[:, 1] .= l .* (1:size(a, 1)) ./ k
5-element view(::Matrix{Float64}, :, 1) with eltype Float64:
  2.0943951023931953
  4.1887902047863905
  6.283185307179586
  8.377580409572783
 10.471975511965978

This one is more general, and actually preferable in my view:
jl> a[:, 1] .= l .* axes(a, 1) ./ k

For a little more context on axes(a, n), it is a generic way to get the indices of any (or all) dimensions of an array. axes(a, 1) returns Base.OneTo(5), which, if you collect it (don't do that, btw) is
jl> collect(axes(a, 1))
5-element Vector{Int64}:
 1
 2
 3
 4
 5

Without a dimension argument you get all dimensions, two in this case:
jl> axes(a)
(Base.OneTo(5), Base.OneTo(2))

axes is preferable to 1:size(a, 1) because it also works for arrays with zero-based or other kinds of indices.


text:
Q: How to Insert multiple dataline from a Php form to database I am new to Php and what I would like to do is input multiple lines of data into a database through a Php form textfield. The code I have used now is.
 for($n=0;$n<5;$n++) {
      if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
         $insertSQL = sprintf("INSERT INTO cmsd1 (Population_Name) VALUES (%s)",
                           GetSQLValueString($_POST['Form1'], "text"));

         mysql_select_db($database_cmsdtest, $cmsdtest);
         $Result1 = mysql_query($insertSQL, $cmsdtest) or die(mysql_error());

         $insertGoTo = "ttt.php";
     }
 }

However as you can see, all it does is loop the data I have given 5 times.  I got a suggestion to use 'implode' function but as I am new, I have no clue on how to do it. I use Dreamweaver for help with my PhP. I would ideally like this code to loop as many times as the data entered is and not just 5.. Each data point is separated by a space. It could be 100 too. Please advice.
Tried imploding this way but doesn't work..
 GetSQLValueString(implode(" ",$_POST['form1']), "text"));

A: Hope this help and i hope this is what you need: Else please clarify your question further
//if your form name  is = 'frm1'
//if textfield name is ='textfieldname'
// when u submit the form then in php you have the form values in
// $_REQUEST['textfieldname']
    foreach($_REQUEST['textfieldname']  as $value){
    //put your code here
     $insertSQL = sprintf("INSERT INTO cmsd1 (Population_Name) VALUES (%s)",
                           GetSQLValueString($value, "text"));

    //put your code here
    }

A: if the below code is not helping then put your code in pastebin then only i can figure out where are you wrong.
//let the values are like $valesstring = " val1 val2 val3 val4";
//convert them into an array of values with $valuearray = explode(" ",$valesstring);
//then i think u know how to loop the array and put them in text field.
//if your form name  is = 'frm1'
//if textfield name is ='textfieldname'
// when u submit the form then in php you have the form values in
// $_REQUEST['textfieldname']

//do var_dump($_REQUEST['textfieldname']) and check if it got textfield values array
    foreach($_REQUEST['textfieldname']  as $key => $value){
      //print($key."--".$value); to check if u got the values
    //put your code here
     $insertSQL = sprintf("INSERT INTO cmsd1 (Population_Name) VALUES (%s)",
                           GetSQLValueString($value, "text"));

    //put your code here
    }


text:
Q: rake sunspot:solr:reindex not working in Rails 4 app with multiple engines I have rails 4 beta1 application with multiple engines. I've installed sunspot_rails gem /2.0.0.pre.130115/ in my host application. Most of my models lived in engine1. I used them on other engines. After I installed sunspot_rails, using rake sunspot:solr:run I got command/task not found. According to documentation I found a solution. Here is the link: https://github.com/sunspot/sunspot/wiki/Adding-Sunspot-search-to-Rails-in-5-minutes-or-less
After I created a new record Solr found it in a search. But when I reindexed my data, old records were still not found through a search. In my opinion reindex has not worked. I've tried stopping and restarting solr server, restarted my pc few times but no luck. Any idea?
If you need more info let me know.
Here are my gems:
Gems included by the bundle:
  * actionmailer (4.0.0.beta1)
  * actionpack (4.0.0.beta1)
  * activemodel (4.0.0.beta1)
  * activerecord (4.0.0.beta1)
  * activerecord-deprecated_finders (0.0.3)
  * activesupport (4.0.0.beta1)
  * admin (0.0.1)
  * arel (4.0.0.beta2)
  * atomic (1.1.7)
  * bcrypt-ruby (3.0.1)
  * builder (3.1.4)
  * bundler (1.3.2)
  * coffee-rails (4.0.0.beta1)
  * coffee-script (2.2.0)
  * coffee-script-source (1.6.2)
  * core (0.0.1)
  * erubis (2.7.0)
  * execjs (1.4.0)
  * factory_girl (4.2.0)
  * factory_girl_rails (4.2.1)
  * fattr (2.2.1)
  * frontend (0.0.1)
  * highline (1.6.18)
  * hike (1.2.2)
  * i18n (0.6.4)
  * jbuilder (1.0.2)
  * jquery-rails (2.2.1)
  * json (1.7.7)
  * kaminari (0.14.1)
  * mail (2.5.3)
  * mime-types (1.22)
  * minitest (4.7.1)
  * multi_json (1.7.2)
  * nokogiri (1.5.9)
  * options (2.3.0)
  * pg (0.15.1)
  * polyglot (0.3.3)
  * pr_geohash (1.0.0)
  * progress_bar (1.0.0)
  * rack (1.5.2)
  * rack-test (0.6.2)
  * rails (4.0.0.beta1)
  * rails-i18n (0.7.3 1fc01d5)
  * railties (4.0.0.beta1)
  * rake (10.0.4)
  * rdoc (3.12.2)
  * rsolr (1.0.9)
  * sass (3.2.7)
  * sass-rails (4.0.0.beta1)
  * sprockets (2.9.2)
  * sprockets-rails (2.0.0.rc3)
  * store_admin (0.0.1)
  * store_frontend (0.0.1)
  * sunspot (2.0.0.pre.130115)
  * sunspot_rails (2.0.0.pre.130115)
  * sunspot_solr (2.0.0.pre.130115)
  * thor (0.18.1)
  * thread_safe (0.1.0)
  * tilt (1.3.7)
  * treetop (1.4.12)
  * tzinfo (0.3.37)
  * uglifier (2.0.1)

Manually generated solr task:
namespace :sunspot do
  namespace :solr do
    desc 'Start the Solr instance'
    task :start => :environment do
      case RUBY_PLATFORM
      when /w(in)?32$/, /java$/
        abort("This command is not supported on #{RUBY_PLATFORM}. " +
              "Use rake sunspot:solr:run to run Solr in the foreground.")
      end

      if defined?(Sunspot::Rails::Server)
        Sunspot::Rails::Server.new.start
      else
        Sunspot::Solr::Server.new.start
      end

      puts "Successfully started Solr ..."
    end

    desc 'Run the Solr instance in the foreground'
    task :run => :environment do
      if defined?(Sunspot::Rails::Server)
        Sunspot::Rails::Server.new.run
      else
        Sunspot::Solr::Server.new.run
      end
    end

    desc 'Stop the Solr instance'
    task :stop => :environment do
      case RUBY_PLATFORM
      when /w(in)?32$/, /java$/
        abort("This command is not supported on #{RUBY_PLATFORM}. " +
              "Use rake sunspot:solr:run to run Solr in the foreground.")
      end

      if defined?(Sunspot::Rails::Server)
        Sunspot::Rails::Server.new.stop
      else
        Sunspot::Solr::Server.new.stop
      end

      puts "Successfully stopped Solr ..."
    end

    # for backwards compatibility
    task :reindex => :"sunspot:reindex"
  end
end

My model:
# encoding: utf-8

class Product < ActiveRecord::Base

  ##
  # Sunspot
  searchable auto_index: true, auto_remove: true do
    text :name, boost: 5
    text :description, boost: 4
    # integer :store_id
  end
end

And finally solr's schema.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements.  See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You under the Apache License, Version 2.0
 (the "License"); you may not use this file except in compliance with
 the License.  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->
<!--
 This is the Solr schema file. This file should be named "schema.xml" and
 should be in the conf directory under the solr home
 (i.e. ./solr/conf/schema.xml by default)
 or located where the classloader for the Solr webapp can find it.

 This example schema is the recommended starting point for users.
 It should be kept correct and concise, usable out-of-the-box.

 For more information, on how to customize this file, please see
 http://wiki.apache.org/solr/SchemaXml

 PERFORMANCE NOTE: this schema includes many optional features and should not
 be used for benchmarking.  To improve performance one could
  - set stored="false" for all fields possible (esp large fields) when you
    only need to search on the field but don't need to return the original
    value.
  - set indexed="false" if you don't need to search on the field, but only
    return the field as a result of searching on other indexed fields.
  - remove all unneeded copyField statements
  - for best index size and searching performance, set "index" to false
    for all general text fields, use copyField to copy them to the
    catchall "text" field, and use that for searching.
  - For maximum indexing performance, use the StreamingUpdateSolrServer
    java client.
  - Remember to run the JVM in server mode, and use a higher logging level
    that avoids logging every request
-->
<schema name="sunspot" version="1.0">
  <types>
    <!-- field type definitions. The "name" attribute is
       just a label to be used by field definitions.  The "class"
       attribute and any other attributes determine the real
       behavior of the fieldType.
         Class names starting with "solr" refer to java classes in the
       org.apache.solr.analysis package.
    -->
    <!-- *** This fieldType is used by Sunspot! *** -->
    <fieldType name="string" class="solr.StrField" omitNorms="true"/>
    <!-- *** This fieldType is used by Sunspot! *** -->
    <fieldType name="tdouble" class="solr.TrieDoubleField" omitNorms="true"/>
    <!-- *** This fieldType is used by Sunspot! *** -->
    <fieldType name="rand" class="solr.RandomSortField" omitNorms="true"/>
    <!-- *** This fieldType is used by Sunspot! *** -->

    <!-- ANALYZERS -->

    <!-- ENGLISH ANALYZER -->
    <fieldType name="text" class="solr.TextField" omitNorms="false" positionIncrementGap="100">
      <analyzer>
        <tokenizer class="solr.StandardTokenizerFactory"/>
        <filter class="solr.StandardFilterFactory"/>
        <filter class="solr.LowerCaseFilterFactory"/>
        <filter class="solr.WordDelimiterFilterFactory"
                generateWordParts="1"
                generateNumberParts="1"
                catenateWords="1"
                catenateNumbers="1"
                catenateAll="0"
                splitOnCaseChange="1"/>
        <filter class="solr.StopFilterFactory" words="stopwords.txt" ignoreCase="true"/>
        <filter class="solr.TrimFilterFactory"/>
        <filter class="solr.PorterStemFilterFactory"/>
        <filter class="solr.EdgeNGramFilterFactory" minGramSize="1" maxGramSize="100" side="front"/>
      </analyzer>
    </fieldType>

    <!-- *** This fieldType is used by Sunspot! *** -->
    <fieldType name="boolean" class="solr.BoolField" omitNorms="true"/>
    <!-- *** This fieldType is used by Sunspot! *** -->
    <fieldType name="date" class="solr.DateField" omitNorms="true"/>
    <!-- *** This fieldType is used by Sunspot! *** -->
    <fieldType name="sdouble" class="solr.SortableDoubleField" omitNorms="true"/>
    <!-- *** This fieldType is used by Sunspot! *** -->
    <fieldType name="sfloat" class="solr.SortableFloatField" omitNorms="true"/>
    <!-- *** This fieldType is used by Sunspot! *** -->
    <fieldType name="sint" class="solr.SortableIntField" omitNorms="true"/>
    <!-- *** This fieldType is used by Sunspot! *** -->
    <fieldType name="slong" class="solr.SortableLongField" omitNorms="true"/>
    <!-- *** This fieldType is used by Sunspot! *** -->
    <fieldType name="tint" class="solr.TrieIntField" omitNorms="true"/>
    <!-- *** This fieldType is used by Sunspot! *** -->
    <fieldType name="tfloat" class="solr.TrieFloatField" omitNorms="true"/>
    <!-- *** This fieldType is used by Sunspot! *** -->
    <fieldType name="tdate" class="solr.TrieDateField" omitNorms="true"/>

    <!-- A specialized field for geospatial search. If indexed, this fieldType must not be multivalued. -->
    <fieldType name="location" class="solr.LatLonType" subFieldSuffix="_coordinate"/>
  </types>
  <fields>
    <!-- Valid attributes for fields:
     name: mandatory - the name for the field
     type: mandatory - the name of a previously defined type from the
       <types> section
     indexed: true if this field should be indexed (searchable or sortable)
     stored: true if this field should be retrievable
     compressed: [false] if this field should be stored using gzip compression
       (this will only apply if the field type is compressable; among
       the standard field types, only TextField and StrField are)
     multiValued: true if this field may contain multiple values per document
     omitNorms: (expert) set to true to omit the norms associated with
       this field (this disables length normalization and index-time
       boosting for the field, and saves some memory).  Only full-text
       fields or fields that need an index-time boost need norms.
     termVectors: [false] set to true to store the term vector for a
       given field.
       When using MoreLikeThis, fields used for similarity should be
       stored for best performance.
     termPositions: Store position information with the term vector.
       This will increase storage costs.
     termOffsets: Store offset information with the term vector. This
       will increase storage costs.
     default: a value that should be used if no value is specified
       when adding a document.
   -->
    <!-- *** This field is used by Sunspot! *** -->
    <field name="id" stored="true" type="string" multiValued="false" indexed="true"/>
    <!-- *** This field is used by Sunspot! *** -->
    <field name="type" stored="false" type="string" multiValued="true" indexed="true"/>
    <!-- *** This field is used by Sunspot! *** -->
    <field name="class_name" stored="false" type="string" multiValued="false" indexed="true"/>
    <!-- *** This field is used by Sunspot! *** -->
    <field name="text" stored="false" type="string" multiValued="true" indexed="true"/>
    <!-- *** This field is used by Sunspot! *** -->
    <field name="lat" stored="true" type="tdouble" multiValued="false" indexed="true"/>
    <!-- *** This field is used by Sunspot! *** -->
    <field name="lng" stored="true" type="tdouble" multiValued="false" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="random_*" stored="false" type="rand" multiValued="false" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="_local*" stored="false" type="tdouble" multiValued="false" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_text" stored="false" type="text" multiValued="true" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_texts" stored="true" type="text" multiValued="true" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_b" stored="false" type="boolean" multiValued="false" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_bm" stored="false" type="boolean" multiValued="true" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_bs" stored="true" type="boolean" multiValued="false" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_bms" stored="true" type="boolean" multiValued="true" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_d" stored="false" type="date" multiValued="false" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_dm" stored="false" type="date" multiValued="true" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_ds" stored="true" type="date" multiValued="false" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_dms" stored="true" type="date" multiValued="true" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_e" stored="false" type="sdouble" multiValued="false" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_em" stored="false" type="sdouble" multiValued="true" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_es" stored="true" type="sdouble" multiValued="false" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_ems" stored="true" type="sdouble" multiValued="true" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_f" stored="false" type="sfloat" multiValued="false" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_fm" stored="false" type="sfloat" multiValued="true" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_fs" stored="true" type="sfloat" multiValued="false" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_fms" stored="true" type="sfloat" multiValued="true" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_i" stored="false" type="sint" multiValued="false" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_im" stored="false" type="sint" multiValued="true" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_is" stored="true" type="sint" multiValued="false" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_ims" stored="true" type="sint" multiValued="true" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_l" stored="false" type="slong" multiValued="false" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_lm" stored="false" type="slong" multiValued="true" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_ls" stored="true" type="slong" multiValued="false" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_lms" stored="true" type="slong" multiValued="true" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_s" stored="false" type="string" multiValued="false" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_sm" stored="false" type="string" multiValued="true" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_ss" stored="true" type="string" multiValued="false" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_sms" stored="true" type="string" multiValued="true" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_it" stored="false" type="tint" multiValued="false" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_itm" stored="false" type="tint" multiValued="true" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_its" stored="true" type="tint" multiValued="false" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_itms" stored="true" type="tint" multiValued="true" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_ft" stored="false" type="tfloat" multiValued="false" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_ftm" stored="false" type="tfloat" multiValued="true" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_fts" stored="true" type="tfloat" multiValued="false" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_ftms" stored="true" type="tfloat" multiValued="true" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_dt" stored="false" type="tdate" multiValued="false" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_dtm" stored="false" type="tdate" multiValued="true" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_dts" stored="true" type="tdate" multiValued="false" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_dtms" stored="true" type="tdate" multiValued="true" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_textv" stored="false" termVectors="true" type="text" multiValued="true" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_textsv" stored="true" termVectors="true" type="text" multiValued="true" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_et" stored="false" termVectors="true" type="tdouble" multiValued="false" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_etm" stored="false" termVectors="true" type="tdouble" multiValued="true" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_ets" stored="true" termVectors="true" type="tdouble" multiValued="false" indexed="true"/>
    <!-- *** This dynamicField is used by Sunspot! *** -->
    <dynamicField name="*_etms" stored="true" termVectors="true" type="tdouble" multiValued="true" indexed="true"/>

    <!-- Type used to index the lat and lon components for the "location" FieldType -->
    <dynamicField name="*_coordinate"  type="tdouble" indexed="true"  stored="false" multiValued="false"/>
    <dynamicField name="*_p" type="location" indexed="true" stored="true" multiValued="false"/>

    <dynamicField name="*_ll" stored="false" type="location" multiValued="false" indexed="true"/>
    <dynamicField name="*_llm" stored="false" type="location" multiValued="true" indexed="true"/>
    <dynamicField name="*_lls" stored="true" type="location" multiValued="false" indexed="true"/>
    <dynamicField name="*_llms" stored="true" type="location" multiValued="true" indexed="true"/>
  </fields>
  <!-- Field to use to determine and enforce document uniqueness.
      Unless this field is marked with required="false", it will be a required field
   -->
  <uniqueKey>id</uniqueKey>
  <!-- field for the QueryParser to use when an explicit fieldname is absent -->
  <defaultSearchField>text</defaultSearchField>
  <!-- SolrQueryParser configuration: defaultOperator="AND|OR" -->
  <solrQueryParser defaultOperator="AND"/>
  <!-- copyField commands copy one field to another at the time a document
        is added to the index.  It's used either to index the same field differently,
        or to add multiple fields to the same field for easier/faster searching.  -->
</schema>

A: I was running into a similar issue and the solution is to run the reindex with bundle exec rake not just rake
$ bundle exec rake sunspot:solr:stop
$ bundle exec rake sunspot:solr:start
$ bundle exec rake sunspot:reindex


text:
Q: How to change legend order of Pie Chart in PowerBi As for piechart in powerBi, currently legend order is set by value. I want to reorder it by alphabet order of legend key. I select specified key (IsReady) and flags and show below graph.

Here is my sample data.

A: You can change the sort column by clicking the 3 Dot as shown below-

Just select the column from list you wants to apply the sorting on and then select the order Ascending or Descending.


text:
Q: Trigger action of re-click/double click on first click of button I have an HTML such that when I click on "Continue" button then an overlay appears. That overlay has "Skip and Continue" button. When I click on "Skip and Continue" button then second overlay appears replacing the first one.
My Expectation is to display the second overlay on the click of Continue button, the first overlay should never appear and the action of "Skip and Continue" should be triggered on the click of Continue button.
I have written below code which is partially working. the Single click on Continue button is not triggering anything however when I re-click or doubleclick the Continue button then second overlay appears. I want second overlay to appears on the single/first click of Continue button.
$('button.yelbtn').click(function() {
  $('button.btn.btn-indigo.skip-cnt-btn').trigger('click');
  $('.flexi-promotion-popup').hide();
});

P.S:
Selector for Continue button:
$('button.yelbtn')

Selector for Skip and Continue Button:
$('button.btn.btn-indigo.skip-cnt-btn')

HTML CONTINUE BUTTON :
<button id="continue-button" class="yelbtn">
    Continue

</button>

DIV APPEARS IN DOM WHEN CONTINUE BUTTON IS NOT CLICKED YET

DIV APPEARS IN DOM WHEN CONTINUE BUTTON HAS BEEN CLICKED (FIRSY OVERLAY)

                        Add flexibility to your travel
                        <button type="button" class="closeBtn pull-right" data-dismiss="modal" aria-label="Close">

                        </button>

                         BLR

                          IXC
                           (
                             Saver Fare)

                              Make unlimited changes to your booking at additional

                                  ₹ 354*

                                  <button class="btn btn-abc">Add to trip

                                  </button>
                                  <button type="button" class="btn btn-abc skip-cnt-btn ml20" data-dismiss="modal">Skip and continue

                                   </button>

*Fare difference applies. For more details,
                           Click here.

DIV WHEN SKIP AND CONTINUE BUTTON IS CLICKED:

                                <button class="closeBtn pull-right">

                                </button>

                        <form>

Passenger Mobile Number & Email ID

Note: Entering mobile number & email ID is mandatory to proceed for your booking.
*All notifications will be sent to this mobile number and email address.

+91

<input type="tel" name="mobileNum" value="" placeholder="Enter Mobile No." class="form-control indilogin-wrappertop_mob">

e.g (89687xxxxx)

                                    <input type="email" name="emailId" value="" placeholder="Email Id" class="form-control indilogin-wrappertop_email">

e.g (xxx@gmail.com)

                                    <input type="checkbox" value="on">

                                GST Information (optional)

                                <button type="submit" class="btn btn-primary btn-lg btn-block signin-btn btn-nxt">Next
                                </button>

                        </form>

A: Try hide/show the continue button
$('button.yelbtn').click() {
    $('button.yelbtn').hide();
    $('button.btn.btn-indigo.skip-cnt-btn').show();
    $('button.btn.btn-indigo.skip-cnt-btn').trigger('click');
    ...
 }


text:
Q: What is the difference between bool? MyProperty and bool ?MyProperty While reviewing a PR today I saw this in a class:
public bool ?Selected { get; set; }   //question mark in front of property name

I suspected that the developer meant this
public bool? Selected { get; set; }  //question mark at end of type

I was surprised that this even complied so I tried it myself and found that this is legal code and it ends up doing the same thing.
My question is: Is there any subtle (or not so subtle) difference between these two?

A: First of all, my Visual Studio 2017 immediately corrects this
public bool ?Selected { get; set; }

To this
public bool? Selected { get; set; }

Then, IL DASM to the rescue! You can see that the resulting IL is the same, just like @mjwills said in the comments:

In the end, you can always hit Ctrl+K + Ctrl+D to have Visual Studio reformat your code and properly manage blanks and indentation.
As per your question about changing bool? to bool, it depends: if something can have an indefinite value or state, just like checkboxes, you should use bool?; otherwise bool is fine.

A: It might make a little more sense when you realize that the following is also valid:
public bool?Selected { get; set; }

? in that context is the nullable type identifier and as such it can't be followed by any character that would make sense in the current token, so the lexer simply processes the nullable type identifier and starts lexing the following expected token. Whats really redundant is the whitespace, its more a format helper to make it more readable than a syntax requirement.
Whitespaces are in many contexts meaningless trivia the compiler could do without.
Its similar in a sense as to why the following are all valid:
static bool Huh<T >() { return false; }
static bool Huh<T > () { return false; }
static bool Huh <T > () { return false; }
etc.

A: As others have suggested, there is no difference in how the code functions based on the location of ?. The compiler doesn't much care for whitespace assuming it can make out the operators and operands. It simply comes down to readability and personal/team preference.
For example, given:
var app = new App();

These are also the same:
app.      SomeMethod();

And
app      .SomeMethod();

And
app   .   SomeMethod();

Or placing the dot operator anywhere else inbetween; including on a new line. It all compiles down to the same IL.


text:
Q: Catch html5 geolocation events Is there a way to catch the html5 geolocation events?
Right now im using geolocator.js
and my problem is:
When the message pops up if i want to allow html5 locations if i accept it takes html5 location if I get ipLocation.
But I want to listen for these clicks so I can set a timeout if the user doesn't click for 10 seconds it automatically takes ip location.
Is there any way to get the event for "accept" and "decline"? Here is my code snippet for it
if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(geoSuccess, geoError, html5Options);
    } else { // not supported
        fallback(new Error('geolocation is not supported.'));
    }

EDIT: Im using Chrome on iMac
EDIT 2:
var html5Options = { enableHighAccuracy: true,timeout: 10000, maximumAge: 0 };

EDIT 3: using the solution by kravitz
if (navigator.geolocation) {
        waitTooLong=setTimeout(geoError, 15000);
        navigator.geolocation.getCurrentPosition(geoSuccess, geoError, html5Options);
    } else { // not supported
        fallback(new Error('geolocation is not supported.'));
    }

function geoSuccess(position) {
        clearTimeout(waitTooLong);
       //doing my locationstuff
}

function geoError(error) {
        //doing my locationstuff
        clearTimeout(waitTooLong);
        fallback(error);
 }

A: var geoError = function(){
  //get location failed so get manually by IP here
};

if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(geoSuccess, geoError, html5Options);
    } else { // not supported
        fallback(new Error('geolocation is not supported.'));
    }

Above should work but if you want to be really sure:
var timeOut = setTimeout(geoError, 10000);
var geoSuccess =  function(){
   clearTimeout(timeOut);
};


text:
Q: Testing android flow I am trying to unit test my android viewmodel:
inside of it I have a few init calls:
  init {
        executeUseCase(useCases.GetUserResults())
        executeUseCase(useCases.GetUserInfectionDetectionLinkUseCase())
    }

Now I want to test that my viewmodel actually gets data and sets the view state. But these "calls" returns a flow:
return  flow {
    DataState.Data(useCase, response)
}

Note that I have dumbed down the actual code but in general these returns a flow.
In my test I have the a @Before
    @Before
fun setUp() {
    logger = mockk<Logger>()
    useCases = useCases(RepositoryMock())
    userUseCases = mockk<UserUseCases>()

    viewModel =  MyViewModel(logger = logger,useCases, userUseCases);
}

How can I ensure that the viewmodel gets the databack from the repository (IE the flow is complete) before I begin my test?


text:
Q: Trying to find trapezoid volume Im still new to coding and still experimenting with different forms. I have been able to calculate the volume of a trapezoid using prompts but now I am looking to achieve the same effect using viewable inputs and buttons and the code keeps outputing a NaN so I was wondering if anyone can spot what it is I might be doing wrong here, anything helps!

Trapazoid Calculator

Length

<input id="Length" type="number" onchange="Trapazoid()" value=7>

Height

<input id="Height" type="number" onchange="Trapazoid()" value=7>

Width

<input id="Width" type="number" onchange="Trapazoid()" value=7>

Top

<input id="Top" type="number" onchange="Trapazoid()" value=7>

<input type = "button" id="button1" value="Calculate" onclick = "calculateTrapazoid()"/>
<input type = "reset" value="Clear" />

A: document.getElementById("Length") returns the html DOM object
document.getElementById("Length").value returns the value contained in the DOM object which is what you're looking to do
More info on getElementById and the DOM https://www.w3schools.com/jsref/met_document_getelementbyid.asp
Here's a working fiddle with the following code (in case the link doesn't work properly). https://jsfiddle.net/g43u9x7h/

Data

<input id="Top" type="number" onchange="Trapazoid()" placeholder='Top'>
<input id="Height" type="number" onchange="Trapazoid()" placeholder='Height'>
<input id="Width" type="number" onchange="Trapazoid()" placeholder='Width'>
<input id="Length" type="number" onchange="Trapazoid()"  placeholder='Length'>

<input type = "button" id="button1" value="Calculate" onclick = "calculateTrapazoid()"/>
<input type = "reset" value="Clear" />


text:
Q: Cannot delete linked list when calling the destructor void Set::remove(Set::Node* p) {
    if(p == nullptr) return;
    Node* tmp = p->next;
    delete p;
    return remove(tmp);
}

Set::~Set() {
    remove(list);
}

class Set {
public:
~Set();

private:
    struct Node {
        int value;
        Node* next;
    };
    Node* list;
}

Set& Set::operator= (const Set& other) {
    if(this == &other) return *this;
    list = copy(other.list);
    sizeOfList = other.sizeOfList;
    return *this;
}

Set::Node* Set::copy(Set::Node* list) {
    if(list == nullptr) return nullptr;
    return cons(list->value, copy(list->next));
}

Set::Node* Set::cons (int value, Set::Node* next) {
    Node* tmp = new Node;
    tmp->value = value;
    tmp->next = next;
    return tmp;
}

Set() : list(nullptr), sizeOfList(0) {};

I wanted to test the destructor, so I call it manually(on the last line of the program)
x.~Set();

but then I got * error for object 0x100103ad0: pointer being freed was not allocated. I dont know what I have done wrong. I have read as many related posts as possible but cant find a solution. Hope someone's help!

A: You have no constructor that sets list from an undefined value to a known one, so list is never being set to anything and you are trying to delete it.
Try adding a default constructor that sets list = nullptr;


text:
Q: OpenGL staging buffer to improve Uniform Buffer performance I read that driver seems to put buffers on client side memory, so it comes to me a different idea to manage my uniform buffers.
My uniform buffers work with matrix, materials etc, so they are updated more than once by frame.
The old way was this one :

*

*Create uniform buffer using glBufferStorage, and map it with flush_bit.

*Update a part of this buffer, flush it and drawcall.

My new way could be like that :

*

*Create uniform buffer using glBufferData and dynamic (??) hint.

*Create a little transfer buffer with bl buffer storage and client side hint(thanks to that, I must not flush it?)

*Update the transfer buffer

*Copy the transfer buffer to the uniform one.

Do you think it could improve performance?


text:
Q: Python script to match date in particular time interval We have access logs which contain logging in below format:
0.93 172.19.180.93 - - - [14/Mar/2016:11:07:22 +0130] "GET /MyWeb/appResources/css/ng-tags-input.min.css HTTP/1.1" 200 1077 **0/4864**

Now, want to parse each line using python script to identify number of such acess request occured between 10.00 to 19:00 hr on particular date.
Trying Something like:
for fname in filenames_245:
    with open(fname) as infile:
        for line in infile:
            if re.search('[0-9][0-9]//Mar//2016/:[1]',line):
                outfile.write(line)

Can someone please suggest the correct usage of pattern to get required data.

A: re.search() evaluates to true even if there is no match, because ir return's an SRE object, and you regex was wrong on the [1], you want:
You want:
re.findall('\d\d/Mar/2016:1', data)

A: Your regular expression can work, but the problem is that you're using two slashes instead of one. So you should write it as '[0-9][0-9]/Mar/2016:[1]'.
Note that to escape a character you should prepend it with a backslash (\) not a forward slash (/). But here you don't need to escape anything.

A: Try:
>>> re.search("14/Mar/2016:1", line)
<_sre.SRE_Match object at 0x7f37cd4179f0>

or
>>> re.search("{0}/{1}/{2}:1".format(date, month, year), line)
<_sre.SRE_Match object at 0x7f37cd417ac0>

if you want to pass your days as variables.
Regarding Joao Pinto, search returns none if there is no match:
https://docs.python.org/3.5/library/re.html


text:
Q: Highlight initial SwiftUI List item when a Mac app launches I have a Mac app that uses a List to determine which view is displayed in the DetailView. UserDefaults saves the state of which view is displayed when the app launches.
However, the List item associated with the initial detail view is not highlighted when the app launches. How can I highlight the appropriate List item when the Mac app launches?
struct SidebarView: View {

    @State private var selected = Set([UserDefaults.standard.object(forKey: "Selected") as? String ?? "Second View"])

    private let items = ["First View", "Second View", "Third View"]

    var body: some View {
        List(items, id: \.self, selection: $selected) { item in
            NavigationLink(destination: DetailView(selection: item)) {
                Text("\(item)")
            }
        }
        .listStyle(SidebarListStyle())
    }
}

struct DetailView: View {

    var selection: String

    var body: some View {
        switch selection {
        case "First View":
            UserDefaults.standard.set("First View", forKey: "Selected")
            return AnyView(FirstView())
        case "Second View":
            UserDefaults.standard.set("Second View", forKey: "Selected")
            return AnyView(SecondView())
        case "Third View":
            UserDefaults.standard.set("Third View", forKey: "Selected")
            return AnyView(ThirdView())
        default:
            return AnyView(
                Text("Some \(selection) view here").frame(maxWidth: .infinity, maxHeight: .infinity)
            )
        }
    }
}

struct ContentView: View {

    private let selected = UserDefaults.standard.object(forKey: "Selected") as? String ?? "Second View"

    var body: some View {
        NavigationView {
            SidebarView()
            DetailView(selection: selected)
        }
    }
}


text:
Q: Atmel Attiny 104 - Arduino support From what I have gathered, you can implement a new chip in Arduino by editing boards and arduino_pins.h
From what I can see, AtTiny84 is pretty similar to 104, but the pin out and pin functions are slightly different.
My question is:
How can I edit Arduino_pins.h to match that of AtTiny104 chip?
*I tried programming with Atmel studio but my comprehension of C of that magnitude is shallow so I prefer doing it with Arduino ide.
My project is simple:
If inputs i1 high or i2 high or i3 (analog value) < 700
then output o1 is high
Else
if i4 is high
Then o1 is low
Else
O1 is high
Arduino support or atmel studio support much appreciated.


text:
Q: Exporting attributes from QGIS to .dxf/dwg I have a QGIS point layer with attributes in table. I want to export a layer with some of the attributes as a CAD block with attributes. Is it possible to do something like this?

A: You can Use 'MAPIMPORT' in autocad to import shapefiles and some other formats. The map import window will give you some choices on how to import it (as a block, as a text, give the shapefile attributes to the block, import data table...)
The block's attributes will have to match the shapefiles's attributes to be imported correctly