Fetch then after catch still be called even be catched

Question: I want to return a fetch promise to upper layer to use, but I found even this fetch promise fail (be catched), upper layer's then still be called. Is it possible "upper layer's then" only be called when fetch success?
export default function request(url, options) {
  .......
  return fetch(url, options)
    .then(checkStatus)
    .then(parseJSON)
    .then(data => {
      // debugPrint("receive response" + JSON.stringify(data));

      if (+data.status.code !== 200) {
        message.error(data.status.message || "please retry");
      }
      return data;
    })
    .catch(err => {
      message.error(err.toString() || "please retry");
      return err;
    });
}

// then I call request this way:
export function userLogin(account) {
  return request(`${domain}/signin/get_accesstoken`, {
    method: "POST"
  }).then(data => {
    // even catch be called, this then still be called. Is it possible only call this then when catch not be called ?

    do something;
    return data;
  });
}

Second edit:
I try to return a promise in then, but look like it is not a promise be returned, I don't know why.
export default function request(url, options) {
  .......
  return fetch(url, options)
    .then(checkStatus)
    .then(parseJSON)
    .then(data => {
      // debugPrint("receive response" + JSON.stringify(data));

      if (+data.status.code !== 200) {
        message.error(data.status.message || "please retry");
      }
      return new Promise(resolve=>{
          resolve(data)
      });
    })
    .catch(err => {
      message.error(err.toString() || "please retry");
      return new Promise((resolve, reject)=>{
         reject(err)
      });
    });
}

Edit third:
    export default function request(url, options) {
  .......
  return fetch(url, options)
    .then(checkStatus)
    .then(parseJSON)
    .then(data => {
      // debugPrint("receive response" + JSON.stringify(data));

      if (+data.status.code !== 200) {
        message.error(data.status.message || "please retry");
      }
      return data;
    })
    .catch(err => {
      message.error(err.toString() || "please retry");
      return;
    });
}

    // then I call request this way:
export function userLogin(account) {
  return request(`${domain}/signin/get_accesstoken`, {
    method: "POST"
  }).then(data => {
    // add this
    if (!data) {
      return
     }
    do something;
    return data;
  });
}

Comment: Well, that's just what `catch` does: handle the error and provide a result to the caller. Don't use `catch` if you don't handle (or rethrow) the error.
Comment: yes, I understand this is what catch does. but I want to know how to design for this request/response logic. In request function, then will do all check for response, if there have any error in response, will throw an error to catch.  for upper layer, just need to take care of success case(then case), and all error handle by request. so is it the only way to use callback in last then of request function?
Comment: No, you should not do error handling in `request` only, an error might happen in `userLogin` as well. Of course you can handle them by ignoring them. For the `request` function, you have 3 options when an error happens: a) fulfill the returned promise with a status flag (requires a conditional in the upper layer), b) never resolve the promise (so that the upper layer never knows when the request finished - you don't want that), or c) reject the returned promise.
Comment: @Bergi for  a) fulfill the returned promise with a status flag, do you mean the way as Edit three? if so I feel a little repetitive, since I have to add if (!data) in every upper layer functions.  and for c) reject the returned promise, I am not understand, I am new in JS area. Possible give some code? Thanks.
Comment: Yes, I wouldn't use a) either - better use the promise functionality to signal failure. and the way to do that is c), like the code in your second edit or in Usama's answer, where you rethrow the error.
Answer: if you want to call your upper layer's then only in case of success then throw some error in catch block of fetch instead of returning err.

export default function request(url, options) {
  .......
  return fetch(url, options)
    .then(checkStatus)
    .then(parseJSON)
    .then(data => {
      // debugPrint("receive response" + JSON.stringify(data));

      if (+data.status.code !== 200) {
        message.error(data.status.message || "please retry");
      }
      return data;
    })
    .catch(err => {
      message.error(err.toString() || "please retry");
      throw new Error('fetch failed');     // throw error
    });
}
Comment: No, system will say "request.js:62 Uncaught (in promise) Error: fetch failed", I don't want to handle error again in upper layer, since request has handle it.
Comment: @Cindy No, you didn't handle the error, you just returned it, and that's why then is triggered in the first place, it thinks the returned error is valid data. So like Usama said you have to rethrow the error
Comment: if not return in catch, the upper layer then still be called after catch
Comment: if you won't return anything from `catch` block then `upper layer's` `catch` block won't get called.


Can not load any gems after upgrade

Question: I'm trying to move from ruby 1.8 to 1.9 something.
I have tried installing the newer ruby in a number of ways - with rvm, with apt-get, etc. No matter which way I do it, once I've got /usr/bin/ruby pointing at that, no gems can be loaded ("no such file to load").
I have tried reinstalling them, both as super user and regular, and the gem install command finishes successfully, but it still doesn't find them.
I have also installed rubygems1.9.1
Can someone please tell me what's wrong. This is insanely frustrating - I have installed every gem several times in many many places and yet it doesn't find any of them. I have tried setting GEMS_DIR to no avail as well.
Answer:
Remove every Ruby installation you got. Be sure there are no 'ruby' and 'gem' executables anywhere.
Install RVM and check if it went well
Install all the dependencies listed in rvm notes output.
Do rvm install 1.9.2 and start installing your gems.
Comment: `rvm use` should not link to /usr/bin/ruby, everything should be happening inside your home dir.
Comment: step 3 should be to confirm the RVM install using the "Post Install" section of the install page. Step 4 should be to follow the directions after typing `rvm notes`. Then RVM can be used to install Rubies.
Comment: No luck, I've already tried doing this. RVM doesn't really seem to work for me... 'rvm use 1.9.2' says that's its using that version, but I can't really tell what it does. It _doesn't_ link that executable to /usr/bin/ruby, which seems like a pretty crucial step, so I'm not sure what else, if anything, it is doing. I've tried doing rvm gem install ______, sudo rvm gem install (which the docs say not to), and regular [sudo] gem install. It doesn't matter, when I try to run a script with gems it fails to load them.
Comment: @hsiu, It really sounds like you need to take the time to read completely through the [installation documents](http://rvm.beginrescueend.com/rvm/install) for RVM, including the "Post Install" and troubleshooting section before you start.

Can not load any gems after upgrade


ionic Cannot show full month string in picker due to picker option width

Question: Part of month name string is hidden for long month name in Chinese like 十一月

Observation:
In inspector, altering width(css) of picker option results in full month name shown.
However, the alignment is broken.

Hope to see advice to correctly show the month name.
Thanks
Comment: Why not increase the width in the css by default ?
Answer: try something like this for full months names:
<ion-item>
 <ion-label>Date</ion-label>
 <ion-datetime display-format="DD MMMM YYYY" picker-format="DD/MMMM/YYYY"></ion-datetime>
</ion-item>

Comment: I'm sorry that cannot accept this answer as this changes the desired picker format
Answer: To enlarge month name datepicker width:
add
.picker-col{
    max-width: 70px !important;
}

in app.scss


rearrange date order in dataframe column

Question: I have a dataframe, df, where I would like to rearrange the order of my dataframe values under a specific column.
Data
id  date    stat
aa  Q1.22   5
aa  Q2.22   2
aa  Q3.22   2
aa  Q4.22   1
bb  Q2.22   9
bb  Q3.22   0
bb  Q4.22   0
bb  Q1.22   1

Desired
id  date    stat
aa  Q1.22   5
aa  Q2.22   2
aa  Q3.22   2
aa  Q4.22   1
bb  Q1.22   1
bb  Q2.22   9
bb  Q3.22   0
bb  Q4.22   0

Doing
 df.sort_values(by='date')

However, the original dataframe remains, and the dataframe stays unsorted.
Any feedback is appreciated
Comment: use `df=df.sort_values(['id','date'])` instead of sorting values by **'date'** sort by **'id'** and **'date'**
Comment: Right.  The point is that `sort_values` does not sort in place.  It returns a new data frame with that column sorted.
Comment: ok thank you @AnuragDabas - this is not working. I will try and tweak this
Comment: so it is not working?
Comment: no, when I tried on my full dataset, it remains in the same order
Answer: >>> df.sort_values(['id', 'date'])

   id   date  stat
0  aa  Q1.22     5
1  aa  Q2.22     2
2  aa  Q3.22     2
3  aa  Q4.22     1
7  bb  Q1.22     1
4  bb  Q2.22     9
5  bb  Q3.22     0
6  bb  Q4.22     0

You have 2 choices:
Return a sorted copy of your dataframe:
df = df.sort_values(['id', 'date'])

or sort inplace:
df.sort_values(['id', 'date'], inplace=True)

Refer to the documentation
Comment: I will try again
Answer: Another way let's see if it works or not(bcz it's working fine df.sort_values(['id', 'date'])):
Idea is to create timestamps from 'date' column then sort values according to them and after sorting drop it:
df['sort']=pd.PeriodIndex(df['date'].str.split('.').str[::-1].str.join('-'),freq='Q').to_timestamp()
df=df.sort_values(['id','sort']).drop('sort',1)


flow diverter for a nonstandard tub installation

Question: I installed an antique clawfoot tub in a tiled & grouted sunken recess (originally a built-in japanese-style soaking tub) which required me to install an s-shaped tub outlet, so as to clear the lip of the tub as shown in the photo.
To divert flow up to the shower head, I tried installing a shower flow diverter valve on the end of the s-pipe, but the flow through the diverter is so restricted that when I want to fill the tub, only a thin jet of water exits the valve outlet into the tub while water backs up all the way to the shower head, which then dribbles like crazy.
I did a temporary fix by screwing a pipe cap onto the end of the s-pipe to block it completely when I want to use the shower head and then unscrewing it when I want to fill the tub, which yields unrestricted flow into the tub with no dribble from the shower head.
This is a clumsy fix, but I cannot find a diverter valve for the end of that s-pipe which provides full flow (like the ordinary tub spout diverter with the pull knob, which will not fit on the end of that s-pipe) without backing up and causing the shower head to dribble.
Does anyone here have any ideas about how to address this problem, short of plumbing in a completely new faucet set/flow diverter/shower head assembly?
Answer: Since the "look" is already rather "industrial" just put a 1/4 turn ball valve on the end of the pipe. Hole the same size as the pipe when open, shuts off fully when shut.

The picture implies that you could also possibly remove the blind cover from a hole in the tub to get a more direct path for a straight pipe stub that would take a normal tub spout, if you'd like a "less industrial" appearance.
Or replace the coupling and "S-bend" with two elbows and two straight nipples, which would allow the normal tub spout to screw onto the end of the second straight nipple.


Fast lossless encoding of SKBitmap images

Question: I'm trying to store large 4096x3072 SKBitmap images with lossless compression as fast as I can. I've tried storing them as PNG using SKImage.FromBitmap(bitmap).Encode(SKEncodedImageFormat.Png, 100) but this was really slow. Then using information from this question and this example code I made a method to store them as a Tiff image, which was a lot faster but still not fast enough for my purposes. The code has to work on Linux as well. This is my current code:
public static class SKBitmapExtensions
{
    public static void SaveToPng(this SKBitmap bitmap, string filename)
    {
        using (Stream s = File.OpenWrite(filename))
        {
            SKData d = SKImage.FromBitmap(bitmap).Encode(SKEncodedImageFormat.Png, 100);
            d.SaveTo(s);
        }
    }
    public static void SaveToTiff(this SKBitmap img, string filename)
    {
        using (var tifImg = Tiff.Open(filename, "w"))
        {
            // Set the tiff information
            tifImg.SetField(TiffTag.IMAGEWIDTH, img.Width);
            tifImg.SetField(TiffTag.IMAGELENGTH, img.Height);
            tifImg.SetField(TiffTag.COMPRESSION, Compression.LZW);
            tifImg.SetField(TiffTag.PHOTOMETRIC, Photometric.RGB);
            tifImg.SetField(TiffTag.ROWSPERSTRIP, img.Height);
            tifImg.SetField(TiffTag.BITSPERSAMPLE, 8);
            tifImg.SetField(TiffTag.SAMPLESPERPIXEL, 4);
            tifImg.SetField(TiffTag.XRESOLUTION, 1);
            tifImg.SetField(TiffTag.YRESOLUTION, 1);
            tifImg.SetField(TiffTag.PLANARCONFIG, PlanarConfig.CONTIG);
            tifImg.SetField(TiffTag.EXTRASAMPLES, 1, new short[] { (short)ExtraSample.UNASSALPHA });

            // Copy the data
            byte[] bytes = img.Bytes;

            // Swap red and blue
            convertSamples(bytes, img.Width, img.Height);

            // Write the image into the memory buffer
            for (int i = 0; i < img.Height; i++)
                tifImg.WriteScanline(bytes, i * img.RowBytes, i, 0);
        }
    }
    private static void convertSamples(byte[] data, int width, int height)
    {
        int stride = data.Length / height;
        const int samplesPerPixel = 4;

        for (int y = 0; y < height; y++)
        {
            int offset = stride * y;
            int strideEnd = offset + width * samplesPerPixel;

            for (int i = offset; i < strideEnd; i += samplesPerPixel)
            {
                byte temp = data[i + 2];
                data[i + 2] = data[i];
                data[i] = temp;
            }
        }
    }
}

And the test code:
SKBitmap bitmap = SKBitmap.Decode("test.jpg");

Stopwatch stopwatch = new();
stopwatch.Start();

int iterations = 20;
for (int i = 0; i < iterations; i++)
    bitmap.SaveToTiff("encoded.tiff");

stopwatch.Stop();
Console.WriteLine($"Average Tiff encoding time for a {bitmap.Width}x{bitmap.Height} image = {stopwatch.ElapsedMilliseconds / iterations} ms");

stopwatch.Restart();

for (int i = 0; i < iterations; i++)
    bitmap.SaveToPng("encoded.png");

stopwatch.Stop();
Console.WriteLine($"Average PNG encoding time for a {bitmap.Width}x{bitmap.Height} image = {stopwatch.ElapsedMilliseconds / iterations} ms");

As a result I get:
Average Tiff encoding time for a 4096x3072 image = 630 ms
Average PNG encoding time for a 4096x3072 image = 3092 ms

Is there any faster way to store these images? I can imagine that I can avoid copying the data at var bytes = img.Bytes but I'm not sure how. The encoded file size for the PNG is 10.3MB and for the Tiff it is 26MB now.
Answer: If you are not so interested in making the most optimal png (from a file size point of view) then you can get access to some faster encoding options through:
SKBitmap bitmap = SKBitmap.Decode("test.jpg");
using(var pixmap= bitmap.PeekPixels())
{
    var filters = SKPngEncoderFilterFlags.NoFilters;
    int compress = 0;
    var options = new SKPngEncoderOptions(filters, compress);
    using (var data = pixmap.Encode(options))
    {
        byte[] bytes = data.ToArray();
        // use data - write bytes to file etc
    }
}

In the above example:

compress = 0 will use no zlib compression so the pngs will effectively be similar size to an uncompressed TIFF. You could try a higher value for compress (I think 9 is maximum but slowest).
filters = SKPngEncoderFilterFlags.NoFilters will be fastest under all scenarios. It could make files produced with compress != 0 larger in file size. The filters option is used to try to improve compressibility at the file with SKPngEncoderFilterFlags.AllFilters producing potentially the most compressed file.


Where to set /TSAWARE in Visual Basic 6.0 project in Visual Studio 98

Question: I need to set the /TSAWARE flag for a legacy VB 6.0 activeX EXE.  I can do it with
BINEDIT /TSAWARE app.exe

after building the app, but I'm thinking there should be a way to select it in the VB6 project itself in Visual Studio.  I've looked at project properties but don't see anywhere to set linker options.  The project is an ActiveX component.
This question mentions doing it in Visual Studio 6.0 with C++ in the linker but haven't seen way to do it in VB which doesn't seem to have explicit link settings.
Comment: VB6 is certainly older than Windows 2000, which is when Terminal Services really started to become a thing. I'm not sure if it's older than NT4 Terminal Services Edition. Regardless, VB6 is really *that* old.
Comment: Ignore the trolls.  People wouldn't be using VB6 if Microsoft had ever provided a replacement.  Sadly it is the only general purpose high level language native compiler they ever produced for Windows.
Comment: Oh, I still love VB6. It's just that it is so old and unsupported, that when you try to use it with anything newer, you run into issues like this. It can be easy to forget how many things came out *after* VB6, and thus it may not handle easily out of the box.
Answer: You are going to need to do it as you currently are, that flag is not supported by the VB6 linker:
A@ALEX C:\Program Files (x86)\Microsoft Visual Studio\VB98
> link /OUT:x.exe /TSAWARE x.obj
Microsoft (R) Incremental Linker Version 6.00.8168
Copyright (C) Microsoft Corp 1992-1998. All rights reserved.

LINK : warning LNK4044: unrecognized option "TSAWARE"; ignored

Comment: As I said in my answer, you can specify that you want this by hand-editing your .VBP files and adding the undocumented `[VBCompiler]` section.
Comment: Testing seems to prove this to be an incorrect statement.  Works just fine here.
Comment: @Bob77 Are you saying that you can specify /TSAWARE in VB6 Visual Studio?  Where and how?  I can't find anywhere that linker options are specified in the IDE.  However you are right about linker supporting /TSAWARE.  Note my linker is later than Alex K.

C:\Program Files (x86)\Microsoft Visual Studio 6.0\VB98>link
Microsoft (R) Incremental Linker Version 6.00.8447
Copyright (C) Microsoft Corp 1992-1998. All rights reserved.

usage: LINK [options] [files] [@commandfile]
   options:
      /ALIGN:#
 . . .
      /SWAPRUN:{CD|NET}
      /TSAWARE[:NO]
      /VERBOSE[:LIB]
  . . .
Answer: Actually the "VB6 linker" (VS 6.0 LINK.EXE) does indeed support this flag.  Of course you may have to be sure you have installed the VS 6.0 service packs through at least SP6.
To invoke this you can edit your Project's .VBP file, adding the section:
[VBCompiler]
LinkSwitches=/TSAWARE

Using a later "Microsoft (R) COFF/PE Dumper Version 8.00.50727.42" to dump the compiled EXE for confirmation, it shows as 8000 DLL characteristics Terminal Server Aware.
As far as I know this has worked for a very long time, perhaps since Service Pack 3.
Comment: So the only way to do it is to edit the VBP file directly?  There's no user interface for this in Visual Studio 6?
Comment: If by "Visual Studio 6" you are talking about the VB 6.0 IDE (the VS 6.0 IDE itself does not support VB 6.0) then no, there is no UI access provided.  However there may be 3rd party add-ins or add-ins from Microsoft that they shared with certain classes of customers such as Partners.  Or you might make your own.


The distances on totally geodesic submanifold and manifold.

Question: There is a conlusion that the distances on a totally geodesic submanifold $M^{n} \subseteq N^{n+p}$ are the same with the distances on $N^{n+p}$(if we need we can add completeness). But I do not know how to prove it(Seems to be obvious)? Is there any proof or references about the question?
Comment: What is the definition you consider for totally geodesic?
Comment: @Didier In the general means. The second fundemental form vanished.
Comment: Then show that a geodesic in $N$ is in fact a geodesic in $M$ thanks to the equality $\nabla^M_{\gamma'}\gamma' = \nabla^N_{\gamma'}\gamma' + II(\gamma',\gamma')$. If $N$ is complete, the distances are thus the same.
Comment: Are you sure the conclusion is true?
Comment: You're totally right, we cannot conclude anything about the distances
Comment: This is a nice question. And I fell in the trap until @JasonDeVito alerted me. Of course, we have a geodesic that stays in $M$, but no one says it's the shortest one joining the points in $N$. Perhaps Jason should write an answer. :)
Comment: @TedShifrin:  Done!
Answer: As I mentioned in a comment above, this is not true as stated.
Perhaps the simplest counterexample is the following.  Let $N = S^1\times S^1$ be a flat torus, with each circle factor of total length $1$.  Envisioning this as square with sides identified, it is easy to see that it has diameter $\frac{\sqrt{2}}{2}$.
Now, for $k\in \mathbb{Z}$, consider the geodesic $\gamma_k:[0,1]\rightarrow N$ with $\gamma_k(t) = (t, kt)$.  Then $\|\gamma'(t)\| = \sqrt{1+k^2}$.   By inspecting the first coordinate, it is clear that $\gamma_k$ is injective, except that $\gamma_k(0) = \gamma_k(1)$.  In particular, the length of $\gamma_k$ is $\sqrt{1+k^2}$.
Take $N$ to be the image of $\gamma_k$, which is a totally geodesic submanifold of $M$.  From the calcuation in the previous paragraph, we see that $d_N(\gamma_k(0),\gamma_k(1/2)) = \frac{\sqrt{1+k^2}}{2}$.  For $|k| > 2$, it now follows that $d_N(\gamma_k(0),\gamma_k(1/2)) > d_M(\gamma_k(0), \gamma_k(1/2)).$
Comment: Ah, very nice. I was thinking about alteringing the Euclidean metric in $\Bbb R^3$ off a fixed plane to make a shorter path by venturing off the plane.
Comment: @TedShifrin:  I also like your example, because it gives examples where the totally geodesic submanifold can have arbitrary dimension and codimension.  And, for people like me who prefer compact spaces, one can just adapt Ted's example to lie in $T^k$.


What causes these cracks on top of window corners?

Question: Today i suddenly saw this crack coming up in top corner of a window. I am curious to why such a thing happens. Is it normal or can be a sign of bigger problem like foundation issue??
Window is not difficult to open.
house is 4 year old and i am in NW arkanses where it has suddenly gone cold in last month
is this just a paint crack or dry wall crack and can we stop it from getting worse?
Comment: "Is it normal or can be a sign of bigger problem like foundation issue?" Yes.
Comment: The type of construction we're looking at is fairly important to know. Please revise to add that, along with home age, location (climate), etc.
Comment: @FreeMan you just said yes.. i hope it was Yes to that its normal
Comment: Yes, it could be either. If the crack propagates farther, start suspecting some settling (or past settling cracks that weren't patched correctly). Note that minor settling is common and harmless. If it goes on, get an engineer to evaluate it. My century-old place was stabilized only after one corner was an inch higher than the rest -- but it _is_ now stable and if you can tolerate that tilt it's good for another century, despite having been thrown together as factory-worker housing.
Answer: Those type of cracks are the result of normal expansion and contraction. Often they manifest as the weather gets colder. The normal solution is caulking with a flexible and paintable latex caulk and touching up with matching paint.


Migration to  Selenium 2 from Selenium1 :Unable to find any elements using XPath or CSS

Question: I am trying migrate to Selenium 2 (WebDriver) from Selenium 1 (rc).
I have replaced the below code with the Firefox driver upon which my browser opens and runs:
Selenium selenium = new DefaultSelenium(
    "localhost", 4444, "*firefox", "http://www.yoursite.com");
selenium.start();

My problem is that Selenium cannot find any elements using XPath or CSS, just id seem to work so far. I have tried using different XPath and css locators, as well as DOM, but they don't work. The Selenium migration guide said finding elements by XPath or CSS Selectors does not  always work but they don't  seem to work for me at all.
Below is an example of an element I am trying to identify along with the CSS identifier I am trying to use, which works in selenium 1 and in the Selenium IDE :

css=[title='Actions']

Answer: Try css=div[title='Actions'].  You need to specify an element to match the attribute on.  Or if you want any element, css=*[title='Actions']
Comment: Is it a requirement for Selenium CSS locators to specify a type or universal selector for attributes? `[title='Actions']` is valid CSS and will match the same thing as `*[title='Actions']`, so I see no reason it shouldn't work here unless it's a Selenium-specific thing.
Comment: I tried css=div[title='Actions'] in the ide and it worked but in the code it doesn't
Comment: It's a CSS Selector requirement to have an element.  Browsers tend to guess what you want, but staying strict gives you a better chance of working.  http://www.w3.org/TR/CSS2/selector.html
Comment: Post the exact code that you are using the selector in, please.
Comment: @Nialscorva: Where does it say that it's a requirement to have a type or universal selector with an attribute selector?
Comment: @BoltClock my bad.  Section 5.3 explicitly says that you can omit the universal selector on attributes.  Sorry for the misinformation.
Answer: You might want to take a look at 2.19, it supposedly makes the migration from 1.X to 2.X much easier.
Is there any reason you aren't searching on the ID?  It's much faster anyhow.


How to implement debounce in typeahead.js?

Question: I am writing a search functionality using typeahead.js. I am trying to figure out how debounce can be implemented for the search feature. I went through the typeahead docs, but I couldn't find any relevant information. How to implement the debounce in typeahead? The code is shown below.
<code>$('input.typeahead').typeahead({
  name: 'movies',
  remote: 'http://localhost:3000/searchMovie?key=%QUERY',
  limit: 10
});
</code>
Comment: Javascript typehead using debounce: https://codereview.stackexchange.com/questions/175434/javascript-typehead-using-debounce
Answer: If you are using bloodhound with twitter's typeahead.js library, there is a native option for debouncing the input for the remote lookup.
bloodhound remote twitter typeahead doc on github
<code>var my_bloodhound = new Bloodhound({
    name : 'search_filter_' + my_filter,
    datumTokenizer : Bloodhound.tokenizers.obj.whitespace('name'),
    queryTokenizer : Bloodhound.tokenizers.whitespace,
    limit : 20,
    prefetch : {
        url : '/my_search.php?filter=' + my_filter,
        filter : myFilterSearchTypeaheadResponse
    },
    remote : {
        wildcard : 'LOOKUP',
        url : '/my_search.php?filter=' + my_filter + '&query=LOOKUP',
        rateLimitBy : 'debounce',
        rateLimitWait : 600,
        filter : myFilterSearchTypeaheadResponse
    }
});
my_bloodhound.clearPrefetchCache();
my_bloodhound.clearRemoteCache();
my_bloodhound.initialize();
</code>


How to get only first letters from string in C#

Question: I am new to C# and I am using windows forms.
I am dealing with Postcodes string and I am trying to get the first letters from the Post code and store it in a variable, for example:
BL9 8NS    (I want to get BL)
L8 6HN     (I want to get L)
CH43 7TA   (I want to get CH)
WA8 7LX    (I want to get WA)
I just want to get the first letters before the number and as you can see the number of letters can be 1 or 2 and maybe 3.
Anyone knows how to do it?  Thank you
Comment: Using a Regex pattern would likey be the easiest option.
Comment: I had a look here but no luck.
Comment: https://stackoverflow.com/questions/7316258/how-to-get-only-letters-from-a-string-in-c
Comment: https://stackoverflow.com/questions/17096494/counting-letters-in-string
Answer: Since string imlements IEnumerable<char>, using Linq TakeWhile and char.IsLetter would be very easy:
string firstLetters = string.Concat(str.TakeWhile(char.IsLetter));

Answer: Use a regex with a group to match the first letters.
This is the regex you need:
^([a-zA-Z]+)

You can use it like this:
Regex.Match("BL9 8NS", "^([a-zA-Z]+)").Groups[1].Value

The above expression will evaluate to "BL".
Remember to add a using directive to System.Text.RegularExpressions!
Comment: I'm not in America so I'd agree simply because post codes don't have any letters.
Op uses post code as example but please consider other people who find this question later with different requirments.
Also, who ever trusted a user to input perfect data. ^([a-zA-Z]+) should match everything.
Comment: This pattern does not match strings beginning with a lower case alpha
Comment: @Joe_DM As far as I'm concerned, post codes don't have lowercases, right?
Answer: You can use StringBuilder and loop through the characters until the first non-letter.
string text = "BL9 8NS";
StringBuilder sb = new StringBuilder();
foreach(char c in text) {
    if(!char.IsLetter(c)) {
        break;
    }
    sb.Append(c);
}
string result = sb.ToString(); // BL

Or if you don't care about performance and just want it simple, you can use TakeWhile:
string result = new string(text.TakeWhile(c => char.IsLetter(c)).ToArray());

Comment: @Mhd.Tahawi Are you saying, loop to find the indexOf the first non alpha, then break the loop and do a substring.... I could get on board with that! :)
Comment: @Mhd.Tahawi the sample posted by the op is small, but who knows how long this could be in production? What if the string has 1000 characters before the first non numeric? `string` is immutable and so we wouldn't want to create 1000 new reference type objects on the stack.
Comment: why the string builder?
Comment: @Mhd.Tahawi Faster than concatenating to a string.
Comment: @Joe_DM, True, maybe I was not clear. why loop and concatenate when you can just do substr
Comment: @Joe_DM, here is what I meant (one more answer :D )
Answer: What about
string result = postcode.Substring(0, postcode.IndexOf(postcode.First(Char.IsDigit)));

If your postcodes will always contain that digit, First won't throw any exception.
Comment: there are many non alpha numeric characters that could appear before a didgit. perhaps `postcode.First(!Char.IsLetter)` ?
Comment: `FirstOrDefault` won't thow an exception if you're worried about that.
Comment: But `Substring` will in that case (with `FirstOrDefault`)
Comment: Good point, I guess this would need a few external guard clauses to prevent it becoming buggy. Either way, It's a good hint for the op and points him in the right direction :)
Answer: char[] numbers = new char[]{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

string a = "BL9 8NS";
string result = a.Substring( 0, a.IndexOfAny(numbers) );
Console.WriteLine( result );

Comment: What about when whitespace appears first, or another non alphanumeric character?
Comment: They will be displayed, i.e.: a = "> BL9 8NS", result is = "> BL"
Comment: I was thinking about an input value like this "BL ♣ 9 8NS"
Comment: a = "BL ♣ 9 8NS", result = "BL ♣"
Comment: While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.
Answer: While the answer of Ofir Winegarten is really great, I up-voted it, I wanted to share my answer I wrote before the sudden power cut!
string code = "BL9 8NS";
string myStr = "";
for (int i = 0; i < code.Length; i++)
  {
     if (char.IsNumber(code[i]))
         break;
     else
         myStr += code[i];
  }

Comment: `int.TryParse(code[i].ToString(), out int _n)` - just NO-NO-NO! In .Net you can use char.IsXXX() methods, where XXX - is one of the Unicode categories. char.IsDigit() is one of them. It is much faster and easier to read


How to diagnose a problem in a Jet AFS-1000B Air Filtration system

Question: I've had a Jet Air Filtration unit (AFS 1000B) system for years and it's worked perfectly.  Recently I took out the filters for cleaning.  When I put them back the unit would not start.  All of the lights came on (ALL of them, including lights that should not be on at the same time) but the unit does not start.
Does anyone have any idea where to start in diagnosing the problem?
Comment: When you put the filters in place they may push a tab or button which must be depressed for the unit to operate. This would be to insure that the unit is not operated without a filter in place. Remove the filters again and see if there is an interlock like this which is somehow not depressed the way the filters are currently in place. It might be that the order of the filters is important and the interlock is to insure that the filters are in the correct order. There could be *two* interlocks and one must be depressed and the other extended.
Comment: Did you try contacting Jet directly?
Comment: Are there any error codes in the manual?
Comment: Nope, none at all
Comment: I took a quick look last night and didn't see anything - I'll take a more thorough look tonight
Comment: No word back yet
Comment: A safety interlock sounds logical since the filters were changed+. I was thinking the same thing.
Comment: I just checked - there are no switches of any kind near the filter.
Answer: My AFS1000B air filter system started acting up after several years of use. In my shop I have it plugged into the same circuit where I have several fluorescent light fixtures connected. Over the years I have replaced several of the fluorescent fixtures with LED fixtures. My remote stopped cycling through the time selections and the fan would not run for very long before it would automatically shut off. I fixed this issue by removing the remaining two fluorescent light fixtures and replaced them with LED. So obviously it had something to do with Fluorescent fixtures, or perhaps my fluorescent fixtures got too old but anyway, it is working fine now, so for whatever it's worth it might be useful to disconnect the fluorescent fixtures and see if the fan will operate properly


How to aggregate rows in a data frame based on string match in R? - regex

Question: I'm working with a data frame that contains around 200 rows, I want to remove duplicated rows, adding together the values in the 'minutes' column. I'm fairly new to R and I haven't found a way to do this. Does it involve applying regex? I would really appreciate any solution!
The data frame I have looks like this:
df <- data.frame(name = c("Adam Tucker", "AdamTucker", "email@example.com", "adamtucker", "James Mirra", "JamesTMirra", "Sebastian F"), minutes = c(10, 3, 15, 2, 5, 1, 10))

                     name   minutes
              Adam Tucker      10
               AdamTucker       3
 email@example.com     15
               adamtucker       2
              James Mirra       5
              JamesTMirra       1
              Sebastian F      10

And the result I'm looking for would look like this:
       name    minutes
 Adam Tucker      30
 James Mirra       6
 Sebastian F      10

Thanks in advance!
Comment: Automatically recognising things like `"AdamTucker"` and `"firstname.lastname@example.com"` as belonging to the same person is not the simplest thing. Do you have any other information you can use to identify these people? Otherwise some manual cleaning may be required.
Comment: Unfortunately no, I don't have any other information. I was guessing that a programmatic solution wouldn't be enough - particularly for that case - but because I'm just a beginner in coding I thought of asking around just in case. And by the way, how would you solve this example manually? Thank you!
Comment: I would edit the data manually (in the original csv file or whatever), adding a new column `cleaned_name` where I wrote out the name for each row in a standardized form. After that, you could do the aggregation automatically.
Comment: Oh, got it. AndI can see how the manual cleaning can become a headache for big data frames!
Answer: Do you have a master list with all unique names ? You can probably look at pmatach package in R , or use sqldfpackage to use LIKE function
df <- data.frame(name = c("Adam Tucker", "AdamTucker", "email@example.com", "adamtucker", "James Mirra", "JamesTMirra", "Sebastian F"), minutes = c(10, 3, 15, 2, 5, 1, 10))
require(sqldf)
sqldf("select * from df where name LIKE '%adam%'")

#                       name minutes
1               Adam Tucker      10
2                AdamTucker       3
3 email@example.com      15
4                adamtucker       2

Then use levels to reassign each the same name or just add another column here with name say Adam Tuck as final version and merge with original data using name column as key.
Comment: I can ask for a master list with the final names! And I'll look up the pmatach package as well. Thanks!


How can I open secret doors in alien bases?

Question: The mission briefing for the alien base tells me that there are hidden doors that I can use .

I took over the Command Room, revealing the entire map of the alien base. It's pretty clear where all the secret doors are, but I can't seem to use them. No door icon appears when hovering the cursor over that wall section, and I also can't simply tell my guy to walk into the secret corridor. How do I use them?
Answer: After asking the question, it occurred to me that I should try free-targeting that section of wall. You can indeed blast a hole in it, allowing access to the corridor. I don't know if there are any other ways to get it open.
Comment: grenade the door, it will open.


Who should I appoint regents and partners?

Question: In Massive Chalice, you can appoint a regent and a partner to a keep. However, there is no explanation of what to look for in a suitable couple, other than to remember that they will be retired from combat.
In the default list, they are sorted by experience ... but I don't know if it's actually important.
As far as I can tell, their only purpose is to breed new heroes. Therefore, I tend to pick people with good traits and fertility, and ignore their attributes alltogether. I pick the "best" one as the regent, and the second best one as their mate.
However, I've read other places that the regent is the "dominant" one, but I don't know to what degree. Does it influence their class? Does the partner have any influence at all?
What considerations should I keep in mind, when appointing regents and partners?
Answer: When appointing a regent and their partner, prefer heroes with no relics, as they will keep their relics with them and so out of fights. The stats of the regent will also influence the stats of new heroes in their bloodline, thereby giving an incentive for using powerful heroes as regents. Also don't forget that heroes will die over time, and if they don't have any offsprings their bloodline will be lost with them. So you must consider carefully all of these in order to maximize the usefulness of your heroes.
Source1, Source2


git: Resetting/rebasing sub-repositories in a monorepository

Question: **

Installation:
  To get the right version of LLVM and clang follow the instructions to install from git and then rebase both to the specified versions.
  LLVM fa840e7dfb9115a3ac9891d898e7fe2543c65948
  clang 3e24ceaa26f9e1cbd67fdc8625f07bfcc9977053

**
Hi,
I've been trying to follow the above instructions to build llvm and clang from source code. The source code repo is one unified project which has llvm, clang and additional sub-projects. I'm having difficulty trying to figure out how to rebase/revert/reset the individual sub-repositories to specified hashes. I get "fatal: Needed a single revision" or "fatal: Could not parse object 'fa840e7dfb9115a3ac9891d898e7fe2543c65948'." if i try to rebase or reset it respectively.
Not sure if i am doing it right.
Answer: Most probably the hashes are from old "per-module" git mirrors. The hashes in the monorepo are different. You may probably need to find the corresponding SVN revisions to obtain new hashes


error installing package "devtools" in R

Question: <code>> install.packages("devtools")

Installing package into 'C:/Users/hyunj/OneDrive/문서/R/win-library/3.4'
(as 'lib' is unspecified)
also installing the dependency 'withr'

  There is a binary version available but
  the source version is later:
      binary source needs_compilation
withr  2.1.1  2.1.2             FALSE

trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.4/devtools_1.13.5.zip'
Content type 'application/zip' length 443954 bytes (433 KB)
downloaded 433 KB

package 'devtools' successfully unpacked and MD5 sums checked

The downloaded binary packages are in
    C:\Users\hyunj\AppData\Local\Temp\RtmpayZaSB\downloaded_packages
installing the source package 'withr'

trying URL 'https://cran.rstudio.com/src/contrib/withr_2.1.2.tar.gz'
Content type 'application/x-gzip' length 53578 bytes (52 KB)
downloaded 52 KB

* installing *source* package 'withr' ...
** package 'withr' successfully unpacked and MD5 sums checked
Warning in file(file, if (append) "a" else "w") :
  cannot open file 'C:/Users/hyunj/OneDrive/9.<-/R/win-library/3.4/withr/DESCRIPTION': Invalid argument
Error in file(file, if (append) "a" else "w") :
  cannot open the connection
ERROR: installing package DESCRIPTION failed for package 'withr'
* removing 'C:/Users/hyunj/OneDrive/문서/R/win-library/3.4/withr'
In R CMD INSTALL
Warning in install.packages :
  running command '"C:/PROGRA~1/R/R-34~1.3/bin/x64/R" CMD INSTALL -l "C:\Users\hyunj\OneDrive\문서\R\win-library\3.4" C:\Users\hyunj\AppData\Local\Temp\RtmpayZaSB/downloaded_packages/withr_2.1.2.tar.gz' had status 1
Warning in install.packages :
  installation of package 'withr' had non-zero exit status

The downloaded source packages are in
    'C:\Users\hyunj\AppData\Local\Temp\RtmpayZaSB\downloaded_packages'
</code>
Answer: it looks like you have localization problem. All localization problems are hard to debug. Your problem looks like to be in your path probably
<code> C:/Users/hyunj/OneDrive/문서/R/win-library/3.4
</code>
If it would be possible to change the "문서" part for something else it might help.


Allocation of variables in CUDA C++ - unable to allocate device variable

Question: I'm trying to process .bmp file with filter on GPU. For this I need to allocate and fill variable d_bufferRGB on device. But when I do so, my compiler just tells me it is defined on host and end with error "identifier d_bufferRGB is undefined". Functions load_BMP and save_BMP are fully functional. I need to know how to copy bufferRGB into d_bufferRGB, cause obviously I am doing some mistake.
Can you please help me ?
The source code is here >>>
  #include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include <cuda_runtime.h>
#include <cuda.h>
#include "device_launch_parameters.h"
#include <iostream>
//using namespace std;

int width, heigth;
long size, *d_size;
RGBTRIPLE *bufferRGB, *new_bufferRGB;
RGBTRIPLE *d_bufferRGB, *d_new_bufferRGB;

void load_bmp(RGBTRIPLE **bufferRGB, int *width, int *heigth, const char *file_name)
{
    BITMAPFILEHEADER bmp_file_header;
    BITMAPINFOHEADER bmp_info_header;
    FILE *file;

    file = fopen(file_name, "rb");

    fread(&bmp_file_header, sizeof(BITMAPFILEHEADER), 1, file);

    fread(&bmp_info_header, sizeof(BITMAPINFOHEADER), 1, file);

    *width = bmp_info_header.biWidth;
    *heigth = bmp_info_header.biHeight;
    size = (bmp_file_header.bfSize - bmp_file_header.bfOffBits);

    int x, y;
    *bufferRGB = (RGBTRIPLE *)malloc(*width* *heigth * 4);

    fseek(file, bmp_file_header.bfOffBits - sizeof(bmp_file_header) - sizeof(bmp_info_header), SEEK_CUR);

    for (y = 0; y < *heigth; y++)
    {
        for (x = 0; x < *width; x++)
        {
            (*bufferRGB)[(y * *width + x)].rgbtBlue = fgetc(file);
            (*bufferRGB)[(y * *width + x)].rgbtGreen = fgetc(file);
            (*bufferRGB)[(y * *width + x)].rgbtRed = fgetc(file);
        }
        for (x = 0; x < (4 - (3 * *width) % 4) % 4; x++)
            fgetc(file);
    }
    fclose(file);
}

void save_bmp(RGBTRIPLE *bufferRGB, const char *new_name, const char *old_name)
{
    BITMAPFILEHEADER bmp_file_header;
    BITMAPINFOHEADER bmp_info_header;
    FILE *file;

    file = fopen(old_name, "rb");

    fread(&bmp_file_header, sizeof(BITMAPFILEHEADER), 1, file);

    fread(&bmp_info_header, sizeof(BITMAPINFOHEADER), 1, file);
    fclose(file);

    file = fopen(new_name, "wb");

    fwrite(&bmp_file_header, sizeof(BITMAPFILEHEADER), 1, file);
    fwrite(&bmp_info_header, sizeof(BITMAPINFOHEADER), 1, file);
    fseek(file, bmp_file_header.bfOffBits - sizeof(bmp_file_header) - sizeof(bmp_info_header), SEEK_CUR);

    int alligment_x = (4 - (3 * width) % 4) % 4;
    unsigned char *to_save = (unsigned char *)malloc((width * 3 + alligment_x)*heigth);
    unsigned int index = 0;
    int x, y;

    for (y = 0; y < heigth; y++)
    {
        for (x = 0; x < width; x++)
        {
            to_save[index++] = bufferRGB[(y * width + x)].rgbtBlue;
            to_save[index++] = bufferRGB[(y * width + x)].rgbtGreen;
            to_save[index++] = bufferRGB[(y * width + x)].rgbtRed;
        }
        for (x = 0; x < alligment_x; x++)
            to_save[index++] = 0;
    }
    fwrite(to_save, (width * 3 + alligment_x)*heigth, 1, file);

    fclose(file);
    free(to_save);
}

__global__ void CUDA_filter_grayscale()
{
    int idx = blockIdx.x*blockDim.x + threadIdx.x;
    BYTE grayscale;

    if (idx < *d_size)
    {
        grayscale = ((d_bufferRGB[idx].rgbtRed + d_bufferRGB[idx].rgbtGreen + d_bufferRGB[idx].rgbtBlue) / 3);
        d_new_bufferRGB[idx].rgbtRed = grayscale;
        d_new_bufferRGB[idx].rgbtGreen = grayscale;
        d_new_bufferRGB[idx].rgbtBlue = grayscale;
    }
}

int main()
{

    //GPU cast ----------------------------------------------------------------------------------------------

    cudaMalloc((void**)&d_new_bufferRGB, width*heigth * 4);
    cudaMalloc((void**)&d_bufferRGB, width*heigth * 4);
    cudaMalloc((void**)&d_size, sizeof(size));

    load_bmp(&bufferRGB, &width, &heigth, "test.bmp");

    cudaMemcpy(&d_size, &size, sizeof(size), cudaMemcpyHostToDevice);
    cudaMemcpy(d_bufferRGB, bufferRGB, sizeof(bufferRGB), cudaMemcpyHostToDevice);

    CUDA_filter_grayscale << <256, 512 >> >(); //size dont bother me for now

    cudaMemcpy(d_new_bufferRGB, new_bufferRGB, sizeof(new_bufferRGB), cudaMemcpyDeviceToHost);

    save_bmp(new_bufferRGB, "filter_grayscale_GPU", "test.bmp");

}

Answer: Kernels cannot access host-code variables (such as the variable d_bufferRGB). If you need access to a host-code variable in a kernel, you need to pass it to the kernel as an argument:
__global__ void CUDA_filter_grayscale(const RGBTRIPLE *d_bufferRGB, RGBTRIPLE *d_new_bufferRGB)
{
    // Code same as before
}

// Usage in main():
CUDA_filter_grayscale << <256, 512 >> >(d_bufferRGB, d_new_bufferRGB);

Comment: Thx a lot. I was bothering with this for 2 days and wasnt able to find answer.


How can I seal a two inch gap in the floor along a wall?

Question: I have almost a 2 inch gap between my wooden floor and wall in the apartment I am renting. I think the dust down there is causing me allergies and I'm worried about the cold AC air escaping down there. Is there a REALLY quick easy way that I can fix it that my landlord is likely to approve? The hole down there is about 10 inches - it is through the floor not just the hardwood planks.
The floorboard are on top of old floorboards that do not line up and neither reach the wall. The coin is a 5 cent coin. Thanks again!
Comment: Does the gap run the entire length of the wall, or is it just one small section?
Comment: Duct tape is about 2".  Since it sound like you're just needing to fill an unfinished gap, would a few layers of that work? (Picture would help a lot).
Comment: Semantics:  Dust does not "cause" allergies. One can be allergic to dust but dust does not make you allergic to things. Perhaps you mean to say *you **think** you are having an allergic reaction to the dust*.
Answer: Without seeing it, my first inclination is to get some extruded foam board (not beadboard/Styrofoam--it's too messy) of suitable thickness (3/4" for just the depth of the hardwood, 1" or 1-1/2" for hardwood plus subfloor). Using a utility knife and a straightedge, cut strips that will fit snugly in the gap. Press them in by setting the inner edge against the floor and tilting the wall side down.
If you fit them well they'll be self-supporting and make a great seal. That said, this probably isn't the only air access to the floor framing. If there's significant air movement between floors you may not solve the problem with this patch.
Answer: This is what "baseboard" is for. If you are renting, your landlord should be amenable to installing baseboards for you, they are a standard way of taking care of that gap between a wall and floor that always exists.
If you end up having to do it yourself, you can buy vinyl (rubber) baseboard strips (also called "wall cove base") that are over 2" high and come with peel-and-stick adhesive on the back. Very simple to install and can be cut to length with basic heavy duty scissors (like "kitchen shears" or cut with a razor knife.
Comment: Except in this case, I think the gap is in the floor, not the wall.  I.e. the photo is shot from directly above, with the wall at the bottom.  This baseboard is a good suggestion, but instead of covering a bit of the floor and the lower three or four inches of the wall, it would have to be installed the opposite way, so that it covers a bit of the wall and three or four inches of the floor.
Comment: Oh... duh! The nickel in the photo would have had to have been glued there in my scenario! I'm so embarrassed...


How can I remove this screw?

Question: Any one know how to open this screw?
Tried pliers but no avail and standard box of security  screwdrivers couldnt open it.

Here are some more photos
Answer: Those are external line head screws, and are used as anti-tamper screws in some Japanese electronics.  You can probably find a driver for them from a game console hack supplier (they're used on Gamecube, Wii, and some other game consoles).  The driver looks like this (sorry for the horrible pic):

They also come in 5 and 7 point varieties (hard to tell how many points from the picture you posted).  I've also seen them called torx inverted.
If you don't want to get a specific driver for them, you can probably get them out by clamping on the head really hard with a pair of vise-grips or use a screw extractor.  You might be able to find a socket that will mesh with them well enough, but that's a long shot.
Comment: Looks like possibly a watch crab or adjustable spanner (where spanner means specifically "two-pin style") wrench **might** be made to work. There's also always the option of welding a nut to them ;-)
Answer: If it's a screw, a couple of ideas:

You can use a dremel to cut a slot in the screw head and then use a normal screwdriver on it.
Get an old toothbrush. Head up the handle with a lighter or a heat gun. When it gets hot, press it over the screw head. Hold it until it cools. That gives you a custom screwdriver. Press hard when you use it.
Answer: It looks like a rivet, in that case you will have to cut it off or try to pry the head off.
It also looks like it has 6 tabs, you might be able to get a 6-sided socket on it and break the head.
Answer: You can use a pipe wrench for this. If you use it "downwards" the wrench tightens itself on the screw. It is a little tricky because you have to make sure the wrench stays on the screw of course.

How can I remove this screw?


How to leave low voltage wiring behind wall?

Question: I am having a new home built and I am putting in my own low voltage wiring.
In addition to standard network wiring, I am hoping to install CAT6 wiring for a few potential future tasks: surveillance cameras, security systems, etc.
However, I don't intend to actually wire these devices for quite some time -- I just want to put the wiring in the walls before the drywall is put up. When I put the equipment in later, I'll retrieve the wires behind the drywall.
My question is: What is the best way to do this? If I don't have a low voltage box that I'm running the wiring to, how do I keep a few feet of cable coiled up behind the wall that is:
a) easy to access later,
b) up to code, and
c) makes sense to other people working on the house why it's there.
Answer: The common practice for future expansion is to install the box and put a blank cover on it.
That eliminates the requirement of chopping into the drywall to find the wire. It also eliminates the need to create as-built documents and store them for future reference so you can find the wires later.
My recommendation is to install device boxes with ENT (referred to as "Smurf tube" since it is bright blue) connected to them from the basement or attic. Then when you decide to install a structured cabling system it can be the latest technology. Or, if you decide to update to fiber in the future you will have easy access to these boxes.
Communication / data is a dynamic field and planning for the future is difficult if you use a permanent wiring method stapled into the walls. In commercial buildings we normally install 4" square boxes with 3/4" conduit and single gang mud rings for the drywall. That way wiring can be easily replaced in the future.
Good luck!
Comment: Exactly.  Run conduit, add the wires later.  Yes, 3/4" conduit.   To be amateur-friendly, I aim for no more than one 90 degree bend between access points, I can usually push the wire through without having to use a fishing tape.
Comment: Thanks for the answer. I think that installing a box makes sense for interior network ports, speakers, etc. I am also interested in what the best approach would be for wiring for eventual outdoor motion detectors / surveillance cameras -- for those, I don't think there's a standard outdoor box to use -- or even if it's a good idea to put a hole in the exterior wall until I knew the nature of the final device to be installed.
Comment: The standard for an outdoor box is a "bell" box. Just google "bell box" and you will see pictures of them. I don't like the looks of them myself and I normally cut device boxes in to the exterior wall for devices. No matter what device you select the standard for mounting is a device box. Some have adapter plates for round boxes but any device worth the money will mount to a device box. You can install the boxes and wire and then put a gasketed blank cover on it until later.


MySQL Workbench error while accessing configuration

Question: After installing MySQL Community Server 5.59 (64bit) and MySQL Workbench 5.2.31a and setting it up I try accessing the db's configuration and receive the following error:

Configuration file 'C:\Program Files\MySQL\MySQL Server 5.0\my.ini' can not be found. New file will be created on apply of changes.

I click OK. Then when trying to apply any change I get a second IO Error for not being able to write to the file.
It figures as my installation is at C:\Program Files\MySQL\MySQL Server 5.5 and not at C:\Program Files\MySQL\MySQL Server 5.0. But why does Workbench search there?
Comment: Because workbench is a peice of @#$%. Workbench does not keep up with mysql. Every time there is a change to mysql almost everything breaks in workbench (in the latest workbench even simple things don't work - like adding a user http://bugs.mysql.com/bug.php?id=58938). I wouldn't rely on it for anything. I have encounted nothing but endless crashes and error message while trying to do the simplest of tasks.
Comment: @Myforkwik - I think that's actually an answer, I'll accept it if you write it :)
Answer: I had the same issue with MySQL Server 5.7 and MySQL Workbench 6.3. The solution is quite simple.

Open MySQL Workbench or switch to the home page with the connections
Click the small tool icon next to the label MySQL Connections
The Manage Server Connections dialog appears
Select the connection from the list of MySQL Connections
The Connection data for this connection appear to the right
Switch from the Connection tab to System Profile
Change the entry in the Configuration File field
Click the Close button and you are done

In my case all I had to do is to change the entry from:
%ProgramFiles%\MySQL\MySQL Server 5.0\my.ini
to
%ProgramData%\MySQL\MySQL Server 5.7\my.ini
Comment: I never worked with MySQL Workbench 5.2. Now, with Workbench 6.3 it might be much easier, but I posted this answer after I've been searching for a solution myself because that somewhat hidden entry is really hard to find.
Comment: Please not that I not only had to change the server version from 5.0 to 5.7 but also from __%ProgramFiles%__ to __%ProgramData%__ where already a preconfigured my.ini existed.
Answer: Try: You can change the base directory in
Server Administration-> Manager Server Instances > Local MySQL >system Profile > Configuration file : <your dir>\my.ini (Click the directory)
Comment: its unchangeable field, how i could make it possible to change the directory?
Answer: You need to create a New Server Instance in server administration section of Workbench. There you will be able to specify your .ini file location.
Comment: Exactly this, as soon as I deleted my old instance and registered a new one the correct .ini file was found. Jut make sure you MySQL server is running at the time so workbench knows what service to connect to.

Running Windows 7 and XAMPP by the way.
Answer: Your Server instance is registered wrong.
When you create new server instance for server administration in workbench, there is a selected option, e.g.:

Mysql Installation Type:
  Window(MySQL5.0 x64 Installer Package)

If you selected a wrong one with your current OS and Server installation, it would result an incorrect base path mapping.
To solve your issue,  you can change the base directory in Server Administration-> Logging the instance -> Configuration Menu -> Configuration -> General:
1) Click the base directory checkbox
2) Input the path e.g.

"C:/Program Files/MySQL/MySQL Server
  5.1/"

3) Click the data directory checkbox
4) Input the path e.g.

"C:/Documents and Settings/All
  Users/Application Data/MySQL/MySQL
  Server 5.1/Data/"
Comment: I tried it and when clicking apply it errored out again. It can't change configuration as it can't access the configuration file...
Answer: Jonathan, when I looked upon your question for which I was originally searching I found the answer few minutes later.
To connect them as you already probably know but a lost soul may learn from this is that the configuration file we are talking about is not presented inside MySQL. It is located in
C:\Program Files (x86)\wamp\alias
Of course, figure it out for ourselves where your wamp is located if you are using it. In my case the desired file was in alias folder.
I hope this would help someone with my case.
Best regards and blessings.


Where is the documentation for the "path" taskelement in Ant?

Question: I must be missing something obvious here... I found the online documentation for the <property>  task, but I can't find it for the <path> task, e.g.:
<path id="client.classpath">
   <fileset dir="${libDir}">
       <include name="*.jar"/>
   </fileset>
</path>

Where is <path> documented?
Answer: Right here: Path-like Structures in Ant manual.
Comment: The Ant docs are pretty bad, to be fair. They need some serious attention.
Comment: oh. {sheepish look} I guess I was expecting a separate page that had "" at the top.
Comment: Ant needs to be taken out and shot.  Thanks for the  tag reference, though!


Unknown host 'repo.maven.apache.org'. You may need to adjust the proxy settings in Gradle

Question: I have the above issue when I try to build my react native application using android studio
my Gradle version:6.3
I tried to update the Gradle version and set the proxy to auto in android studio but still stuck in the same issue,
Answer: You can try enabling auto detect proxy in Setting > Appearance & Behaviour > System Settings > Https Settings
I faced the same error today and found that doing the above fixes it


Regular expression to extract fractions

Question: I am looking for a regex to match the fractions of format [0-9]\/[1-9]{1,2} in a given string.
Below is an example:
my_str = "This is a 1/2 1/4. Press 1/2/3. He drove a car for 1/2hour." # A free text

def replace_fractions(text):
    fraction_dict = {
        '1/2': 'half',
        '1/4': 'quarter',
        '3/4': 'three quarters',
        '2/3': 'two thirds',
    }
    _tmp = ' '.join([fraction_dict.get(w, w).strip() for w in text.split()])
    return _tmp

current_result = replace_fractions("This is a 1/2 1/4. Press 1/2/3. He drove a car for 1/2hour.")

current_result:
"This is a half 1/4. Press 1/2/3. He drove a car for 1/2hour."
expected_result:
"This is a half quarter. Press 1/2/3. He drove a car for half hour."
It is clear that regex needs to be used to handle cases like 1/2/3 or 1/4. or 1/2hour.
But, this [0-9]\/[1-9]{1,2} matches everything. What will be the right regex to handle these cases.
Note: The regex need to only handle the above cases. All extreme cases can be ignored (or will be re-edited after expert comments)
Comment: I can suggest a solution without using regex if you want
Comment: should start the denominator range from 1 instead of 0.
Comment: @bhansa: yes - edited the question
Comment: @AmirHmZ: that will be great to know how it can be done.
Answer: You may use the following return in your method:
return re.sub(r'(?<!\d)(?<!\d/)[0-9]/[0-9]{1,2}(?!/?\d)', lambda x: fraction_dict.get(x.group(), x.group()), text)

See the Python demo. Note the space between half and hour is missing, because it was missing in the input. You would need to add more logic to add the space only in expected cases.
Details

(?<!\d)(?<!\d/) - a digit or a digit and / are not allowed immediately on the left
[0-9]/[0-9]{1,2}  - a digit, / and 1 or 2 digits
(?!/?\d) - immediately to the right, there should not be / + digit or just a digit.

Full code snippet:
import re
my_str = "This is a 1/2 1/4. Press 1/2/3. He drove a car for 1/2hour." # A free text

def replace_fractions(text):
    fraction_dict = {
        '1/2': 'half',
        '1/4': 'quarter',
        '3/4': 'three quarters',
        '2/3': 'two thirds',
    }
    return re.sub(r'(?<!\d)(?<!\d/)[0-9]/[0-9]{1,2}(?!/?\d)', lambda x: fraction_dict.get(x.group(), x.group()), text)

current_result = replace_fractions("This is a 1/2 1/4. Press 1/2/3. He drove a car for 1/2hour.")
print(current_result)
# => This is a half quarter. Press 1/2/3. He drove a car for halfhour.

Regular expression to extract fractions


How to combine tables produced by stored procedure

Question: I have a stored procedure and it outputs value as table pf two columns. This is in SQL Server
exec infos @tablee = 'tem', @dbs = 'tempdb', @columns = 'revenue'

exec infos @tablee = 'tem', @dbs = 'tempdb', @columns = 'price'

When I execute this with separate values then it create separate tables for each execution. Is there any way to combine all tables into one .
max             5000
mean            5000
median          5000
min             5000
nulls              0
nun null count    24
std. dev           0
total         120000
total count       24

Another table
max              40
mean             40
median           40
min              40
nulls             0
nun null count   24
std. dev          0
total           960
total count      24

Comment: `SELECT * FROM TABLE1 UNION ALL SELECT * FROM TABLE2`
Comment: Create a temporary table. Then `INSERT INTO .... EXEC` twice followed by `SELECT FROM` your temporary table.
Comment: but its not table, the output is as a table. so i cant give the procedure in from clause
Answer: Your wording makes it sound as if the stored procedure is creating an actual table rather than simply outputting a dataset. I believe what you are asking is how to insert the output of a stored procedure into table and then display the output.
CREATE TABLE #tmpinfos
(
   stat_test VARCHAR(20),
   test_value INT
)

INSERT INTO #tmpinfos
exec infos @tablee = 'tem', @dbs = 'tempdb', @columns = 'revenue'

INSERT INTO #tmpinfos
exec infos @tablee = 'tem', @dbs = 'tempdb', @columns = 'price'

SELECT * from #tmpinfos

While the above works you need to also include the @columns in the output of the stored procedure so that you can separate 'revenue' and 'price' for obvious reasons. Or you can update after each insert:
CREATE TABLE #tmpinfos
(
   test_category VARCHAR(20),
   stat_test VARCHAR(20),
   test_value INT
)

INSERT INTO #tmpinfos(stat_test, test_value)
exec infos @tablee = 'tem', @dbs = 'tempdb', @columns = 'revenue'
UPDATE #tmpinfos SET test_category = 'revenue' WHERE test_category IS NULL;

INSERT INTO #tmpinfos
exec infos @tablee = 'tem', @dbs = 'tempdb', @columns = 'price'
UPDATE #tmpinfos SET test_category = 'price' WHERE test_category IS NULL;

SELECT * from #tmpinfos


continue jacoco code coverage report after fail test case

Question: Code coverage report not generated when Test case failed in android studio using Jacoco plugin.How to skip failed test case and generate code coverage report.
Comment: Did u got the solution to generate the coverage report when test case fails?
Comment: https://stackoverflow.com/questions/20142486/dont-fail-the-gradle-build-if-a-test-is-failing-with-the-gradle-android-test-pl/25587012#25587012 This may help you. Follow the above link
Answer: Try adding this flag when running your test
-Djacoco.haltOnFailure=false
Answer: Use the following code in Build.gradle(Module:app):
android {

 testOptions {
    unitTests.all {
        setIgnoreFailures(true)
    }
}

buildTypes {
    debug {
        testCoverageEnabled true
        }
    }
}

Comment: It would be better to add a little bit of commentary to this answer, to explain how it answers the question, and what side-effects there might be. For example, does `setIgnoreFailures(true)` only apply to the coverage report, or does it mean that a build will be considered successful even with failed builds?
Comment: is it working if i try this this didn't worked for me
Answer: If you just need to get the report you can add the @Ignore above the tests in order to temporarily skip them.
When you take care of the reason these tests fail then you just remove the annotation.
This annotation will not run any of the marked tests, you can use it either at class file or at the method/test.
Comment: @Ignore is used to skip the class, not to generate coverage report, when any of the class fails in the test suite.


Encrypting page contents without SSL

Question: Is there any way to encrypt the page content so that robots and search engines can't access the content of the website at all. If yes what is the best method?
Comment: With a system that requires logging in, not "encryption".
Answer: Use your .htaccess to block all traffic.
order deny,allow
deny from all
allow from your.ip.address.

Answer: Use a robots.txt file to disable search engine indexing, and populate it like so:
User-agent: *
Disallow: /

Encrypting page contents without SSL


How can I test RESTful methods with Arquillian?

Question: I have a set of classes to work with REST methods in project. They look like this:
<code>@Path("customer/")
@RequestScoped
public class CustomerCollectionResource {

    @EJB
    private AppManager manager; // working with DB

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response list(@QueryParam("email") String email) {
        final List<Customer> entities = manager.listCustomers(email);
        // adding customers to result
        return Response.ok(result).build();
    }
}
</code>
After that I've wrote test method:
<code>@RunWith(Arquillian.class)
public class CustomerResourceTest {

@Deployment
public static WebArchive createTestArchive() {
        return ShrinkWrap.create(WebArchive.class, "test.war")
        // Adding omitted
        //.addClasses(....)
    }

    @Test @GET @Path("projectName/customer") @Consumes(MediaType.APPLICATION_JSON)
    public void test(ClientResponse<List<Customer>> response) throws Exception {
    assertEquals(Status.OK.getStatusCode(), response.getStatus());
    }
}
</code>
And I get NullPointerException when trying to run this test. It's because of empty response in test case. Why is this happens? DB is configured properly.
Answer: There are two modes an arquillian test can run: in-container and client mode. HTTP interfaces can be tested only in client mode (never tried the extensions, only used vanilla Arquillian for this).
By default the test methods executed in the context of the container, called by the arquillian test runner servlet.
<code>@RunWith(Arquillian.class)
public class CustomerResourceTest {

    @EJB SomeBean bean; // EJBs can be injected, also CDI beans,
                        // PersistenceContext, etc

    @Deployment
    public static WebArchive createTestArchive() {
        return ShrinkWrap.create(WebArchive.class, "test.war")
        // Adding omitted
        //.addClasses(....)
    }

    @Test
    public void some_test() {
        bean.checkSomething();
    }
}
</code>
In client mode, the test methods are running outside of the container, so you don't have access to EJBs, EntityManager, etc injected into the test class, but you can inject an URL parameter for the test method.
<code>@RunWith(Arquillian.class)
public class CustomerResourceTest {

    // testable = false here means all the tests are running outside of the container
    @Deployment(testable = false)
    public static WebArchive createTestArchive() {
        return ShrinkWrap.create(WebArchive.class, "test.war")
        // Adding omitted
        //.addClasses(....)
    }

    // baseURI is the applications baseURI.
    @Test
    public void create_account_validation_test (@ArquillianResource URL baseURI) {
    }
</code>
You can use this URL parameter to build URLs to call your HTTP service using whatever method you have, like the new JAX-RS client API.
You can also mix the two modes:
<code>@RunWith(Arquillian.class)
public class CustomerResourceTest {

    @EJB SomeBean bean;

    @Deployment
    public static WebArchive createTestArchive() {
        return ShrinkWrap.create(WebArchive.class, "test.war")
    }

    @Test
    @InSequence(0)
    public void some_test() {
        bean.checkSomething();
    }

    @Test
    @RunAsClient // <-- this makes the test method run in client mode
    @InSequence(1)
    public void test_from_client_side() {
    }
}
</code>
This is sometimes even necessary, because some extensions, like persistence cannot run in client mode.


Could you remove extra bangs from my swift?

Question: Could you suggest how to clean up this abomination
func restartLastSession(let extra : String?)
{
    let rescopes  = NSMutableArray(array: [ "restart" ])
    if(extra != nil && !(extra?.isEmpty)!) {
        rescopes.addObject(extra!)
    }

that transformed into
func restartLastSession(let extra_ : String?)
{
    let rescopes  = NSMutableArray(array: [ "restart" ])
    if let extra = extra_ where !extra.isEmpty {
        rescopes.addObject(extra)
    }

thanks to Eric D who did not allow me to wing reading the optionals chapter of the swift book
I suppose this is resolved with no provisions to contribute +10 to Eric's karma ;-)
Comment: "Optionals" chapter is all you need: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID330
Answer: Simplify by dropping unnecessary keywords (such as let), and by using true Swift arrays.
func restartLastSession(extra: String?) {
  var rescopes = ["restart"]
  if extra?.characters.count > 0 { rescopes.append(extra!) }

  // do something else with rescopes before returning, else it will be discarded
}


How to calculate the upper and lower sum of a definite integral using the darboux definition

Question: I have no idea how to calculate the L(f,P) and U(f,P) for this question. Can anybody please help me out?
$f(x) = -x, x\in[0,1];P=\text{{0,$\frac{1}{8}$,$\frac{1}{3}$,0.9,1}}$
Comment: The terms of lower sum are the infima (minimum in this case) of $f$ on the interval multiplied by the length of the interval. For example, on $[0, 1/8]$ you'd get $1/8(-1/8)$
Comment: So it'd be negative 1 in this case?
Comment: I'm still kinda confused.
Answer: Let's say $P=\{x_0, x_1 ,...,x_n\}$ then $$L(f,P)=\sum_{i=1}^n m_i (x_i-x_{i-1})$$
Where $m_i$ is the infimum of $f$ on the interval $[x_{i-1},x_i]$ (Which is like the minimum value). For example in your case $m_1 = -1/8$ since that is the minimum value of $f$ on $[0,1/8]$. So your first term in the sum will be $-1/8 \cdot 1/8$, since $1/8$ is the length of the first interval. Do this for the other intervals and add them all.
For the upper sum you do the same thing but use the supremum (maximum) of $f$ on the sub intervals.
Comment: so it'd be $\frac{-1}{64}$ plus the min for all the other intervals?
Comment: @deezythe next term will be $(1/3-1/8)\cdot -1/3. You have to multiply the min for each interval by the length of that interval
Comment: And for the max we just multiply by the max of that interval?
Comment: @deezy  That is correct.
Comment: Would the same rules apply if f(x) was a constant?


Zimbra not releasing space

Question: We are using Zimbra 8.0 collaboration server open source edition. (Release 8.0.0_GA_5434.RHEL6_64_20120907144639 CentOS6_64 FOSS edition ) on centos6.
While we deleting an Account or Emptying Folder , the free Space in HDD is not increasing.
For Example, If we deleted an account having 10GB size, only 1GB is getting added to Total free space of HDD.
In detail, I Emptied an Account having size 10.1GB.
The Space occupied by the Store Folder before deleting is 10.1 GB
/opt/zimbra/store/0/443 - 10.1 GB
After Emptying inbox folder the size of the store folder reduced to 100 MB.
/opt/zimbra/store/0/443 - 100 MB
(Emptied using command zmmailbox -z -m firstname.lastname@example.com emptyFolder /Inbox)
But NO change in "df" output. The Total free space remains the same.
Accordingly, Space is not releasing while deleting an account.
Anyone Please help to find a solution in this issue.  What need to be done to get free space added to HDD. Help needed.
Comment: Your question is off-topic here, please post it at http://serverfault.com/
Answer: I don't know what your dumpster settings are, though they could be determined by a command like this:
zmprov ga email@example.com |grep Dumpster
zimbraDumpsterEnabled: TRUE
zimbraDumpsterPurgeEnabled: TRUE
zimbraDumpsterUserVisibleAge: 10d
zimbraMailDumpsterLifetime: 10d
I suspect that the messages are sticking around in the dumpster though.  You can clean them out with a command like this:
zmmailbox -z -m email@example.com -A emptyDumpster
Comment: In our server "zimbraDumpsterEnabled" is FALSE.

zimbraDumpsterEnabled: FALSE
zimbraDumpsterPurgeEnabled: TRUE
zimbraDumpsterUserVisibleAge: 30d
zimbraMailDumpsterLifetime: 30d

We also ran the command zmmailbox -z -m firstname.lastname@example.com -A emptyDumpster, but no change in free space.!

could you please give your suggestions..!

Zimbra not releasing space


Group Chat In Android

Question: I wanna implement very efficient group chat in android. How can I do that? Please give me your best suggestions and also some step by step tutorial will help me in this.
I want to do peer to peer chat and also group chat. So Both type of implementations I wanna implement. Any SDK is available there? Or Any java lib are there?
Please give me your best suggestions.
Thanks,
Jay Patel
Comment: Valid question. Been wondering this myself.
Comment: Thanks dude, I have one solution. But I am not sure. Can we implemented it using push notification service using C2DM thats now GCM?
Comment: I made a sample chat group chat application, but all it does is check for updates on my server every two seconds. I needed it for a proof of concept one day, but I don't know how to go about it.
Comment: ya that solution I may be very complicated.!! We need to do it very efficient. M I right?
Comment: The description of GCM actually sounds perfect. `This could be a lightweight message telling the Android application that there is new data to be fetched from the server (for instance, a movie uploaded by a friend), or it could be a message containing up to 4kb of payload data (so apps like instant messaging can consume the message directly).`
Comment: @EGHDK Yes We really need to go with GCM only.
Answer: Start with checking out Google's own Google Cloud Messaging. This lets you push messages to other devices. After that, you can google and see if you find any examples or tutorials and you are good to go!
Comment: I guess GCM is the way to go, but it seems almost too easy. Heh. I'll have to look into this again. @Jai let me know how you make out on this quest.
Comment: @EGHDK That's how it is when Google does something. Black magic I suspect. ^^ GL to you both.
Comment: @EGHDK Exactly dude GCM will be the best way for us.
Answer: Here is a sample code of Android Chat SDK developed using Applozic backend server and Chat SDKS.
https://github.com/AppLozic/Applozic-Android-SDK
PS: I am from Applozic
Answer: You need to submit form like this for making a persistent group:
private void setConfig(MultiUserChat multiUserChat) {
    try {
<code>    Form form = multiUserChat.getConfigurationForm();
    Form submitForm = form.createAnswerForm();
    for (Iterator<FormField> fields = submitForm.getFields(); fields.hasNext();) {
        FormField field = (FormField) fields.next();
        if (!FormField.TYPE_HIDDEN.equals(field.getType()) && field.getVariable() != null) {
            submitForm.setDefaultAnswer(field.getVariable());
        }
    }
    submitForm.setAnswer("muc#roomconfig_publicroom", true);
    submitForm.setAnswer("muc#roomconfig_persistentroom", true);
    multiUserChat.sendConfigurationForm(submitForm);

} catch (Exception e) {
    e.printStackTrace();
}
</code>
}

Group Chat In Android


Compass sprite path causing error

Question: I've tried many responses already, but for some reason I can't get this to work. The error is:
No files were found in the load path matching "sprites/*.png"

My config.rb code:
relative_assets = true
cache=false

Encoding.default_external = "utf-8"

#########
# 1. Set this to the root of your project when deployed:
http_path = "/"
http_generated_images_path = "../images";

# 2. probably don't need to touch these
css_dir = "../css"
sass_dir = "./"
images_dir = "../images"
images_path = "../images"
javascripts_dir = "../js"
environment = :development

line_comments = true

My folder structure:
css

images
- sprites

scss (config.rb located in scss folder)
- partials
- - _mixins.scss (the file where the error is occuring)

And in mixins:
@import "sprites/*.png";

Any ideas what's wrong with the paths?
Thanks for any help.
Answer: First question is: do you actually have any files in your sprites folder? If yes, try adding this setting:
generated_images_path = "../images"

http_generated_images_path will be used to define what is the final path for the generated image, in the final (compiled) css, so maybe the setting above (without http_) is the one you need. My project structure is different but it works fine for me, I have more settings pointing to the same path though, this is what I have:
images_dir = "/assets/img"
generated_images_path = "assets/img"
http_images_dir = "assets/img"
http_images_path = "assets/img"

If just the first one doesn't solve the problem for you, try maybe adding all these?
Worst case change your project structure so you don't have to go up one level to get the folder (not saying that this is the problem as it shouldn't be but well, testing is the best way to find out)
Comment: Thanks Paulo. There are images in there. I tried those extra options, but unfortunately it still didn't work. Thanks anyway.
Answer: I tried various options here. In the end I updated to Ruby 2.1.5 and turned off the Compass "save on build" plugin for Sublime, which seems to have fixed it. Not a perfect solution, but it works for now!

Compass sprite path causing error


running graphql example on command line resulting in unexpected token

Question: Was trying out the sample code given for graphql on the following link:
http://graphql.org/graphql-js/running-an-express-graphql-server/
When i try to start the server on command line ended up with Syntax Error : Unexpected Token
The error log is as follows:
<code> C:\Users\ssadanandappa\Desktop\temp\node\server.js:8
var { buildSchema }  = require('graphql');
    ^

SyntaxError: Unexpected token {
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:373:25)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Function.Module.runMain (module.js:441:10)
    at startup (node.js:139:18)
    at node.js:974:3
</code>
Sorry tried out a lot of options i could lay my hands on but still the same.
Newbie here, any help would be really appreciated. :)
Answer: I had the same issue in a windows machine.
resolved upgrading from the LTS version to the Current one.
Hope it helps
Comment: Thank you very much Alexandre.. Was able to get it working with your suggestion. sorry for the late reply though. Accepted your answer : )
Answer: That's really strange, check the upper lines if there's any other problem like missing a ';', not closing quotations or missing a 'var' declaration.
Check your node version too, try using the latest release.


Onedrive API read files on given Link

Question: I want to create project with Microsoft Cognitive Services working with Onedrive API.
Scenario is : User will give me an Onedrive link and my API will go files on that folder.
Is it possible?
If so, where can I find more documentation about it?
Answer: You'll want to leverage the shares API using an encoded version of the OneDrive Link.

GET ../v1.0/shares/{sharingTokenOrUrl}

Where sharingTokenOrUrl in your case is the URL encoded in the following manner:

First, use base64 encode the URL.
Convert the base64 encoded result to unpadded base64url format by
removing = characters from the end of the value, replacing / with _
and + with -.)
Append u! to be beginning of the string.

As an example, to encode a URL in C#:
string sharingUrl = "https://onedrive.live.com/redir?resid=1231244193912!12&authKey=1201919!12921!1";
string base64Value = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(sharingUrl));
string encodedUrl = "u!" + base64Value.TrimEnd('=').Replace('/','_').Replace('+','-');

Check out this documentation for a complete description of the shares endpoint.
Comment: Do you know what is the same encoding and base64 value for javascript
Comment: See if the answer to [this answer](http://stackoverflow.com/questions/5641303/base64url-in-java) is what you need

Onedrive API read files on given Link


parse webpage upto n levels using wget

Question: I am trying to extract URLS from a webpage up to user defined n levels using wget. I tried this
 wget -r -l$2 --reject=gif -O out.html www.google.com | sed -n 's/.*href="\([^"]*\).*/\1/p'` "

It is displaying only the first level. it is not parsing any levels
how could i rectify it
Answer: Get rid of the $2 unless you're assigning a variable 2=1 or something like that elsewhere, -l$2 will cause wget to output wget: --level: Invalid number  which will not feed into sed very well.
you can do:
wget -l 2 <address>

or
wget --length=2 <address>

you may also have interest in the no-parent option, which will prevent wget from traversing up the directory (n levels). This is an especialy  useful option when retrieving recursively, since it guarantees that only the files below a certain hierarchy will  be downloaded.
wget -np <address>

parse webpage upto n levels using wget


Trace a breaker to what it powers

Question: I have started on the task of labeling all my breakers but in this process it has left me with one major issue, I have one breaker that doesn't kill anything in the house. During the checks every other outlet, ceiling fixtures, appliances are accounted for, but I still have a single 15 amp breaker that I can't figure out what it controls. Is there any advice on figuring out where this breaker goes to?
Comment: Have you tried leaving this as the ONLY breaker on and seeing what might work?
Comment: Can you confirm that there is indeed a wire connected to the breaker inside the panel? You also didn't specify the location of the panel. If it is exposed in a basement, is it possible to trace where the wire goes? Also make sure that all of your duplex receptacles aren't "split", like when one outlet is on constant while the other is (or perhaps was) controlled by a switch.
Comment: Check doorbell transformer. Often times there is a whole 15A branch circuit just for this.
Comment: @BrownRedHawk I laughed with delight at this comment. It should be an answer!
Answer: Note: This may seem silly, as it's just the opposite of what you've already done, but I promise it is not in jest.
Try turning off ALL breakers except for the mystery breaker. It is completely possible that one or more circuits were erroneously "double fed" by this breaker and another.
Alternatively, you could have something not-so-obvious like an exterior light, garage door opener, doorbell that is powered off this circuit.
Lastly, someone could have "dead ended" an unused circuit by simply capping it off where it terminates, but leave the breaker and wiring for future use.
Comment: So I could just disconnect the wire from that breaker and use the breaker for something else then.
Comment: If you disconnect that breaker and reuse it, Murphy's law says you'll discover what it was connected to at the most inconvenient moment possible. I wouldn't disconnect it without fully tracing it. If you're out of space in the breaker box, consider swapping this or another out for a unit which provides two breakers in the same space.
Comment: I did enjoy your comment, and I thought about outside and I checked all of those, they are all still working and the breaker is currently off, I checked some things like the hard wired garbage disposal and none of these are off.

I did think about a dead ended circuit but that was I guess more of my question how could I find where it ends?
Comment: It's pretty hard to find where it terminates. They do make some "snoopers" to find breakers for mystery outlets, but I believe those require some amount of current. If it's dead ended, I believe they do not work. In practice, most people disconnect the feed side from the panel and terminate it in a labeled junction box, leaving the wiring in place. If you're dead set on finding it, I suggest starting in the attic, then light fixtures, then basement. It's usually more work than it's worth IMO.
Comment: Do you cave a sump pump or something similar?  Could it be powering a service outlet in an unexpected location, like by the panel, or water heater, or attic?  Attic vent fan?
Comment: I wish we could have a betting pool on what it is, or is not hooked up to. @RDrast Good call suggesting sump pump and attic fan. Those things might not normally be powered up, or obvious.

Trace a breaker to what it powers


How to make a visual table comparison?

Question: I have to redesign a comparison between the two tables. The rows with differences should highlight the attribute which is different (see image). My problem is: it grows really fast. I start thinking about presenting a pixel heat map with interactions to "zoom in" in a "details on-demand" fashion. But I am not sure about that because it could be a too drastic difference for users.
Comment: Are the tables populated from a DB as Flex, Grid, or HTML tables? What language is being used -- PHP?
Comment: Hey @Steve, thanks for your time. It is a web application, so I would answer HTML.
Comment: Above the table it says, "1 to 5 of 37 entries" so that indicates a database output. Are you asking for how to code this? Because it is already being shown in your screenshot. If you are not asking for code, what are you asking for? Your screenshot answers the question at the top of the page, so it's hard to answer it. That may be why there are no answers.
Comment: Hi Steve. No, I am not asking about how to code. I am asking about design hints. I have to facilitate this task of "Table comparison" in a row by row fashion. The current design (the one in the picture) scales really bad and it is by nature a 2 lines row/result in a Listview (which is also bad). I hope that now I made my question clearer.

Let me know in case of further doubts and thanks for your time.
Answer: It seems like one of the reasons for having to create this table is to help with cleaning up the dataset. And since you mentioned that the rows grow really fast, that means there must be any number of columns that might be mismatched. If it is usually just the type of mismatch shown on the screen shot, I don't think it would be much of an issue because that's probably exactly what you want to see.
So if we take the case that any number of columns might be mismatched, what you probably need are additional filters that let you narrow down the amount of rows that you are looking at. This could be a simple filter on a single column type, or something more complex with multiple filters based on specific criteria.
This will limit the amount of changes that you have to make to the design.

How to make a visual table comparison?


After using clearTimeout(tick) my program freeze

Question: I have following code:
var tick;

/* START - timer */
startclock();

/* CLOCK - stop timer */
function stopclock() {
    alert('stop timer');
    clearTimeout(tick);
}

/* CLOCK - start timer */
function startclock() {
    var ut = new Date();
    var h, m;
    var time = "        ";
    var hour;

    h = ut.getHours();
    m = ut.getMinutes();

    if (m <= 9) m = "0" + m; if (h <= 9) h = "0" + h;
    time += h + ":" + m;
    /* EXPIRE - check */
    var day = moment(expire).diff(new Date(), 'days');
    if (day > 0) { hour = moment(expire).diff(new Date(), 'hours') - (day * 24); } else { hour = moment(expire).diff(new Date(), 'hours'); };
    switch (day) {
        case 3:
        case 2:
        case 1:
            /* MESSAGE - expiration */
            $(".authentication_problem_container").css("display", "block");
            $(".authentication_problem_block").html("Your Account Expire: " + day + " Day(s) " + hour + " Hour(s)");
            tick = setTimeout(startclock, 1000);
            break;
        case 0:
            /* AUTHORISATION - error */
            $("#account").css("display", "none");
            $(".cut_off").css("display", "block");
            $(".cut_off_text").html("Your STB is blocked.
 Call the provider.");
            window.active = 'authorisation';
            /* CLOCK - stop timer */
            stopclock();
            break;
    }
}

/* REMOTE - control codes */
    $(document).keydown(function(e){
        switch(e.keyCode || e.which){
            case 112:
               alert("RED BUTTON PRESSED!");
               break;
            case 113:
               alert("YELLOW BUTTON PRESSED!");
               break;
            case 114:
               alert("BLUE BUTTON PRESSED!");
               break;
        }
    })

I have problem that when i get message 'stop timer' my program is not responding anymore. So i don't have clue where i did it wrong. I read online tutorial of using timers in javascript but this does not work.
So before timer gets cleared when i press yellow button on remote control i got correct alert 'YELLOW BUTTON PRESSED!' after is clearTimeout(tick) function called then none of my buttons works.
Comment: Can you provide a [mcve] in a snippet or fiddle to let us try your code and debug it?
Comment: Are you sure that the page becomes unresponsive? Isn't it possible that all the actions are inside the `startclock` function and thus stopping to clock will disable the actions?
Comment: `clearInterval(..)` disables the functionality running because of `setInterval` or `setInterval`.
Comment: I updated above code...so my keyup is broken when i call clearInterval()
Answer: The problem is that alert(...) function blocks the rest of code from being executed until you close it. I tested your code and it worked fine for me so it's either the alert call that freezes your code or some external factor, like other piece of code you wrote.
Comment: I added updated complete code example above...so if you could please take a look


How to strip off certain characters from String text Java

Question: I've got a pice of String text as such:
<![CDATA[<SomeTag>SomeText Here</SomeTag>]]>
I'd like to strip off the CDATA tag so I just get this:
<SomeTag>SomeText Here</SomeTag>
How can I accomplish this in Java using anymethod, preferably regular expressions?
Edit:
What if it weren't CDATA it could be any piece of text, I'd like to extract just this:
<SomeTag>SomeText Here</SomeTag>
Answer: how about
source.replaceAll("\\<!\\[CDATA\\[","").replaceAll("\\]\\]\\>", "")

or
source.replaceAll("\\<!\\[CDATA\\[|\\]\\]\\>",""));

or with pattern matching
    Pattern p = Pattern.compile("\\<!\\[CDATA\\[|\\]\\]>");
    String s = "<![CDATA[<explanation>SomeText Here</explanation>]]>";
    Matcher m = p.matcher(s);
    String extracted = "";

    while (m.find()) {
       extracted = m.replaceAll("");
    }

        System.out.println(extracted );

Comment: basically if you have a list of things that you want to replace, just add them to the regex
Comment: What is the wrapping text weren't CDATA what if it were foo or some other arbitary text?
Comment: Actually this doesn't seem to work
Comment: thanks, i made some changes. please review
Comment: Thanks, works perfectly
Comment: sure, glad to help :) all the best !