text:
Q: Detecting if input is a string or an integer Please tell me what is wrong in my approach.
#include <iostream>
#include <string>
using namespace std;

string datatype(string x) {
    for (int k = 0; k < strlen(x.c_str());) {
        for (int i = 0; i < 10; i++) {
            char z = i;
            if (x[k] == z) {
                k++;
            }
            else {
                return "string";
            }
        }
    }
    return "int";
}

int main() {
    string inp;
    cin >> inp;

    cout << datatype(inp);
}

Whatever i enter, it always returns "string".
I have seen the other questions posted here but please tell me what is wrong in my approach.

A: The standard library has the isdigit function that tells you if the char is a digit.
Here you check that each char of your input is a digit, as soon as a character that is not a digit is found string is returned, else int.
For example 1234 returns int, sdf returns string.
string datatype(string str) {
    for (unsigned char c : str) {
        if (!isdigit(c)) {
            return "string";
        }
    }
    return "int";
}

Edit:
This solution also handles leading - and +. It will return int for -10 and +10 but returns string for +1+1 or -10+10.
string datatype(string str) {
    if (str.size() == 1) {
        return isdigit(str[0]) ? "int" : "string";
    }

    bool isInt = true;
    for (int i = 1; i < str.size(); i++) {
        isInt = isInt && isdigit(static_cast<unsigned char>(str[i]));
        if (!isInt) {
            break;
        }
    }

    if (isInt) {
        unsigned char c = str[0];
        isInt = isInt && (c == '-' || c == '+' || isdigit(c));
    }

    return isInt ? "int" : "string";
}

A: First of all Include (cstring) as header since x.c_str is not in iostream and string. Then,
When you are doing char z=i; here you are not storing the character equivalent of i in z but the ascii value of i.
Next, You are returning string at the first mismatch between i and x[k]. You should return string if you cannot find a match with any of the possible 10 digits.
You can have a look at the modified code.
#include <iostream>
#include<cstring>
#include <string>
using namespace std;

string datatype(string x) {

    for (int k = 0; k < strlen(x.c_str());k++) {
         int flag=0;
        for (int i = 0; i < 10; i++) {
           // char z = i;
            if ((x[k]-'0') == i || (k==0 && x[k]=='-')) {
                flag=1;
               break;
            }

        }
          if(flag==0)
          return "string";

    }
    return "int";
}

int main() {
    string inp;
    cin >> inp;
   cout << datatype(inp);
}


text:
Q: GIT - Going back to a previous commit and modify it I have a project where I have the following commit sequence:
* 800cedc (HEAD, origin/master, origin/HEAD, master) Commit 6
* 1d51716 Commit 5
* 5232f4b Commit 4
* 01838a5 Commit 3
* 3aeb34d Commit 2
* 9b75b72 Commit 1

For development reasons, what I need to do is the following:
1. Go to Commit 5.
2. Make some small changes.
3. Publish the changes to production.
4. Add the changes to the the commits.
The problem comes when I see that the file that I have changed, it's also changed in Commit 6.
What can I do to change the file in Commit 5 and merge the changes with commit 6 to keep good track of everything?
Thank you!!

A: As @NilsWerner 's comment says, it's not a good idea to rewrite a published history. But if you really want to,
git reset 1d51716 --hard
# modify the file and
git add path/to/file
git commit --amend

# apply Commit 6 again
git cherry-pick 800cedc

# there might be conflicts and if any,
# resolve the conflicts, and then
git add path/to/file
git cherry-pick --continue

# force push "master"
git push origin -f master

After force-push, do tell other contributors that you have rewritten master and they should force-update their local master and apply their unpushed commits onto their new local master, which is quite a troublesome task.

A: You can do below steps.

*

*Create new branch out of commit5.
git branch branchname <sha1-of-commit5>
git checkout branchname

*You cannot do cherrypick for individual file. You can only do cherrypick at commit level.
do a local copy of the specific file of Commit5(say file_a), which you want to merge from commit6. After doing that, checkout the specific file from commit6.
git checkout <sha1-ofcommit6> path/to/file_a

*Now,manually do the merge of commit5 file (local copy) with commit6 file (in git branch)

*After doing the changes, stage them and push to remote.
git add .
git commit -m "manual merge for file_a"
git push origin branchname```

A: Try:
git revert 1d51716
git revert --no-commit HEAD

then, make your change.
Not sure, please be careful to verify.
BTW: I think the best way is just make a new commit :-)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Editable Polygons in Mapbox I'm using the mapbox-gl-js library trying to implement a function where the user can add polygons to a mapbox map and edit them if desired.  I've been able to add the polygon to the map by adding a layer, but I don't know how to allow users to edit them.  Is there a simple way to add polygons to mapbox and change whether or not they are editable?

A: after load map you can add Feature(point,line,polygon)
example:

  var map = new mapboxgl.Map({
        container: 'map',
        style: 'mapbox://styles/mapbox/streets-v9'
    });

    var draw = new MapboxDraw();

map.addControl(draw);

map.on('load', function () {

var feature = {
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [
              49.62524414062499,
              31.653381399664
            ],
            [
              55.458984375,
              31.653381399664
            ],
            [
              55.458984375,
              35.28150065789119
            ],
            [
              49.62524414062499,
              35.28150065789119
            ],
            [
              49.62524414062499,
              31.653381399664
            ]
          ]
        ]
      }
    }
  ]
};
var featureIds = draw.add(feature);

 });

A: You're looking for the mapbox-gl-draw plugin. You can see a demo here.


text:
Q: How can I achieve a reliable UDP protocol? I know how to send and receive both UDP and TCP packets, how can I achieve some way of sending reliable UDP packets??
I'm just asking for a logic as I have no idea how this works.
Thanks in advance.

A: This is some old code that i used as a previous company
there are a lot of other methods behind this too, too many to really share on here but you want to be using Acknowldgemet and Not Acknowledged messages to show that the comms have been sent and received.
public void InitialiseVenemaComms()
{
    string initMessage = null;
    DebugInfo(1, "*** InitialiseVenemaComms");
    initMessage = "002" + StationPrms.StationId + "ACK";

try
{
    System.Net.Sockets.UdpClient udpClient = new System.Net.Sockets.UdpClient(Convert.ToInt32(StationPrms.Venema.LocalPort));
    byte[] messageBytes = System.Text.Encoding.ASCII.GetBytes(initMessage);
    udpClient.Connect(StationPrms.Venema.DNS, Convert.ToInt32(StationPrms.Venema.RemotePort));
    DebugInfo(1, string.Format("*** Sending init message '{0}' from port '{1}' to ip '{2}' on port '{3}'", initMessage, StationPrms.Venema.LocalPort, StationPrms.Venema.DNS, StationPrms.Venema.RemotePort));

    udpClient.Send(messageBytes, messageBytes.Length);
    udpClient.Close();
    DebugInfo(1, "*** Init Message Sent");
}
catch (Exception ex)
{
    DebugInfo(2, "Error: " + ex.Message);
    CssError("Error initalising Venema comms: " + ex.Message);
}

}
but youre better off sending over TCPIP as per my comments.


text:
Q: Does StringBuilder.toString retain the built string? I'm creating a StringBuilder to collect strings that I periodically flush to a server.  If the flush fails, I want to keep the strings to try again next time, although in the mean time I might get additional strings to send which must be added to the StringBuilder.
What I want to know is what the most efficient way to do this would be, as this is being done in an Android app where battery usage and thus CPU usage is a big concern.  Does calling StringBuilder's toString() function store the resulting string it returns internally so that a subsequent call doesn't have to do the work of copying all the original strings over?  Or if the call fails, should I create a new StringBuilder initialized with the return value from toString()?

A: Here is the OpenJDK source code for StringBuilder:
public String toString() {
    // Create a copy, don't share the array
    return new String(value, 0, count);
}

The source for the String constructor with those parameters is:
public String(char value[], int offset, int count) {
    if (offset < 0) {
        throw new StringIndexOutOfBoundsException(offset);
    }
    if (count < 0) {
        throw new StringIndexOutOfBoundsException(count);
    }
    // Note: offset or count might be near -1>>>1.
    if (offset > value.length - count) {
        throw new StringIndexOutOfBoundsException(offset + count);
    }
    this.offset = 0;
    this.count = count;
    this.value = Arrays.copyOfRange(value, offset, offset+count);
}

So yes, it does create a new String everytime, and yes, it makes a copy of the char[] everytime.
It's important to note that this is one implementation of toString, and another implementation may obviously be different.

A: It would be an implementation detail.  Since java strings are immutable a correct impl can choose to share or create new strings from StringBuilder.toString() even if it's not needed.
As everyone says, you can test to see if this is indeed a real performance issue for you.  If it is one (clunky) workaround is to wrap StringBuilder and cache the resulting string.  You can use a dirty flag to indicate the content was modified.

A: StringBuilder.toString API says that a new String object is allocated and initialized to contain the character sequence currently represented by this object.


text:
Q: How does Marshal.FreeHGlobal is freeing allocated memory? I am learning different ways to allocate and free memory in C#. Here is the sample code that is working.
   class clsA
   {
       private IntPtr _buffer;
       public clsA()
       {
            _buffer = Marshal.AllocHGlobal(1024);
            //_buffer = Marshal.AllocCoTaskMem(1024);
       }
       public void free()
       {
           Marshal.FreeHGlobal(_buffer);
          //Marshal.FreeCoTaskMem(_buffer);
       }
    }

   class Program
   {

      static void Main(string[] args)
      {

       unsafe
       {
            List<clsA> l = new List<clsA>();
            for(int i = 0; i < 8192; i++)
            {
                l.Add(new clsA());

            }
            Console.WriteLine("Added");
            foreach (var a in l)
            {
                a.free();
            }

            Console.ReadLine();
        }

       }
   }

Memory allocation is working as expected but after de-allocation 1-2 mb seems to increase after both process are done. Initially the app had 4.6 Mb. after allocation it reached to 13.3 Mb which was expected. But after freeing up that space overall app was using 7.1 Mb. What is exactly happening here? And how can I free up that remaining space.


text:
Q: Multiple overlays vs continous redrawing im MKMapView I am drawing users location path on MKMapView live and I am wondering what's better approach.
Currently I am gathering all location data in location manager and I am redrawing whole overlay every second.
- (void)showLines {
    NSArray *locations = [[SHLocationManager sharedInstance] locations];
    CLLocationCoordinate2D *pointsCoordinate = (CLLocationCoordinate2D *)malloc(sizeof(CLLocationCoordinate2D) * locations.count);
    [locations enumerateObjectsUsingBlock:^(CLLocation *location, NSUInteger idx, BOOL *stop) {
        pointsCoordinate[idx] = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude);
    }];

    MKPolyline *polyline = [MKPolyline polylineWithCoordinates:pointsCoordinate count:locations.count];
    free(pointsCoordinate);

    [self.mapView removeOverlays:self.mapView.overlays];
    [self.mapView addOverlay:polyline];
}

- (MKPolylineRenderer *)mapView:(MKMapView *)mapView viewForOverlay:(id)overlay{
    MKPolylineRenderer *polylineView = [[MKPolylineRenderer alloc] initWithPolyline:overlay];
    polylineView.strokeColor =  [UIColor colorWithRed:0.17 green:0.57 blue:0.85 alpha:1];
    polylineView.lineWidth = 8.0;
    polylineView.alpha = 1;

    return polylineView;
}

Is it better to draw a line for every pair of point's I get from location manager?
It would create number of overlays - don't know how it would affect performance.
What's better in your opinion?


text:
Q: problem with slide and ajax i have this structure in my html

            <form method="post" id="customForm" action="">
                //my content - name, email, mypassword, pass2
            </form> //i already tried delete this

            <form method="post" id="customForm1" action="">  //and this, to have only one form obviously this didn't work, because the div of slide1 is already closed.
                //my content - other stuff
            </form>

and i have this JS
 $(document).ready(function() {
        $("#customForm").submit(function() {
            $.ajax({
                url: "validation1.php",
                type: "post",
                dataType: "json",
                data: {
                    name: $('#name').val(),
                    email: $('#email').val(),
                    myPassword: $('#myPassword').val(),
                    pass2: $('#pass2').val()
                },
                success: function(data) {
//stuff
}

the problem is. I want to group the data of tho slides and send to validation1.php, but for that i must have a only form.
If the problem is not clear please tell me.
thanks

A: If I understand correctly you are saying that you need to send the 2 slides in one post but in your html the data lives in 2 forms elements.
You can always build a new form with the data you want in it and just submit that, but also review the use of forms on your page anyway.
var href = '.... where ever you are sending the data .....';
var form = $('<form method="post" action="' + href + '"></form>');

var d1=$('.slide1 some subdata selector');
var d2=$('.slide2 some subdata selector')

$('<input type="hidden" name="data1">').val(d1).appendTo(form);
$('<input type="hidden" name="data2">').val(d2).appendTo(form);
$('body').append(form);
form.submit();
form.detach();


text:
Q: Редиректы нестандартные для Wordpress Добрый вечер.
Возник следующий вопрос:
на сайте сейчас сделали свои доработки и есть контент, который выводится с помощью параметров такого плана:
site.com/?country=france

или
site.com/?country=france&city=paris

Я хочу чтобы в первом варианте по ссылке https://site.com/france.html показывалась страница site.com/?country=france, но адрес в строке браузера оставался https://site.com/france.html
во втором случае, чтобы по ссылке
https://site.com/france/paris.html

открывалась страница site.com/?country=france&city=paris, но адрес показывался
https://site.com/france/paris.html

Подскажите, можно ли так сделать? Если да, то каким образом это реализовать?
Спасибо.


text:
Q: Safari: how to open a URL while in search mode? In Chrome you can open a search-highlighted URL with CTRL + ENTER (and thus obviate the need for using a mouse). How do you do that in Safari (6.0.1)?

A: I don't know any way to do that out of the box, but there's some extensions like Type-To-Navigate that allow selecting links by typing.

Keep your hands on the keyboard while browsing the web. Type any text that occurs inside a link, and hit return to follow it. ⌘G jumps to the next link containing the text, and ⌘⇧G jumps to the previous. Hit ESC to cancel or exit a focused field.


text:
Q: Contacts not loaded in UITableView In my iOS application I have a ViewController which displays a UITableView. Everything (delegate, datasource...) has been set correctly. I want to do a common thing: populate the TableView with the contacts in the phone.
However for some reason the TableView is always empty, while I successfully get the contacts in viewDidLoad. I noticed that the method tableView:numberOfRowsInSection: is called before I get my contact list but I don't know what's the issue. Here is my Controller.m:
@interface Controller () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) NSMutableArray *contacts;
@property(nonatomic, strong) IBOutlet UITableView *contactsTable;

@end

@implementation Controller

- (void)viewDidLoad {
[super viewDidLoad];
self.contacts = [[NSMutableArray alloc] init];
ABAuthorizationStatus status = ABAddressBookGetAuthorizationStatus();

if (status == kABAuthorizationStatusDenied || status == kABAuthorizationStatusRestricted) {
    // if you got here, user had previously denied/revoked permission for your
    // app to access the contacts, and all you can do is handle this gracefully,
    // perhaps telling the user that they have to go to settings to grant access
    // to contacts

    [[[UIAlertView alloc] initWithTitle:nil message:@"This app requires access to your contacts to function properly. Please visit to the \"Privacy\" section in the iPhone Settings app." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
    return;
}

CFErrorRef error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);

if (!addressBook) {
    NSLog(@"ABAddressBookCreateWithOptions error: %@", CFBridgingRelease(error));
    return;
}

ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
    if (error) {
        NSLog(@"ABAddressBookRequestAccessWithCompletion error: %@", CFBridgingRelease(error));
    }

    if (granted) {
        // if they gave you permission, then just carry on

        [self listPeopleInAddressBook:addressBook];
    } else {
        // however, if they didn't give you permission, handle it gracefully, for example...

        dispatch_async(dispatch_get_main_queue(), ^{
            // BTW, this is not on the main thread, so dispatch UI updates back to the main queue

            [[[UIAlertView alloc] initWithTitle:nil message:@"This app requires access to your contacts to function properly. Please visit to the \"Privacy\" section in the iPhone Settings app." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
        });
    }

    CFRelease(addressBook);
});
}

- (void)listPeopleInAddressBook:(ABAddressBookRef)addressBook
{
NSArray *allPeople = CFBridgingRelease(ABAddressBookCopyArrayOfAllPeople(addressBook));
NSInteger numberOfPeople = [allPeople count];
for (NSInteger i = 0; i < numberOfPeople; i++) {
    ABRecordRef person = (__bridge ABRecordRef)allPeople[i];

    NSString *firstName = CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty));
    NSString *lastName  = CFBridgingRelease(ABRecordCopyValue(person, kABPersonLastNameProperty));
    NSString *fullname = [NSString stringWithFormat:@"%@ %@", firstName, lastName];
    ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);

    CFIndex numberOfPhoneNumbers = ABMultiValueGetCount(phoneNumbers);
    for (CFIndex i = 0; i < numberOfPhoneNumbers; i++) {
        NSString *phoneNumber = CFBridgingRelease(ABMultiValueCopyValueAtIndex(phoneNumbers, i));
        NSLog(@"  phone:%@", phoneNumber);
        GIContact *contact = [[GIContact alloc] initWithFullName:fullname telephone:phoneNumber];
        [self.contacts addObject:contact];
    }

    CFRelease(phoneNumbers);
}
}

//Called before I got the contacts
- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section
{
return [self.contacts count]; //This works when I replace it with a number like 2
}
- (UITableViewCell *)tableView:(UITableView *)tableView
     cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Create an instance of UITableViewCell, with default appearance
UITableViewCell *cell =
[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                       reuseIdentifier:@"ContactTableCell"];
// Set the text on the cell with the description of the item
// that is at the nth index of items, where n = row this cell
// will appear in on the tableview
   GIContact *contact = self.contacts[indexPath.row];
   cell.textLabel.text = contact.fullname;
   return cell;
}

@end

Contact is a simple model class with two NSString (fullname and telephone)

A: After a successful connection and retrieving the contact list, refresh the table view. numberOfRowsInSection is called because the view is immediately trying to display the data, which is not there yet.
dispatch_async(dispatch_get_main_queue(), ^{
    [self.tableView reloadData];
});

A: You get contact after tableView reloadData method call.
- (void)listPeopleInAddressBook:(ABAddressBookRef)addressBook
{
NSArray *allPeople = CFBridgingRelease(ABAddressBookCopyArrayOfAllPeople(addressBook));
NSInteger numberOfPeople = [allPeople count];
for (NSInteger i = 0; i < numberOfPeople; i++) {
    ABRecordRef person = (__bridge ABRecordRef)allPeople[i];

    NSString *firstName = CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty));
    NSString *lastName  = CFBridgingRelease(ABRecordCopyValue(person, kABPersonLastNameProperty));
    NSString *fullname = [NSString stringWithFormat:@"%@ %@", firstName, lastName];
    ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);

    CFIndex numberOfPhoneNumbers = ABMultiValueGetCount(phoneNumbers);
    for (CFIndex i = 0; i < numberOfPhoneNumbers; i++) {
        NSString *phoneNumber = CFBridgingRelease(ABMultiValueCopyValueAtIndex(phoneNumbers, i));
        NSLog(@"  phone:%@", phoneNumber);
        GIContact *contact = [[GIContact alloc] initWithFullName:fullname telephone:phoneNumber];
        [self.contacts addObject:contact];
    }

    CFRelease(phoneNumbers);
}
[self.tableView reloadData];// refresh table Data
}

A: The method ABAddressBookRequestAccessWithCompletion does its work off the main thread. A hint for that, is the trailing Closure which is invoked as callback, as soon as the method finished doing what it does.
So when (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection: (NSInteger)section is called, its still working off the main thread or the data hasn't 'reached' the main thread yet.
If you want to populate the data as soon as you've finished fetching the address book request you should reload the UITableView on the main thread:
- (void)listPeopleInAddressBook:(ABAddressBookRef)addressBook
{
NSArray *allPeople = CFBridgingRelease(ABAddressBookCopyArrayOfAllPeople(addressBook));
NSInteger numberOfPeople = [allPeople count];
for (NSInteger i = 0; i < numberOfPeople; i++) {
ABRecordRef person = (__bridge ABRecordRef)allPeople[i];

NSString *firstName = CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty));
NSString *lastName  = CFBridgingRelease(ABRecordCopyValue(person, kABPersonLastNameProperty));
NSString *fullname = [NSString stringWithFormat:@"%@ %@", firstName, lastName];
ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);

CFIndex numberOfPhoneNumbers = ABMultiValueGetCount(phoneNumbers);
for (CFIndex i = 0; i < numberOfPhoneNumbers; i++) {
    NSString *phoneNumber = CFBridgingRelease(ABMultiValueCopyValueAtIndex(phoneNumbers, i));
    NSLog(@"  phone:%@", phoneNumber);
    GIContact *contact = [[GIContact alloc] initWithFullName:fullname telephone:phoneNumber];
    [self.contacts addObject:contact];
}

CFRelease(phoneNumbers);
}
// reload the tableview on the main thread here
dispatch_async(dispatch_get_main_queue(), ^{
   [self.tableView reloadData];
});
}


text:
Q: Close Intermediate Files After Loop Pyspark I wrote a pyspark script to loop through tables in a hive database and do something with them (can't say exactly what per company policy), for example:
hc = HiveContext(sc)
for table in tables:
    df = hc.sql("select * from {}".format(table))
    df.do_something()
    df.unpersist()

It works fine until I get a few tables in and then I get an error:
ERROR DiskBlockObjectWriter:...
java.io.FileNotFoundException ... (Too many open files)

This is because of all the intermediate files spark creates before shuffle.
I thought I could avoid this by unpersisting the data frame (df.unpersist()) immediately after using it and going into the next loop, but that doesn't seem to help.
Is there a way I can close all open files after use and before the next loop? Once I finish each loop, I have no more use for that df. I am certain there is no issue with the specific table that it fails on because I can read that specific table into a DF just fine as long as I haven't opened too many other ones previously.


text:
Q: REST and HTTP API Client for java like RestSharp(http://restsharp.org/) I have used restsharp for some of my .net projects. and I found it pretty useful for getting Json Data from web-service and converting them to .net objects. I need a similar framework for java. I want to use it for reading the same Json web-service  for my android apps.

A: You can try reasteasy cleint http://www.jboss.org/resteasy/.


text:
Q: How can I get random obstacles distance? I´m new to programming but I managed to create a game where I jump over obstacles in Xcode. The problem is that the obstacles have the same distance between each other. Can anyone help me with coding my game so that the obstacles have a random distance between each other every time?
Coding for my obstacles:
SKSpriteNode *obstacle = [SKSpriteNode spriteNodeWithColor:[self getRandomColor] size:CGSizeMake(40, 50)];
obstacle.name = @"obstacle";
obstacle.position = CGPointMake(self.currentObstacleX, ground.position.y + ground.frame.size.height/2 + obstacle.frame.size.height/2);
obstacle.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:obstacle.size];
obstacle.physicsBody.categoryBitMask = obstacleCategory;
obstacle.physicsBody.dynamic = NO;
[self.world addChild:obstacle];

self.currentObstacleX += 250;


text:
Q: SMS and PHP... and Google Voice? I've been searching for a few hours on the best way to add sms notifications and reception to my PHP website. It seems that it's easy to send texts (to an email forward to a phone), but hard to receive them without an SMS gateway. Clickatell was recommended a lot.
But: I stumbled across a few article recommending Google Voice as a channel to send and receive SMS. (Here's one post: http://sudocode.net/article/190/receiving-incoming-smstext-messages-from-google-voice-in-php/)
Is there any reason I shouldn't/can't use a Google Voice number (and PHP) to handle my sms outbound and inbound messages?

A: I would check the Google Voice terms of service. If this is a commercial venture, I believe that's prohibited. Also since there is no official API, things could change at any time and break your app.
If you need reliable incoming or outgoing SMS there is no substitute for a gateway. I would recommend one, but I am not an impartial observer (see profile).

A: There is no official PHP API for Google Voice, however I used GVmax along with this PHP-SDK to create a website called Memebro.


text:
Q: Assembly x86 - Menu's colors are gone when transferring a page so this is a part of my code:
start:
    mov ax,@data
    mov ds,ax

    ;Set graphics mode 320x200 & 256 colors
     mov ax,13h
     int 10h

     mov al,00h
     mov ah,0
     int 10h
     mov ah,09h
     mov bl, 0c3h ; 3 = light blue , c = lightning (for unknown reason) & red line
     mov cx, 40   ; numbers of characters to color
     int 10h
     mov dx, offset menu
     int 21h
    ;set cursor location(dh,dl) (I'm hiding the cursor)
     mov dl, 16  ; column.
     mov dh, 30  ; row.
     mov ah, 02h
     int 10h
     call Beep
    jmp start

I added the jmp start at the end just so you guys realise that even when I jump to the start even without transferring to another page the colors are still gone and the cursor position is not set to the position I told him, yet the menu is showing, what am I doing wrong?
Note: The colors and cursor position are working before I jump to the start back again.

A: Firstly remove the jmp start and replace it by mov ah,0 and int 16h. This will give you a chance to actually see what's on screen.
mov ax,13h
int 10h

mov al,00h
mov ah,0
int 10h

In this block of code you set the screen 2 times! The 2nd and final time it's set to a 16-color text screen of 40 columns and 25 rows.

mov bl, 0c3h ; 3 = light blue , c = lightning (for unknown reason) & red line

You're using the BIOS 'write character and attribute' function with too few parameters. You should also define:
mov al, " "  ;Space character
mov bh, 0    ;Display page 0
mov bl, 0C3h ;This chooses a cyan foreground on a red background


text:
Q: JKS protection Are JKS (Java Key Store) files encrypted? Do they provide full protection for encryption keys, or do I need to rely solely on access control?
Is there a way to ensure that the keys are protected?
I'm interested in the gritty details, including algorithm, key management, etc. Is any of this configurable?

A: To be more precise:

*

*PrivateKeys and SecretKeys within a
JKS file are encrypted with their own password.

*Integrity of trusted certificates is protected with a MAC using the key store password.

*The file as a whole is not
encrypted, and an attacker can list
its entries without the key store
password.

A: They are encrypted.
The algorithm is provider dependent. The provider will return the key/certificate based on a password. If you need strong security, find a keystore provider that uses a strong encryption.


text:
Q: Memory crash with uploading image to Firebase Storage Swift I'll make this quick. About 10% of the time a user uploads their profile photo, the app crashes due to a memory leak. I have tried a load of different things to try and prevent this but for some reason it happens a fraction of the time. Please I have no idea why certain users crash when they upload a photo. (I assume it happens in didFinishPickingMediaWithInfo function).
class CustomImagePickerController: UIImagePickerController  {
    var imageBttn: UIButton?
}

@objc private func handleSelectPhoto() {
        let alert = UIAlertController(title: "Access your photos", message: "Can Crusht open your photos so you can select a profile picture?", preferredStyle: .alert)

        let action = UIAlertAction(title: "Yes", style: .default){(UIAlertAction) in
            let imagePicker = CustomImagePickerController()
            imagePicker.delegate = self
            imagePicker.imageBttn = self.selectPhotoButton
           self.present(imagePicker, animated: true)
        }

        let cancel = UIAlertAction(title: "No", style: .cancel, handler: nil)
        alert.addAction(action)
        alert.addAction(cancel)
        self.present(alert, animated: true, completion: nil)
        return
    }

extension EnterPhotoController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    @objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        weak var selectedImage = info[.originalImage] as? UIImage
        let imageButton = (picker as? CustomImagePickerController)?.imageBttn
        imageButton?.setImage(selectedImage?.withRenderingMode(.alwaysOriginal), for: .normal)
        self.imageFull = true

        dismiss(animated: true)

        self.errorLabel.text = "Registering, hang tight..."
        self.errorLabel.isHidden = false
        self.selectPhotoButton.isEnabled = false

        let filename = UUID().uuidString
        let ref = Storage.storage().reference(withPath: "/images/\(filename)")
        guard let imageData = selectedImage?.jpegData(compressionQuality: 0.75) else { return }

        ref.putData(imageData, metadata: nil) { (nil, err) in
            guard err == nil else { return }
            ref.downloadURL { (url, err) in
                guard err == nil else { return }
                let imageUrl = url?.absoluteString ?? ""
                if imageUrl == "" {
                    print("fuck me man")
                }

                self.saveInfoToFirestore(imageUrl: imageUrl)
            }
        }
    }
}

   private func saveInfoToFirestore(imageUrl: String){
        let uid = Auth.auth().currentUser?.uid ?? ""
        let docData: [String: Any] = ["ImageUrl1": imageUrl]
        Firestore.firestore().collection("users").document(uid).setData(docData, merge: true) { (err) in
            guard err == nil else { return }
            let customtabController = CustomTabBarController()
            customtabController.modalPresentationStyle = .fullScreen
            self.present(customtabController, animated: true)

      }
 }

A: You need to resize your image to a lower size. We all know that photos captured by ios devices  is quite large and sending it as data to a server is also a big workload. You can resize the image to your liking without losing most of its quality.
Check this out for resizing.
https://stackoverflow.com/a/31314494/11138557
Hope this helps: Thanks :)

A: updated code for anyone who cares!
   @objc private func handleSelectPhoto() {
        let alert = UIAlertController(title: "Access your photos", message: "Can Crusht open your photos so you can select a profile picture?", preferredStyle: .alert)

        let action = UIAlertAction(title: "Yes", style: .default){(UIAlertAction) in
            let imagePicker = CustomImagePickerController()
            imagePicker.delegate = self
            imagePicker.imageBttn = self.selectPhotoButton
           self.present(imagePicker, animated: true)
        }

        let cancel = UIAlertAction(title: "No", style: .cancel, handler: nil)
        alert.addAction(action)
        alert.addAction(cancel)
        self.present(alert, animated: true, completion: nil)
        return
    }

    private func saveInfoToFirestore(imageUrl: String){
        let uid = Auth.auth().currentUser?.uid ?? ""
        let docData: [String: Any] = ["ImageUrl1": imageUrl]
        Firestore.firestore().collection("users").document(uid).setData(docData, merge: true) { (err) in
            guard err == nil else { return }
            let customtabController = CustomTabBarController()
            customtabController.modalPresentationStyle = .fullScreen
            self.present(customtabController, animated: true)

        }
    }
extension EnterPhotoController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    @objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        weak var selectedImage = info[.originalImage] as? UIImage
        let selectedImage2 = selectedImage?.resizeImage(targetSize: CGSize(width: 540, height: 500))
        let imageButton = (picker as? CustomImagePickerController)?.imageBttn
        imageButton?.setImage(selectedImage2?.withRenderingMode(.alwaysOriginal), for: .normal)
        self.imageFull = true

        dismiss(animated: true)

        self.errorLabel.text = "Registering, hang tight..."
        self.errorLabel.isHidden = false
        self.selectPhotoButton.isEnabled = false

        let filename = UUID().uuidString
        let ref = Storage.storage().reference(withPath: "/images/\(filename)")
        guard let imageData = selectedImage2?.jpegData(compressionQuality: 0.9) else { return }

        ref.putData(imageData, metadata: nil) { (nil, err) in
            guard err == nil else { return }
            ref.downloadURL { (url, err) in
                guard err == nil else { return }
                let imageUrl = url?.absoluteString ?? ""
                if imageUrl == "" {
                    print("fuck me man")
                }

                self.saveInfoToFirestore(imageUrl: imageUrl)
            }
        }
    }
}

extension UIImage {
  func resizeImage(targetSize: CGSize) -> UIImage {
    //print("hi")
    let size = self.size
    let widthRatio  = targetSize.width  / size.width
    let heightRatio = targetSize.height / size.height
    let newSize = widthRatio > heightRatio ?  CGSize(width: size.width * heightRatio, height: size.height * heightRatio) : CGSize(width: size.width * widthRatio,  height: size.height * widthRatio)
    let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)

    UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
    self.draw(in: rect)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage!
  }
}


text:
Q: Cannot find FREAK detector in OpenCV I am developing some code in OpenCV 2.4 and I want to test the FREAK detector but I get compilation errors. I am including the feature2d.h, what can I do to fix this?

A: FREAK is included in the OpenCV version 2.4.2, so you cannot use it in your current version as it is not implemented. Download and install OpenCV2.4.2.


text:
Q: Failover sharding mongodb. Autoreconnect doesnt work I have configured Sharding for MongoDB. My setup looks like this:

*

*3 ConfigServers

*2 Shard Servers (Shard1 and Shard2) each of them with 3 ReplicaSet nodes

*1 mongos instance

My current collection has as primary sharding Shard 1. All my data stored right now on Shard 1. Am I right that the data will be stored on Shard 2 as soon as my Shard 1 will get full ?
I'm testing now a failover scenario when my Shard 1 Server is down then the data should go to Shard 2 but it doesnt happen ? It should automatically auto reconnect to Shard 1 right ?

A:
My current collection has as primary sharding Shard 1. All my data
stored right now on Shard 1. Am I right that the data will be stored
on Shard 2 as soon as my Shard 1 will get full ?

Sharding is about distributing data in a collection among shards. Sharding is enabled at database level, but actual data distribution on shards is at collection level. So, a sharded database can have sharded and unsharded collections. All the unsharded collections reside on primary shard. The sharded collection data is distributed on multiple shards (based on shard key). All queries to a sharded database (irrespective of sharded or unsharded collections) go thru the mongos router.
For a sharded collection, it is possible that the initial data is all stored on one shard. Later on as the data grows it is distributed to the next shard. See data partitioning with chunks.

I'm testing now a failover scenario when my Shard 1 Server is down
then the data should go to Shard 2 but it doesnt happen ? It should
automatically auto reconnect to Shard 1 right ?

Faliover is a process associated with replication, not sharding. A replica-set has multiple nodes (as specified in your shard configuration, each shard is a replica-set). When a primary node in the replica-set fails (or goes down) the remaining two secondaries hold an election and elect a new primary. The client applications will automatically connect to the new primary. When the previous primary node comes up again, it will become a seconday.
See replication failover.


text:
Q: Bootstrap 3.3.5 glyphicon issues I have this code:

    The Old Steam House, Unit 10, Goblands Farm, Cemetery Lane, Hadlow, Kent, TN11 0LT

Which outputs like this, which is fine.

However, on a mobile it looks like this

How/what is the best way to indent the text all the way down like this

I apologise if this isn't a good question to ask, i've never used Bootstrap before.

A: Negative left margin on the glyphicon should work.

@import url("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css");

.multiline-margin {
    margin: 0 0 0 20px;
}

.multiline-margin > .glyphicon {
    margin: 0 0 0 -20px;
}

  The Old Steam House, Unit 10, Goblands Farm, Cemetery Lane, Hadlow, Kent, TN11 0LT

A: Like i said in the comment, bootstrap doesn't solve such cases.
What you can do is use padding-left: [value] where value is the font-size + the spacing you want.
HTML ( changed "p" since "div" cannot be a child of "p" ):

The Old Steam House, Unit 10, Goblands Farm, Cemetery Lane, Hadlow, Kent, TN11 0LT

CSS:
/* this selector is just for example */
div {
    font-size: 18px;
}

.padded-box {
    padding-left: 23px /* 18px + 5px for spacing */
}

Here's a fiddle: http://jsfiddle.net/dkcw54wy/


text:
Q: Prove that lim inf$_{n} na_{n} > 1 \Rightarrow \sum_{k = 1}^{\infty} a_{k}$ diverges Prove that lim inf$_{n} na_{n} > 1 \Rightarrow \sum_{k = 1}^{\infty} a_{k}$ diverges
The solution proof goes like:
lim inf$_{n} na_{n} > 1 \Rightarrow$ there exists an $N \in \mathbb{N}$ such that for every $n > N$, $na_{n} = a_{n}/(\frac{1}{n})> \frac{1}{2}$
At this point, my question is, where did the $\frac{1}{2}$ come from? Then the proof goes on to say that
$\Rightarrow a_{n} > \frac{1}{2} \cdot \frac{1}{n}$ and by comparison test, since the infinite sum of $\frac{1}{n}$ diverges, then the infinite sum of $a_{k}$ also diverges.
This part makes perfect sense. But I really don't understand where the $\frac{1}{2}$ comes from.

A: If $\liminf c_n = C$, then for any $B<C$, there exists an $N$ such that $c_n>B$ for all $n>N$. If this weren't the case, you could show that $\liminf c_n\leq B$ which would contradict $\liminf c_n = C > B$.
They just used this fact with $c_n = na_n$, $C=1$ and $B=\frac{1}{2}$.


text:
Q: i18n_patterns: How come some user are accessing /en-us/ where what I have is /en/ I am using i18n_patterns for my URL and yesterday when I launched the live site I noticed through Google Analytics many people are accessing http://www.example.com/**en-us**/ instead of http://www.example.com/**en**/. I do not have http://www.example.com/**en-us**/ link anywhere on my site.
Personally, when I try to access the site through http://www.example.com/ I am redirected to http://www.example.com/**en**/ which is the wanted behaviour. Also when I try http://www.example.com/**en-us**/ I get a not found page, which is also what I want, since it's not good for SEO to have multiple URls for the same page.
Now the weird is I am actually seeing visitors at /en-us/ because I do not have Google Analytics on the not found page yet!
This is part of my settings:
LANGUAGE_CODE = 'en-us'

gettext = lambda s: s
LANGUAGES = (
    ('en', gettext('English')),
    ('fr', gettext('French')),
    ('es', gettext('Spanish')),

Any idea what is causing that? Are these people getting a not found page, and how can I eliminate the issue? It's really hard to debug it when it is not happening to me!

A: LANGUAGE_CODE = 'en-us'

This sets the default, if no acceptable language is found.  See the documentation for details.
If you don't have an en-us translation, then don't set that to be your default - set it to en or similar.

It's really hard to debug it when it is not happening to me!

You can probably recreate the bug by setting your language preference for your browser to American English, or to a language that you haven't localised for.


text:
Q: Using JSON dataArray in Dashcode, doesn't display binded information I'm trying to write a simple dashboard widget (possibly an additional webapp) that displays the information from a JSON feed. I've added the URL to a datasource, and it loads the info properly. It doesn't have any items.
This is the format:
{"username": "emb1995", "unconfirmed_reward": "0.02107742", "send_threshold": "1.00000000", "confirmed_reward": "0.11128238", "wallet": "key_here_but_removed", "estimated_reward": "0.00000000"}
As a test, I added a text element. I went to the datasource section and binded the string to the element that I wanted:

Here is what my layout looks like:

But when I run the widget, the information is never displayed:

Any ideas on how to make this work?

A: This is really trivial but have you allowed access to the network. In the menu on the left you will see "Widget Attributes", click that then second box down "Network / Disk Access" one or both need to be checked to allow the widget access to either/both the the network or local file access.
If you have already done this and it's failing let me know.


text:
Q: setColorFilter to imageView I implemented onTouchListener for an imageView that puts a opacity filter on it when touched
ima.setOnTouchListener(new TextView.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (MotionEvent.ACTION_DOWN == event.getAction()) {
                    ima.setColorFilter(0x80FFFFFF, PorterDuff.Mode.MULTIPLY);
                } else if (MotionEvent.ACTION_UP == event.getAction()) {
                    ima.clearColorFilter();
                    v.performClick();
                } else if (MotionEvent.ACTION_SCROLL == event.getAction()) {
                    ima.clearColorFilter();
                }
                else if (MotionEvent.ACTION_CANCEL == event.getAction()) {
                    ima.clearColorFilter();
                }
                return true;
            }
        });

When I scroll on the layout an press the image by mistake it put the filter for a sudden.
I need to put this filter only when i really want to press this image. Is there any efficient way to do this?


text:
Q: Locking techniques Delphi RAD libraries implement many thread friendly objects in a way which forces one to declare another object for storing the reference returned by that object's locking method. The object thus essentially encapsulates the prime object which is returned on locking. For example;
List := ThreadList.Unlocklist;
// do something with List
ThreadList.LockList;

Why is this approach taken? Why is inheriting from the prime object, adding the locking object, overriding constructors and destructors, discouraged? For example the following implementation adds a TMREWSync to a list;
IMREWS = interface

  ['{5B6DE5FA-847B-42D5-8BF4-9EB20A452C54}']

  procedure BeginRead;
  function  BeginWrite: Boolean;
  procedure EndRead;
  procedure EndWrite;

end;

TThreadList = class ( TList, IMREWS )
private

  FLock : TMREWSync;

public

  constructor Create;
  destructor  Destroy; override;

  property Lock : TMREWSync read FLock implements IMREWS;

end;

constructor TThreadList.Create;
begin
  FLock := TMREWSync.Create;
  inherited;
end;

destructor TThreadList.Destroy;
begin
  inherited;
  FLock.Free;
end;

// Usage:

ThreadList.BeginWrite;
// Do something with ThreadList
ThreadList.EndWrite;

A: when inheriting you fall into the load-modify-store trap
say you want to increase an object's priority:
int prio = myObject.getPriority();
myObject.setPriority(prio+1);

now consider what happens when another thread wants to lower the priority:
int prio = myObject.getPriority();
myObject.setPriority(prio-1);

one interleaved sequence of calls could be:
//thread1         //thead2
int prio1 = myObject.getPriority();
                  int prio2 = myObject.getPriority();
myObject.setPriority(prio1+1); // now is prio+1
                  myObject.setPriority(prio2-1); now is 2 lower than expected

there are several other options which are nearly all bad
this can be solved by encapsulating the operation in a method but that quickly becomes unfeasible for complex operations involving multiple objects
plus if the object changes you need to modify the locking subclass to include the new methods

A: One inarguable reason for taking that approach is because an object has a lock as opposed to is a lock. As soon you get is a / has a correct, everything gets simpler.


text:
Q: ETL flow for taking data from a remote service, transforming it to a local ORM Model, then setting up relationships? I recently set up my first "etl" flow to take data from a remote service, modify it to fit my local models, then save it.  Now that I've finished, it feels rather grotesque for a few reasons
my source is the JSON from the remote service
my transform replaces each row with a newly defined local model, based on the original source row
transform also looks at various values and defines additional local relationships
destination then calls .save on my newly replaced rows which are now models in the ORM.

*

*How am I supposed to create local records based on an external datasource? My models don't look like the remote sources.  Is it right to supplant a row entry with my new Model object?

*If I am supposed to replace the value of row with my local model, then I presume I should split each subsequent action into a transform on that new row (now a model)?

In all, my .etl looks like
pre_process do
  @some = <Go To DB and fetch data>
  @variables = <Setup More Information>
end

source MyRemoteSource

transform DoABunchOfWork,@some,@variables

destination CallSaveOnModels

DoABunchOfWork class has about 6 methods that process will call to manipulate or setup relationships in various ways


text:
Q: Glassfish - high CPU usge I'm using Glassfish 3.1.1 web profile in production envirnoment and it's eating too much CPU.
Here is server settings: Windows Server 2008 R2 64bit, Intel Xeon 8core @ 3,2GHz, 8GB ram.
I'm using JDK 1.7u2 64bit. Glassfish JVM settings:
<jvm-options>-XX:+UseCompressedOops</jvm-options>
<jvm-options>-Xmn1g</jvm-options>
<jvm-options>-Xss128k</jvm-options>
<jvm-options>-XX:+UseParallelOldGC</jvm-options>
<jvm-options>-XX:ParallelGCThreads=4</jvm-options>
<jvm-options>-Xmx3g</jvm-options>
<jvm-options>-XX:+DisableExplicitGC</jvm-options>
<jvm-options>-d64</jvm-options>
<jvm-options>-XX:PermSize=256m</jvm-options>
<jvm-options>-Xms3g</jvm-options>
<jvm-options>-XX:MaxPermSize=256m</jvm-options>
<jvm-options>-XX:+AggressiveHeap</jvm-options>

I've also tune some options according to http://jfarcand.wordpress.com/2009/11/27/putting-glassfish-v3-in-production-essential-surviving-guide/
Running for few hours or 1 day Glassfish use 15% to 40% CPU, someties 90% and application dosen't respond.
[#|2012-02-03T10:30:46.837+0100|WARNING|glassfish3.1.1|com.sun.grizzly.config.GrizzlyServiceListener|_ThreadID=43;_ThreadName=Thread-2;|GRIZZLY0023: Interrupting idle Thread: http-thread-pool-80(32).|#]

[#|2012-02-03T10:30:55.074+0100|WARNING|glassfish3.1.1|com.sun.grizzly.config.GrizzlyServiceListener|_ThreadID=41;_ThreadName=Thread-2;|GRIZZLY0023: Interrupting idle Thread: http-thread-pool-80(41).|#]

[#|2012-02-03T10:30:56.665+0100|SEVERE|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=138;_ThreadName=Thread-2;|java.nio.channels.ClosedChannelException
    at sun.nio.ch.SocketChannelImpl.ensureWriteOpen(SocketChannelImpl.java:249)
    at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:440)
    at com.sun.grizzly.util.OutputWriter.flushChannel(OutputWriter.java:108)
    at com.sun.grizzly.util.OutputWriter.flushChannel(OutputWriter.java:76)
    at com.sun.grizzly.http.SocketChannelOutputBuffer.flushChannel(SocketChannelOutputBuffer.java:326)
    at com.sun.grizzly.http.SocketChannelOutputBuffer.flushBuffer(SocketChannelOutputBuffer.java:398)
    at com.sun.grizzly.http.SocketChannelOutputBuffer.realWriteBytes(SocketChannelOutputBuffer.java:282)
    at com.sun.grizzly.tcp.http11.InternalOutputBuffer$OutputStreamOutputBuffer.doWrite(InternalOutputBuffer.java:898)
    at com.sun.grizzly.tcp.http11.filters.ChunkedOutputFilter.doWrite(ChunkedOutputFilter.java:167)
    at com.sun.grizzly.tcp.http11.filters.GzipOutputFilter$FakeOutputStream.write(GzipOutputFilter.java:223)
    at java.util.zip.GZIPOutputStream.finish(GZIPOutputStream.java:169)
    at java.util.zip.DeflaterOutputStream.close(DeflaterOutputStream.java:238)
    at com.sun.grizzly.tcp.http11.filters.GzipOutputFilter.recycle(GzipOutputFilter.java:186)
    at com.sun.grizzly.http.SocketChannelOutputBuffer.recycle(SocketChannelOutputBuffer.java:417)
    at com.sun.grizzly.http.ProcessorTask.finishResponse(ProcessorTask.java:817)
    at com.sun.grizzly.http.ProcessorTask.postResponse(ProcessorTask.java:750)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:726)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1019)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
    at java.lang.Thread.run(Thread.java:722)
|#]

[#|2012-02-03T10:30:56.665+0100|SEVERE|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=138;_ThreadName=Thread-2;|    at sun.nio.ch.SocketChannelImpl.ensureWriteOpen(SocketChannelImpl.java:249)|#]

[#|2012-02-03T10:30:56.665+0100|SEVERE|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=138;_ThreadName=Thread-2;|    at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:440)|#]

[#|2012-02-03T10:30:56.665+0100|SEVERE|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=138;_ThreadName=Thread-2;|    at com.sun.grizzly.util.OutputWriter.flushChannel(OutputWriter.java:108)|#]

[#|2012-02-03T10:30:56.665+0100|SEVERE|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=138;_ThreadName=Thread-2;|    at com.sun.grizzly.util.OutputWriter.flushChannel(OutputWriter.java:76)|#]

[#|2012-02-03T10:30:56.665+0100|SEVERE|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=138;_ThreadName=Thread-2;|    at com.sun.grizzly.http.SocketChannelOutputBuffer.flushChannel(SocketChannelOutputBuffer.java:326)|#]

[#|2012-02-03T10:30:56.665+0100|SEVERE|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=138;_ThreadName=Thread-2;|    at com.sun.grizzly.http.SocketChannelOutputBuffer.flushBuffer(SocketChannelOutputBuffer.java:398)|#]

[#|2012-02-03T10:30:56.665+0100|SEVERE|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=138;_ThreadName=Thread-2;|    at com.sun.grizzly.http.SocketChannelOutputBuffer.realWriteBytes(SocketChannelOutputBuffer.java:282)|#]

[#|2012-02-03T10:30:56.665+0100|SEVERE|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=138;_ThreadName=Thread-2;|    at com.sun.grizzly.tcp.http11.InternalOutputBuffer$OutputStreamOutputBuffer.doWrite(InternalOutputBuffer.java:898)|#]

[#|2012-02-03T10:30:56.681+0100|SEVERE|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=138;_ThreadName=Thread-2;|    at com.sun.grizzly.tcp.http11.filters.ChunkedOutputFilter.doWrite(ChunkedOutputFilter.java:167)|#]

[#|2012-02-03T10:30:56.681+0100|SEVERE|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=138;_ThreadName=Thread-2;|    at com.sun.grizzly.tcp.http11.filters.GzipOutputFilter$FakeOutputStream.write(GzipOutputFilter.java:223)|#]

[#|2012-02-03T10:30:56.681+0100|SEVERE|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=138;_ThreadName=Thread-2;|    at java.util.zip.GZIPOutputStream.finish(GZIPOutputStream.java:169)|#]

[#|2012-02-03T10:30:56.681+0100|SEVERE|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=138;_ThreadName=Thread-2;|    at java.util.zip.DeflaterOutputStream.close(DeflaterOutputStream.java:238)|#]

[#|2012-02-03T10:30:56.681+0100|SEVERE|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=138;_ThreadName=Thread-2;|    at com.sun.grizzly.tcp.http11.filters.GzipOutputFilter.recycle(GzipOutputFilter.java:186)|#]

[#|2012-02-03T10:30:56.681+0100|SEVERE|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=138;_ThreadName=Thread-2;|    at com.sun.grizzly.http.SocketChannelOutputBuffer.recycle(SocketChannelOutputBuffer.java:417)|#]

[#|2012-02-03T10:30:56.681+0100|SEVERE|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=138;_ThreadName=Thread-2;|    at com.sun.grizzly.http.ProcessorTask.finishResponse(ProcessorTask.java:817)|#]

[#|2012-02-03T10:30:56.681+0100|SEVERE|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=138;_ThreadName=Thread-2;|    at com.sun.grizzly.http.ProcessorTask.postResponse(ProcessorTask.java:750)|#]

[#|2012-02-03T10:30:56.681+0100|SEVERE|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=138;_ThreadName=Thread-2;|    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:726)|#]

[#|2012-02-03T10:30:56.681+0100|SEVERE|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=138;_ThreadName=Thread-2;|    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1019)|#]

[#|2012-02-03T10:30:56.681+0100|SEVERE|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=138;_ThreadName=Thread-2;|    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)|#]

[#|2012-02-03T10:30:56.681+0100|SEVERE|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=138;_ThreadName=Thread-2;|    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)|#]

[#|2012-02-03T10:30:56.681+0100|SEVERE|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=138;_ThreadName=Thread-2;|    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)|#]

[#|2012-02-03T10:30:56.681+0100|SEVERE|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=138;_ThreadName=Thread-2;|    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)|#]

[#|2012-02-03T10:30:56.681+0100|SEVERE|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=138;_ThreadName=Thread-2;|    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)|#]

[#|2012-02-03T10:30:56.681+0100|SEVERE|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=138;_ThreadName=Thread-2;|    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)|#]

[#|2012-02-03T10:30:56.681+0100|SEVERE|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=138;_ThreadName=Thread-2;|    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)|#]

[#|2012-02-03T10:30:56.681+0100|SEVERE|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=138;_ThreadName=Thread-2;|    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)|#]

[#|2012-02-03T10:30:56.681+0100|SEVERE|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=138;_ThreadName=Thread-2;|    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)|#]

[#|2012-02-03T10:30:56.681+0100|SEVERE|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=138;_ThreadName=Thread-2;|    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)|#]

[#|2012-02-03T10:30:56.681+0100|SEVERE|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=138;_ThreadName=Thread-2;|    at java.lang.Thread.run(Thread.java:722)|#]

[#|2012-02-03T10:31:00.440+0100|WARNING|glassfish3.1.1|com.sun.grizzly.config.GrizzlyServiceListener|_ThreadID=40;_ThreadName=Thread-2;|GRIZZLY0023: Interrupting idle Thread: http-thread-pool-80(38).|#]

[#|2012-02-03T10:33:49.170+0100|WARNING|glassfish3.1.1|com.sun.grizzly.config.GrizzlyServiceListener|_ThreadID=40;_ThreadName=Thread-2;|GRIZZLY0023: Interrupting idle Thread: http-thread-pool-80(11).|#]

[#|2012-02-03T10:33:57.235+0100|WARNING|glassfish3.1.1|com.sun.grizzly.config.GrizzlyServiceListener|_ThreadID=43;_ThreadName=Thread-2;|GRIZZLY0023: Interrupting idle Thread: http-thread-pool-80(16).|#]

Edit: I solved the problem, there is bug in Glassfish gzip compression, so I turned it off.
http://www.java.net/forum/topic/glassfish/glassfish/glassfish-301-gzip-problem-threads-apparently-spinning-100-cpu-use
Instead I would use this: http://www.servletsuite.com/servlets/gzipflt.htm to compress content.

A: This is apparently a bug in GlassFish 3.1.1 and 3.1.2. The JIRA issue for it contains patches which might help.

A: This can be caused by an infinite loop in Java code which is referenced by an expression in a view. Take a tread dump of your application server when it is running and gets this problem, and search for the problematic thread(s) like your http-thread-pool-80(32) and http-thread-pool-80(41) -- if your application server is spending all its time on one section of your application code, it may well be an infinite loop (or something else that causes that code to be run more often than it should).

A: We had a similar problem, even though we did not use GZIP. After a while (and under high load) our logs would fill up with
GRIZZLY0023: Interrupting idle Thread: http-thread-pool-28080(34)
We managed to resolve this for Glassfish 3.1.1 by upgrading grizzly to a version found in Glassfish 3.1.2.2. Read more about it at http://thumbtribe-it.blogspot.com/2012/10/grizzly0023.html


text:
Q: Internet Explorer 9 Object Detection I am searching for an object detection capability check which will identify IE9. Can you help me?

A: Check out this snippet by James Padolsey:
// ----------------------------------------------------------
// A short snippet for detecting versions of IE in JavaScript
// without resorting to user-agent sniffing
// ----------------------------------------------------------
// If you're not in IE (or IE version is less than 5) then:
//     ie === undefined
// If you're in IE (>=5) then you can determine which version:
//     ie === 7; // IE7
// Thus, to detect IE:
//     if (ie) {}
// And to detect the version:
//     ie === 6 // IE6
//     ie > 7 // IE8, IE9 ...
//     ie < 9 // Anything less than IE9
// ----------------------------------------------------------

// UPDATE: Now using Live NodeList idea from @jdalton

var ie = (function(){

    var undef,
        v = 3,
        div = document.createElement('div'),
        all = div.getElementsByTagName('i');

    while (
        div.innerHTML = '',
        all[0]
    );

    return v > 4 ? v : undef;

}());

Afterwards, you could use it like this:
if (ie == 9) {
  // It's IE9!
  // Insert your code here
}

The good thing here is that it doesn't sniff the UA string (which, in itself, is unreliable) — instead, it uses conditional comments, which work reliably in IE.
This can be used to detect IE5—9.

A: Not 100% sure this is what you're asking, but if you want to detect information about the browser of the visitor you can do check navigator.appVersion
Example:

A: Use the properties of the IE window object introduced in each release to distinguish IE versions:

*

*IE >= 7: ("onpropertychange" in document) && (!!window.XMLHttpRequest)

*IE >= 8: ("onpropertychange" in document) && (!!window.XDomainRequest)

*IE >= 9: ("onpropertychange" in document) && (!!window.innerWidth)

*IE >= 10: ("onpropertychange" in document) && (!!window.matchMedia)

*IE >= 11: (!!window.msMatchMedia) && (!window.doScroll)


text:
Q: Scroll to top after clicking page 2 in WooCommerce When you have products split on multiple pages in WooCommerce, it loads the next paage from the bottom. Because I have lazyload on images this means for a while there is just an empty white page. I would like to move to the top when the next page is loaded.
My code doesn't work. I have tried the following in my functions.php:

<?php if (isset($_GET['swoof'])): ?>

    <script>
        jQuery(function ($) {

            setTimeout(function () {
                $('html, body').animate({
                    scrollTop: $(".woof_products_top_panel_content").offset().top - 100
                }, 777);
            }, 333);

        });
    </script>

<?php endif; ?>


text:
Q: Powershell Exclude Multiple OUs I need to be able to exclude multiple OUs when searching for Active Users in Powershell. The list of OUs is stored in a data table which can be updated when new OUs need excluding. I can't think of a way of excluding these OUs dynamically, i.e. not requiring to update the script in order to add a new
(`$_.distinguishedname -notlike "*OU1*")

for each OU.
I've been attempting this for a good few hours now with no joy. I've even tried creating the filter by looping through the data table, such as
$ToReturn = "(`$_.distinguishedname -notlike ""*$Row[0]*"")"

and then add
$ToReturn = $ToReturn + " -and (`$_.distinguishedname -notlike ""*$Row[0]*"")"

for subsequent exclusions however it ignores the variable.
UPDATE 1: Code to return users::
$users = Get-ADUser -SearchBase $SourceOu -Server $Domain -Filter {
        whenCreated -lt $DisableDate
        -and PasswordNeverExpires -eq $False
        }|? {$ExludedOUs}

Where $ExcludedOUs is, I need a way of dynamically adding an equivalent of  ($_.distinguishedname -notlike "OU1") for each Exclusion in the datatable.
Many thanks in advance!
Lewis

A: You could use -notmatch and join your exclusions with | regex operator:
$OURegex = $ExcludedOUs -Join '|'
$users = Get-ADUser -SearchBase $SourceOu -Server $Domain -Filter {
    whenCreated -lt $DisableDate
    -and PasswordNeverExpires -eq $False
    } | Where-Object {$_.DistinguishedName -notmatch $OURegex}


text:
Q: Can I trigger a workflow from a hyperlink in a list? I'm trying to incorporate functionality in one of my lists that will allow users to submit candidate resumes for open jobs that appear in the list.  My initial thought was to just have a hyperlink column and place a 'mailto:' link there...simple enough.  However, I'd like to have, at minimum, a reference to which job was being applied for when the email is sent.
After some searching, I've found a way using SPD to build a URL string that links back to the list item in question (essentially it's a link to the list, and the list item ID is retrieved and appended to the end of the URL.  Using that, I've also built the next step in the workflow to produce the email, addressed to the appropriate recipient, with the desired information in the subject and body (job title, ref #, etc.).
Is there a way to trigger this workflow by adding a hyperlink to each list item, or something similar?  I don't want users needing to trigger the workflow, or the email from the ribbon.  I'd prefer if it's something in-line, where they see a job in the list, and can hit a 'Refer' link or button.
Any help would be appreciated.  Thanks!
(edit)
Thanks for the responses below.  I think I'm good now with creating a link or button to trigger the workflow, but now the problem seems to be the workflow itself!  It seems to be executing, but I'm not seeing the email get generated or sent.  Is it possible to have the workflow present the user with a 'Compose Message' window so they can add comments, attachments, etc?  This is really the functionality that I need.

A: Add a hyperlink field, and use a workflow (run on create and change) to set the value of the field.
In the workflow, set a variable equal to mailto:user@domain.com?subject=New Candidate&body=Job Title: [%Current Item:Job Title%]%0D%0AJob Number: [%Current Item:Job Number%]%0D%0ARef Number: Job-[%Current Item:ID%], Click to send email  Then Set field in current item, choose your hyperlink field, and set the value (from the fx button) to `Workflow Variables and Parameters" and your variable.
To get the info from your list (i.e. [%Current Item:Field%], select "Add or Change Lookup" and select Current Item and the field from source.
FYI, you can get the full link to the current item by selecting Workflow Context and Current Item URL.

A: You can add a quick action button to the lists ribbon where a user can click to manually start a workflow.
Do you have SharePoint Designer installed?
If you do, head over to your list, and from the list ribbon, in the Customize List section select New Quick Step.
This will allow you to create a new button in the ribbon, to start a 2010/2013 workflow manually on a selected list item.
Peter Kalmstrom has a great guide, as well as a video where he shows you how to do it.
Create A SharePoint Workflow Button

A: You could use a calculated column to build out the workflow link, since the only thing that changes in the workflow initiation page url is just the ID, you could add a calculated column, insert the link into a formula like this:
=CONCATENATE("Start Workflow")

Just go to an initiation page of any of the items to grab the URL and use it in the above formula. Make sure the returned data type is Number (for some reason Number will interpret the string as HTML).


text:
Q: Wait for query in Node.js MySQL When I run this right now the page renders before it can receive the data from MySQL. The loop goes for all the files in a folder and finds that data in the How can I make it wait for the data to be sent before loading the webpage?
app.get('/explore', function(req,res){
  var fileNames = new Array();
    pool.getConnection(function(err, connection) {
      fs.readdirSync('./files').forEach(file => {
        if (err) throw err;
        var requester = "SELECT * FROM files WHERE dbname = '" + file + "'";
        pool.query(requester, function (err, result) {
          if (err) throw err;
          fileNames.push(result[0].name);
        });
        connection.release();
      });
    });
  res.render('explore', { fileNames : fileNames })
});

A: You can make minor corrections in the code so that it renders as intended.
app.get('/explore', function(req,res){
  var fileNames = new Array();
    pool.getConnection(function(err, connection) {
      fs.readdirSync('./files').forEach(file => {
        if (err) throw err;
        var requester = "SELECT * FROM files WHERE dbname = '" + file + "'";
        pool.query(requester, function (err, result) {
          if (err) throw err;
          fileNames.push(result[0].name);
          res.render('explore', { fileNames : fileNames })
          //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        });
        connection.release();
      });
    });
});


text:
Q: Yesod external stylesheet using localhost I am running a Haskell/Yesod webapp on localhost:666. I used addScriptRemote to load JQuery, which works fine. I would also like to load an external stylesheet and tried: <link rel=...> in toWidgetHead, addStylesheetRemote... addStyleSheet with typesafe URL.
However, I can't seem to load the stylesheet. I did set the approot to approot = ApprootStatic "http://127.0.0.1" by reading another similar question on SO.
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings     #-}
{-# LANGUAGE QuasiQuotes           #-}
{-# LANGUAGE TemplateHaskell       #-}
{-# LANGUAGE TypeFamilies          #-}

module Main where
import           Text.Blaze.Html
import qualified Data.Text as T
import           Yesod
import           Hyper

data             WebApp = WebApp
data             MyRoute = Ext1 | Ext2 | Css1
instance         Yesod WebApp where
  approot = ApprootStatic "http://127.0.0.1:666"

mkYesod "WebApp" [parseRoutes|
  /      HomeR  GET
  /Page1 Page1R GET
  /Page2 Page2R GET
  -- /Json1 Json1R GET
|]
-- getHomeR is a handler-function. Most Yesod code lives in handler-functions
getHomeR :: Handler Html
getHomeR = defaultLayout [whamlet|placeholderto next #{pageVarPage}!|]
getPage1R :: Handler Html
getPage1R = defaultLayout [whamlet|

placeholder static page 1.
    nav towards page 2.
|]
getPage2R :: Handler Html
getPage2R = defaultLayout $ do
    setTitle "#{pageVarPage}"
    toWidget [lucius| h1 {color:green;} |]
    addScriptRemote "https://code.jquery.com/jquery-3.4.1.js"
    addStylesheetRemote "http://127.0.0.1/styles.css"
    toWidget
      [julius|
        $(function() {
          $("h1").click(function(){
            alert ("Test from the book");
          });
        });
      |]
    toWidgetHead
      [hamlet|
        <meta name=keywords content="haskell yesod framework">


text:
Q: Select Rows with min value for each group I have a database with a table that look like this:

Date
Container ID

1/1
1

2/2
1

3/3
1

4/4
2

5/5
2

6/6
3

7/7
3

Container ID is a foreign key to another table and the containers are effectively named groups that elements can be part of.
I'm looking to write a query that gets the earliest date for each Container ID like this:

Earliest Date
Container ID

1/1
1

4/4
2

6/6
3

Is there some way I can join on Container ID to make this happen or am I on the wrong path with joins?

A: But the best would be save dates as date column. The you can use all function for dates

CREATE TABLE table1 (
  [Date]  varchar(10),
  [Container ID] INTEGER
);

INSERT INTO table1
  ([Date], [Container ID])
VALUES
  ('1/1', '1'),
  ('2/2', '1'),
  ('3/3', '1'),
  ('4/4', '2'),
  ('5/5', '2'),
  ('6/6', '3'),
  ('7/7', '3');
GO

SELECT MIN([Date]), [Container ID] FROM table1 GROUP BY [Container ID]
GO

(No column name) | Container ID
:--------------- | -----------:
1/1              |            1
4/4              |            2
6/6              |            3

db<>fiddle here

A: You want group by and min():
select id, min(date)
from t
group by id;

As a note:  You could also use join, but it is a bit more arcane:
select t.*
from t left join
     t t2
     on t.id = t2.id and t2.date < t.date
where t2.id is null;

The left join is matching to rows that have a smaller date.  The smallest date (per id) is the one with no matching rows.

A: Just another option using WITH TIES
Select top 1 with ties *
 From  YourTable
 Order By row_number() over (partition by ContainerID Order by Date)

A: I have not used a date column but you can adjust yours to suit
CREATE TABLE DAta (Date_example VARCHAR(50), ContainerID INT)

INSERT INTO DAta (Date_example, ContainerID)
VALUES ('1a', 1)

INSERT INTO DAta (Date_example, ContainerID)
VALUES ('2a', 1)

INSERT INTO DAta (Date_example, ContainerID)
VALUES ('3a', 1)

INSERT INTO DAta (Date_example, ContainerID)
VALUES ('1b', 2)

INSERT INTO DAta (Date_example, ContainerID)
VALUES ('2b', 2)

INSERT INTO DAta (Date_example, ContainerID)
VALUES ('3b', 2)

INSERT INTO DAta (Date_example, ContainerID)
VALUES ('1c', 3)

INSERT INTO DAta (Date_example, ContainerID)
VALUES ('2c', 3)

INSERT INTO DAta (Date_example, ContainerID)
VALUES ('3c', 3)

The resulting table is:
+---------------+-------------+
| Date_example  | ContainerID |
+---------------+-------------+
| 1a            |           1 |
| 2a            |           1 |
| 3a            |           1 |
| 1b            |           2 |
| 2b            |           2 |
| 3b            |           2 |
| 1c            |           3 |
| 2c            |           3 |
| 3c            |           3 |
+---------------+-------------+

SOLUTION:
SELECT *
FROM (
    SELECT DATE_EXAMPLE
        ,CONTAINERID
        ,ROW_NUMBER() OVER (
            PARTITION BY CONTAINERID ORDER BY CONTAINERID
            ) ROW_NUM
    FROM DATA
    ) A
WHERE ROW_NUM = 1

OUTPUT:
+---------------+--------------+---------+
| date_example  | containerID  | row_num |
+---------------+--------------+---------+
| 1a            |           1  |       1 |
| 1b            |           2  |       1 |
| 1c            |           3  |       1 |
+---------------+--------------+---------+


text:
Q: How can I change the colour of only bottom border of text-box with multicolor in html/css? I am having a text box and I can set the border colour. I want to change only the bottom colour of the text box. Not only that, the bottom should be multi coloured. Like the image:
How can I achieve this? Please help

A: You can use CSS Gradients along with CSS Positioning to simulate such effect. For example :-

* {
  margin: 0;
  padding: 0;
}

textarea {
  resize: none;
  height: 100px;
  width: 400px;
  border: 1px solid #ddd;
}

div {
  margin: 40px;
  position: relative;
  display: inline-block;
  border-radius: 4px;
  overflow: hidden;
}

div:after {
  content: "";
  position: absolute;
  display: block;
  width: 100%;
  height: 5px;
  background: linear-gradient(to right, #ee585b 0%,#ee585b 33%,#ee585b 33%,#f8d270 33%,#f8d270 66%,#f8d270 66%,#20b5ca 66%,#20b5ca 100%);
  bottom: 0;
}

<textarea></textarea>

Here, am doing nothing but using an :after pseudo element and setting a gradient to that. Rest, am using positioning to set it to the bottom and than I use overflow: hidden; on the wrapper to make sure that it gets that border-radius effect and is not pointy on the edges.
There are other ways to do this, by setting :before or :after pseudo along with another stray element and setting background for all the three but that's not optimal at all imo.

Note: Make sure you use class or an id in your HTML for this
  particular textarea and change my CSS selectors accordingly. Am
  using basic tag level selectors just for the demonstration purpose.

A:

div:after {
  content: "";
  position: absolute;
  display: block;
  width: 100%;
  height: 5px;
  background-image: -webkit-linear-gradient(to right, #ee585b 0%,    #ee585b 33%, #f8d270 33%, #f8d270 66%, #20b5ca 66%, #20b5ca 100%);
  background-image: -o-linear-gradient(to right, #ee585b 0%,    #ee585b 33%, #f8d270 33%, #f8d270 66%, #20b5ca 66%, #20b5ca 100%);
  background-image: -moz-linear-gradient(to right, #ee585b 0%,    #ee585b 33%, #f8d270 33%, #f8d270 66%, #20b5ca 66%, #20b5ca 100%);
  background-image: linear-gradient(to right, #ee585b 0%,    #ee585b 33%, #f8d270 33%, #f8d270 66%, #20b5ca 66%, #20b5ca 100%);
  bottom: 0;
}

A: This is alternate solution for it.

* {
  margin: 0;
  padding: 0;
}

.sg-container
{
width:500px;
height:300px;
margin:200px auto;
border:1px solid #dcdcdc;
position:relative;

}

.sg-multicolor {
list-style:none;
width:100%;
font-size:0;
padding:0px;
position:absolute;
bottom:0px;
}

.sg-multicolor li {
display:inline-block;
width:33.3%;
height:5px;

}

.sg-multicolor li:nth-child(1) {
background:#F05757;
}

.sg-multicolor li:nth-child(2) {
background:#FAD46B;
}

.sg-multicolor li:nth-child(3) {
background:#08B5CC;
}


text:
Q: Checkboxes not checking in React drop down menu? I'm working on a dropdown menu in React.js which serves as a filter for some of the items of the page. The filter function works fine, but when I go to check one of the filters, the check does not show up.
import Button from '@material-ui/core/Button';
import Menu from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';

function Filter() {
    const [anchorEl, setAnchorEl] = React.useState(null);

    const handleClick = (event) => {
        setAnchorEl(event.currentTarget);
    };

    const handleClose = () => {
        setAnchorEl(null);
    };

    const handleChange = (event) => {
        setState({ ...state, [event.target.name]: event.target.checked });
    };

    return(

      <Button style={{color: "white"}} onClick={handleClick}>Filter</Button>
            <Menu id="simple-menu" anchorEl={anchorEl} keepMounted open={Boolean(anchorEl)} onClose={handleClose}>

                    <MenuItem>
                        <input type="checkbox" id="one" name="filter" onChange={handleChange} value="opt1" /> Option1
                    </MenuItem>

                    <MenuItem>
                        <input type="checkbox" id="two" name="filter" onChange={handleChange} value="Photography" className="medium" /> Photography
                    </MenuItem>

            </Menu>

    )
}

Basically, I want the checks in the checkboxes to show when I click them. How do I get them to show? I checked to ensure that I'm using the correct conventions for checkboxes with the name and the div that you are supposed to use between them, but I wondering why it still won't show. I'm using components of the Material-UI library: https://material-ui.com/components/menus/

A: because the input name is equal you have change the name how this:

    <MenuItem>
     <input type="checkbox" id="one" name="filter1" onChange={handleChange} value="opt1" /> Option1
    </MenuItem>

    <MenuItem>
       <input type="checkbox" id="two" name="filter2"
         onChange={handleChange} value="Photography" className="medium" />
         Photography
    </MenuItem>

A: The main problem is with handleChange function - there is no setState in scope.
For functional component you can control state with useState hook.
Also I would recommend you to use mui Checkbox component - since you will need only these 3 properties to control its state: name, checked and onChange.
Here is an example, with your code:
import React from "react";
import Button from "@material-ui/core/Button";
import Menu from "@material-ui/core/Menu";
import MenuItem from "@material-ui/core/MenuItem";
import Checkbox from "@material-ui/core/Checkbox";

export default function Filter() {
  const [anchorEl, setAnchorEl] = React.useState(null);
  const [filterState, setFilterState] = React.useState({
    filter1: false,
    filter2: false
  });

  const handleChange = (event) => {
    setFilterState({
      ...filterState,
      [event.target.name]: event.target.checked
    });
  };

  const handleClick = (event) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  return (

      <Button onClick={handleClick}>Filter</Button>
      <Menu
        id="simple-menu"
        anchorEl={anchorEl}
        keepMounted
        open={Boolean(anchorEl)}
        onClose={handleClose}
      >

          <MenuItem>
            <Checkbox
              name="filter1"
              checked={filterState.filter1}
              onChange={handleChange}
            />
          </MenuItem>

          <MenuItem>
            <Checkbox
              name="filter2"
              checked={filterState.filter2}
              onChange={handleChange}
            />
          </MenuItem>

      </Menu>

  );
}


text:
Q: Write something below ampersand sign I need to write something below and top of ampersand sign. I want it to be like \sum. I have tried
\&_{i = 0}^{n}

but it shows  i=0 in the index but not below ampersand sign.

A: If you wanted the ampersand to display larger in display style, you can use scalerel package to grow the size to match the vertical extent of the \sum sign.
\documentclass{article}
\usepackage{amsmath}
\DeclareMathOperator*{\foo}{\scalerel*{\&}{\sum}}
\usepackage{scalerel}
\begin{document}
\[ \foo_{i=3}^{6}(f^2(i)) \]
\centering This is inline: \(\foo_{i=3}^{6}(f^2(i)) \)
\end{document}

A: \documentclass{report}

\DeclareMathOperator*{\amper}{\&}

\begin{document}
Inline: $\amper_{i=1}^n$

Inline with display: $\amper\limits_{i=1}^n$

Display: \[ \amper_{i=1}^n \]
\end{document}


text:
Q: How to define section number that 2d-array is divided to using Python? I have this data structure:

It is 2d-array that is divided on 3 sections. For each letter in the array I need to define Section number. For example, letters a,b,c,d are in Section 1; e,f,g,h are in Section 2.

My code. Firstly, this 2d-array preparation:
from itertools import cycle
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l']

#2d-array initialization
width, height = 3, 6
repRange = cycle(range(1, 3))
values = [0] * (width - 1)
array2d = [[next(repRange)] + values for y in range(height)]

#Filling array with letters:
m = 0
for i in range(height):
    for j in range(1,width):
       array2d[i][j] = letters[m]
       m+=1

#Printing:
for row in array2d:
    print(row)

Output:
[1, 'a', 'b']
[2, 'c', 'd']
[1, 'e', 'f']
[2, 'g', 'h']
[1, 'i', 'j']
[2, 'k', 'l']

Now I need to determine section number of each letter and save it along with the letter itself. I use defineSection function and save values in dictionary:
def defineSection(i, division, height):
    if i <= division:
        return 1
    elif division*2 >= i > division :
        return 2
    elif division*3 >= i > division*2 :
        return 3

dic = {}
for i in range(height):
    for j in range(1,width):
        section = defineSection(i+1, 2, height)
        dic.update({array2d[i][j] : section})

for item in dic.items():
    print(item)

Output:
('f', 2)
('b', 1)
('c', 1)
('e', 2)
('k', 3)
('g', 2)
('d', 1)
('a', 1)
('l', 3)
('h', 2)
('i', 3)
('j', 3)

It defined all section numbers for each letter correctly. But defineSection method is primitive and will not work if number of rows is bigger than 6.
I don't know how to implement defineSection method so that it defines Section number automatically taking into account only current Row number, division and number of rows in total.

Question: Is there some way I can simply determine section number without so many if-elif conditions and independently of total number of rows?

A: You can simplify your matrix creation code immensely. All you need is a letters iterator, which returns itself so you can iterate 2-letters at a time using zip.
In [3]: from itertools import cycle

In [4]: letters = "abcdefghijkl"

In [5]: ranges = cycle(range(1,3))

In [6]: iter_letters = iter(letters)

In [7]: matrix = [[i,a,b] for i,a,b in zip(ranges,iter_letters,iter_letters)]

In [8]: matrix
Out[8]:
[[1, 'a', 'b'],
 [2, 'c', 'd'],
 [1, 'e', 'f'],
 [2, 'g', 'h'],
 [1, 'i', 'j'],
 [2, 'k', 'l']]

As for assigning sections, note that a section is every two rows, which is four letters, so you can use simple floor division to "skip" counts.
In [9]: sections = {letter:(i//4 + 1) for i,letter in enumerate(letters)}

In [10]: sections
Out[10]:
{'a': 1,
 'b': 1,
 'c': 1,
 'd': 1,
 'e': 2,
 'f': 2,
 'g': 2,
 'h': 2,
 'i': 3,
 'j': 3,
 'k': 3,
 'l': 3}


text:
Q: How to disable MySQL Query Caching I am trying to do some benchmarking of different queries on different columns but MySQL just won't let me do it. After the first execution of a query, I can never get the same execution time for that query again. For example if the query executes in 0.062 secs the first time, I can never get the same execution time for the 2nd, 3rd etc runs. It becomes either 0 seconds or something like 0.015.
I have read many posts on disabling and clearing MySQL query cache but none of them has been of any help for me.
like this SO post here
No matter what I do, MySQL seems to insist on using cached results.
I restart the MySQL Workbench then I run;
set global query_cache_type=0;
set global query_cache_size=0;
flush query cache;
reset query cache;

The execution time keeps showing 0 secs.
Only server variable that I haven't been able to change is "have_query_cache". Its value is "yes" and when I try to set it to "no" Workbench says it is read-only.
I also do;
set profiling=1;
run my select query
show profile for query 2;

Profiling result shows this:
'starting', '0.000077'
'checking permissions', '0.000007'
'Opening tables', '0.000016'
'init', '0.000035'
'System lock', '0.000009'
'optimizing', '0.000013'
'statistics', '0.000094'
'preparing', '0.000008'
'executing', '0.000002'
'Sending data', '0.000016'
'end', '0.000002'
'query end', '0.000003'
'closing tables', '0.000005'
'freeing items', '0.000139'
'cleaning up', '0.000009'

If I am not wrong this shows that no caches are being used right? But I stil see 0 secs. for the execution time.
Edit: The query I am running is a SELECT query using "SQL_NO_CACHE" like so:
SELECT SQL_NO_CACHE col1,now() from mytable where col2="some_value"

(I added now() function to help me prevent query caching)
Edit2: I am using innoDB, MySQL 5.6.10
Could someone please help me cause I can't see what is going on here.
Thanks a lot!

A: You can verify the difference between buffer pool page reads versus page reads that had to go to disk to get the page:
mysql> SHOW SESSION STATUS LIKE 'Innodb_buffer_pool_read%';
mysql> ...run a query...
mysql> SHOW SESSION STATUS LIKE 'Innodb_buffer_pool_read%';

Compare these values from the report, and note how much they grow:
+---------------------------------------+----------+
| Variable_name                         | Value    |
+---------------------------------------+----------+
| Innodb_buffer_pool_read_requests      | 10327490 |
| Innodb_buffer_pool_reads              | 1133     |
+---------------------------------------+----------+

The read_requests are logical page reads, which may read from pages already in the buffer pool.  If this number grows after your query, but reads doesn't grow, then your query got its result solely from the buffer pool.
The reads are the number of page reads that had to go out to disk and incur the cost of I/O to copy pages into the buffer pool.  If this number grows after your query, then it had to load data from disk.
For more on the difference between the performance of memory access versus disk access, read http://everythingisdata.wordpress.com/2009/10/17/numbers-everyone-should-know/

Re your comment:
The "Opening tables" is related to an in-memory cache of InnoDB tables, kind of like a data dictionary.  Tables are opened the first time they are referenced after a restart.  A given table's entry in the in-memory data dictionary stays in memory indefinitely, so that memory usage can grow pretty large if you have thousands of tables.  In MySQL 5.6, they have some ne tuning variables to put a cap on that memory usage, and evict infrequently-used tables.  But this whole mechanism is separate from the buffer pool, which stores pages of data and indexes.
The "statistics" is also separate from the buffer pool.  InnoDB maintains in-memory statistics about data and indexes, which it uses to guide the query optimizer.  Statistics are refreshed automatically when you first access an InnoDB table, when you run SHOW TABLE STATUS or run certain queries against the INFORMATION_SCHEMA, when you run ANALYZE TABLE, and also when the size of the table changes significantly.  InnoDB generates these statistics reading a fixed number of pages from the table at random, and this is likely to hit the disk if you have a cold buffer pool.

A: OK. So I have been diggin' on this innoDB buffer pool issue. Thank you @Quassnoi, @TheVedge for mentioning that. It has been very useful for the following work.
I was trying to find a way to disable or reset innoDB buffer pool but I haven't been able to find a way other than restarting MySQL server. (To restart the server on a windows box you can either use services.msc or command prompt.)
I guess all the configuration variable settings and the use of "SQL_NO_CACHE" was more than enough to avoid cache use, and also checking the profiling results I was not seeing any cache reference neither (check the original post).
Then I decided to check the profiling for the same query's 1st and 2nd runs after restarting MySQL server. This way I would be able to see what was going on during the query execution step by step.
1st run after server restart yielded the following steps and timings:
'starting', '0.000078'
'checking permissions', '0.000005'
'Opening tables', '0.120329'
'init', '0.000107'
'System lock', '0.000012'
'optimizing', '0.000024'
'statistics', '0.065317'
'preparing', '0.000026'
'executing', '0.000003'
'Sending data', '0.000038'
'end', '0.000005'
'query end', '0.000006'
'closing tables', '0.000014'
'freeing items', '0.000463'
'cleaning up', '0.000039'

And these are the results of the 2nd run:
'starting', '0.000068'
'checking permissions', '0.000006'
'Opening tables', '0.000019'
'init', '0.000046'
'System lock', '0.000007'
'optimizing', '0.000010'
'statistics', '0.000073'
'preparing', '0.000009'
'executing', '0.000002'
'Sending data', '0.000035'
'end', '0.000003'
'query end', '0.000003'
'closing tables', '0.000006'
'freeing items', '0.000181'
'cleaning up', '0.000015'

As you can see there is a huge difference for the durations of "opening tables" and "statistics" actions between the two executions and none of the executions reference any cache.
The two actions seem to be the most time consuming parts for the 1st execution (I believe as a part of the creation of innoDB buffer pool), and once the pool is generated these two actions not performed as heavily hence the much shorter execution time for the query after the buffer pool creation.
When you sum up the execution times of the individual steps for 2nd run we get 0.000483 seconds and I think MySQL workbench shows this result as 0.000 secs which might also trick you to think that the second run was result of cache using but actually it seems like it is not. This is just a display precision issue for the execution durations of queries.
As a result what I have figured out so far is I actually have been able to disable the use of caches and it is the completion of innoDB buffer pool that speeds up the second query so much. This also means that I can find a record in 2 million rows in 0.000483 seconds.
Would you agree?

A: This could be due to the cache of the data itself, and not the query cache.
To make sure, you can disable the query cache for a single statement by adding SQL_NO_CACHE after your SELECT statement.
Ex:
SELECT SQL_NO_CACHE field FROM table.

A: Running the query for the first time makes InnoDB buffer pool populate with your tables' relevant blocks.
Since re-running the query requires exactly same blocks, it spares the query from the need to read them from disk when it's re-run, making it significantly faster.

A: In your .ini/.cfg in [mysqld] section, add a line have_query_cache=0  # to prevent using resources  from default of yes  ccyy/mm/dd  your initials.  With your other changes, close/restart MySQL.  You should NOT observe any QC activity in profile research.


text:
Q: Exit Criteria with attribut comparison between Journey and Synchronized Data Extensions doesn't work I am trying to set multiple exit criterias in a journey but it doesn't work.
What I did:
I created a journey with Salesforce Entry Event, based on the Account object.
I linked the Journey Data Extension in Data Designer (Contact key to Account:PersonContact:Id)

In the journey I set up the exit criteria as:
(DoubleOptIn__pc is False AND Id equal Account:Id ) OR ( ActiveContract__pc is True AND Id equal Account:Id )

DoubleOptIn__pc = False asks for the synchronized Account DE. To have an unambigous comparison Id equal Account:Id compares the Account Id from the Journey DE with the Account Id of the synchronized DE as an attribute comparison.
Then I triggered contacts in the journey, then I updated the DoubleOptIn__pc field, respectively the ActiveContract__pc field according to the exit criteria but it doesn't work.
Where's the mistake? Would I need to relate between Contact Ids in the exit criteria or is this step even necessary?


text:
Q: WordPress: Place smaller image with transparent background in front of image I would like to place a smaller image with a transparent background in front of a header image in WordPress. The theme I am currently using allows me to set own css styles but I have no clue how to achieve my goal.
Has anybody already worked on this?
Thanks a ton,
Anton

A: Here is an example how to place an image in front of another image. I placed a PNG of a bee inside a banner image.

HTML

CSS
#container {
  position: relative;
}

#banner {
  width: 600px;
}

#bee {
  position: absolute;
  z-index: 5;
  top: 20px;
  left: 20px;
  width: 100px;
}

When we set position: absolute, that element will always be position relative to the nearest parent with position: relative (or absolute). And then you can refine the position of the absolutely positioned element using top, bottom, left, right css properties.
Play arround with this fiddle


text:
Q: elasticsearch update query Create a document/table 'task' in ElasticSearch with the following fields

*

*ID (Auto generated while inserting)

*task_id (Integer)

*priority (integer)

*queue (varchar)

*process (varchar)

*task (varchar)

*status (char)

*user (char)

*description (varchar)

*due_date (Date Time)

*created_on (Date time)

*updated_on (Date time)

A: Here are couple commands which will help you to set-up basic ES index:

*

*Set-up your mappings:
curl -XPUT http://localhost:9200/my_tasks -d '
{
  "mappings": {
    "task": {
      "properties": {
        "task_id": {
          "type":     "integer"
        },
        "priority": {
          "type":     "integer"
        },
        "queue": {
          "type":     "string"
        },
        "process": {
          "type":     "string"
        },
        "task": {
          "type":     "string"
        },
        "status": {
          "type":     "string"
        },
        "user": {
          "type":     "string"
        },
        "description": {
          "type":     "string"
        },
        "due_date": {
          "type":     "date"
        },
        "created_on": {
          "type":     "date"
        },
        "updated_on": {
          "type":     "date"
        }
      }
    }
  }
}'

*Set-up simple document:
curl -XPOST http://localhost:9200/my_tasks/task/ -d '
{
  "task_id": "64123",
  "priority": "2",
  "queue": "Implementation",
  "process": "Project Sample",
  "task": "Feature-64123",
  "status": "In Progress",
  "user": "John Smith",
  "description": "Set-up basic ElasticSearch task",
  "due_date": "2017-03-24T00:00:00Z",
  "created_on": "2017-03-21T01:51:12Z",
  "updated_on": "2017-03-21T01:56:54Z"
}'

*Query your index (silly match_all query):
curl -XGET http://localhost:9200/my_tasks/_search -d '
{
    "query": {
        "match_all": {}
    }
}'