text:
Q: Geolocation doesn't work I have the following problem, the geolocation doesn't work. I use eclipse with phonegap libraries and adt plugin. The code of my project is in html and jquery.
The script that i use is this:
function initialize() {

    var locations = [
        ['Hougang', 1.37265, 103.893658],
        ['Punggol', 1.400617, 103.907833],
        ['MacRitchie Reservoir', 1.346002, 103.825436],
        ['Bishan', 1.352051, 103.849125],
        ['Sentosa', 1.251226, 103.830757]
        ];

    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 15,
        center: new google.maps.LatLng(1.37265, 103.893658),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();

    var marker, i;

    for (i = 0; i < locations.length; i++) {
        marker = new google.maps.Marker({
            position: new google.maps.LatLng(locations[i][1], locations[i][2]),
            map: map
        });

        google.maps.event.addListener(marker, 'click', (function(marker, i) {
            return function() {
                infowindow.setContent(locations[i][0]);
                infowindow.open(map, marker);
            }
        })(marker, i));
    }

    // Check if user support geo-location
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;
            var geolocpoint = new google.maps.LatLng(latitude, longitude);

            var mapOptions = {
                zoom: 8,
                center: geolocpoint,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            // Place a marker
            var geolocation = new google.maps.Marker({
                position: geolocpoint,
                map: map,
                title: 'Your geolocation',
                icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png'
            });
        });
    }
}
google.maps.event.addDomListener(window, 'load', initialize);

I do not understand where can be the error.


text:
Q: Catching several exceptions and rethrowing a general exception I'm using reflection to add some data to a private variable inside a class from a third-party library.  Along the way there are about four different Exceptions that can be thrown; all of them are related to reflection, and all of them are very unlikely to occur.  I'm hardcoding the name of the class and variable involved.  I'm unlikely to receive any class not found or field not found errors, unless the library gets upgraded some day and has changed significantly.
I'd rather not declare all four of these exceptions for my caller to handle.  He's likely to never see them.  I'd like to just catch all of these and throw another exception to say "A Java reflection error has occured; it is likely that the library has been upgraded and changed in a way incompatible with this method."  Is there a standard Java Exception I can throw that indicates just a general reflection error?  Should I define my own?  Or would it be best to just declare that this method can throw all of the possible reflection exceptions?

A: I usually ask myself these questions:

*

*Can whomever calls this method handle these different exception types differently?

*...Or would they treat them all the same?

*Can the caller/user even recover from this error?

If the calling code is likely to treat all four of these exceptions the same (as an unrecoverable error), then it absolutely makes sense to capture each of them and re-throw a more general (single) exception. If you do, make sure you attach the generated exception as an inner exception, just to help any debugging or troubleshooting on the other end.

A: There is some controversy about checked vs unchecked exceptions.  Personally I think checked exceptions are the worst idea in Java--but that's just an opinion (however I'm not alone thinking that)
Anyway, I think the important thing would be to change them to either a single unchecked exception.  More often than not I use a single one like IllegalStateException or IllegalParameterException--with a clear text description, those two exceptions cover 90% of the crap that can go wrong with a method.

A: First off, don't use reflection unless you really, really have to, because it is evil. Assuming you do have to:
As you are hardcoding all the names, it just leaves Method.invoke, Constructor.newInstance and Field.get/set. I'd suggest just rethrowing the checked exceptions you can deal with wrapped in Error. They shouldn't happen, and if you want to deal with it I suggest doing the check at class intialisation time. InvocationTargetException should, of course, be unwrapped and dealt with in an appropriate manner (throw a wrapped Error for checked exception which the method/constructor did not declare).

A: You can turn all the Exceptions into an AssertionError if you never expect them to occur.
InvocationTargetException can be unwrapped if you want to deal with a specific exception.
If you want to throw the actual exception thrown by the method rather than InvocationTargetException you can use this trick, but it may be more confusing than useful
} catch (InvocationTargetException e) {
    // Throw any exception in the current thread (even if it is a checked exception)
    Thread.currentThread().stop(e.getCause());
}

A: How about having those Exception classes extended from a GeneralException and catch that that GeneralException?
I'll try this right now! :)

A: I don't think it makes sense to declare exceptions in this case.
So I would catch the exceptions from reflection, maybe log a stack trace, and throw some RuntimeException, which has the advantage that it doesn't need to be declared.
You could just use RuntimeException with a suitable message, if you are lazy.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I set limits in the y-axis for a Pan Gesture? I want to limit my imageview to specific y-coordinates, but every-time I drag it over or below the 2-coordinates, the view gets stuck and doesn't move again. Also, if I drag fast enough, the imageView goes above or below the coordinates that i limited it to.
@IBAction func handlePan(_ gesture: UIPanGestureRecognizer) {
      // 1
      let translation = gesture.translation(in: view)

      // 2
      guard let gestureView = gesture.view else {
        return
      }

        if gestureView.center.y >= 161 && gestureView.center.y <= 561 {
            gestureView.center.y = gestureView.center.y + translation.y
            gesture.setTranslation(.zero, in: view)
        }

      // 3
      gesture.setTranslation(.zero, in: view)
    }

A: Instead of just not moving the image view at all when its y coordinate is outside of the specified range, you should still allow the image view to be moved downwards if it is too high, and upwards if it is too low.
It would be easier to specify in which situations you don't want the image view to be moved:

*

*y < 161 and panning upwards

*y > 561 and panning downwards

Also, the reason why you can move it out of the valid y range by dragging very fast is because you only check whether the image view's y coordinate is in the range before moving it, but not after. You should instead clamp the values when adding translation.y.
@IBAction func handlePan(_ gesture: UIPanGestureRecognizer) {
    // 1
    let translation = gesture.translation(in: view)

    // 2
    guard let gestureView = gesture.view else {
        return
    }

    // in these two cases, don't translate the image view
    if (gestureView.center.y < 161 && translation.y < 0) ||
        (gestureView.center.y > 561 && translation.y > 0) {
        gesture.setTranslation(.zero, in: view)
        return
    }

    // clamping the translated y
    gestureView.center.y = min(max(gestureView.center.y + translation.y, 161), 561)
    gesture.setTranslation(.zero, in: view)
}


text:
Q: Nested Using statements affects performance      using (var db1 = new DataBase1Entities())
        {
           using (var db2 = new DataBase2Entities())
           {
                var list = (from obj in db2.Table1
                            where !db1.Table2.Any(i => i.Table2Col == obj.Table1Col)
                            select obj).ToList();
           }
        }

does anyone know how to retrieve value from one database table and compare it with another database table ? If the above code is correct, then will it cause performance issue ?

A: You seem not to know what a using-statement does. Effectively it´s nothing but a try-finally-block where within the finally there´s a call to Dispose. So your code is translated to the following:
DataBase1Entities db1 = null;
try
{
    db1 = new DataBase1Entities();
    DataBase1Entities db2 = null;
    try
    {
        db2 = new DataBase2Entities()
        // do something with db2
    }
    finally
    {
        if(db2 != null) db2.Dispose(); }
    }
}
finally
{
    if(db1 != null) db1.Dispose();
}

So it´s not the using that may or may not have an effect on performance, but the Dispose. However you shouldn't bother for that at all, as you have to call Dispose. Doing not so is a really bad idea - in particular if it´s done because of any performance-issues. Dispose will release any unmanaged resources, e.g. file handlers. If you´re not calling it there´s no way to release those resources at all which will probably produce memory-leaks.

A: You could certainly remove the nesting if you wanted to. Something like (untested):
HashSet<YourType> bob;

using (var db1 = new DataBase1Entities())
{
    bob = new HashSet<YourType>(db1.Table2.Select(z => z.Table2Col);
}

using (var db2 = new DataBase2Entities())
{
     var list = (from obj in db2.Table1
                 where !bob.Contains(obj.Table1Col)
                 select obj).ToList();
}

You'd need to profile it to check whether it was any faster. Much of the speed benefit, if any, would likely be due to the use of the HashSet rather than the removal of the nested using.


text:
Q: PayPal Capturing Taxes And Fees on an order I'm trying to figure out how to do payouts to multi-party transactions on PayPal. The multi-party payment system documentation is good, but I can't figure out this one detail.
Lets say you have a 3rd party selling something on your platform. They sell one item for 19.99 USD. When the user goes to checkout there's taxes and fees going into this order
So the seller gets the split of 19.99, and then the taxes and fees go to the first party. Are these taxes and fees considered a purchase_unit under the guidelines of the multi-party payment API?
Im using the paypal docs here: https://developer.paypal.com/api/orders/v2/#orders_create
Right now I have this,
         var item = {
            reference_id: "REFID-"+ (i+1),
            payee: {
                email: email
            },
            amount: {
                currency_code: currency,
                value: (price / 100)
            },
            payment_instruction: {
              disbursement_mode: "INSTANT",
              platform_fees: [{
                amount: {
                    currency_code: currency,
                    value: ((price / 100) * 0.03).toFixed(2),
                }
              }]
            },
        }

        purchase_units.push(item);

        var taxes = {
          reference_id: 'REFID-'+0,
          amount: {
              currency_code: currency,
              value: ((totalPrice * cali_tax) / 100).toFixed(2)
          }
        }

        purchase_units.push(taxes);

I'm trying to figure out if the taxes item along with the actual item is necessary or not. By not having a separate purchase unit I believe I can dodge an extra paypal transaction fee. Any help would be appreciated!

A: If the tax is to be collected by the first party, you can add it as a "breakdown" object within the amount, for display purposes -- and also to the platform_fees, so that it is deducted from what the third party seller receives...
        amount: {
            currency_code: currency,
            value: (price / 100)
            /* add "breakdown" object here with additional tax and pre-tax subtotal */
        },
        payment_instruction: {
          disbursement_mode: "INSTANT",
          platform_fees: [{
            amount: {
                currency_code: currency,
                value: /* This amount should be everything the first party is intended to collect. Fees, and any taxes if applicable. */
            }
          }]
        },
    }


text:
Q: Flutter Stay on same y-axis after s navigating back to the previous scrolled Homescreen Im trying to find a solution to come back to the exact same y-axis when I navigate from one screen back to my Homescreen. I have a list of cards on my Homescreen and when I want to choose the last card, I have to scroll down in order to tap it. But when I'm pressing the back button I always land back on the top position of that Homescreen.
Here's the ListView, which is wrapped inside an AnimatedContainer(I have a DrawerScreen implemented)
ListView(
                        children: [
                          Row(
                            children: [
                              secondcard(
                                "Alphabet",
                                titel[0],
                                items[0],
                                pictures[0],
                                descriptions[0],
                                colours4[0],
                                colours1[0],
                                colours2[0],
                                colours3[0],
                              ),
                              card(
                                "Begrüßungen",
                                titel[1],
                                items[1],
                                pictures[1],
                                descriptions[1],
                                colours1[1],
                                colours2[1],
                                colours3[1],
                                colours4[1],
                              ),
                            ],
                          ),
                          Row(
                            children: [
                              card(
                                "Einkaufen",
                                titel[1],
                                items[2],
                                pictures[2],
                                descriptions[2],
                                colours1[2],
                                colours2[2],
                                colours3[2],
                                colours4[2],
                              ),
                              card(
                                "Farben",
                                titel[1],
                                items[3],
                                pictures[3],
                                descriptions[3],
                                colours1[0],
                                colours2[0],
                                colours3[0],
                                colours4[0],
                              ),
                            ],
                          ),
                          Row(
                            children: [
                              card(
                                "Fragewörter",
                                titel[1],
                                items[4],
                                pictures[4],
                                descriptions[4],
                                colours1[1],
                                colours2[1],
                                colours3[1],
                                colours4[1],
                              ),
                              card(
                                "Konversation",
                                titel[1],
                                items[5],
                                pictures[5],
                                descriptions[5],
                                colours1[2],
                                colours2[2],
                                colours3[2],
                                colours4[2],
                              ),
                            ],
                          ),
                          Row(
                            children: [
                              card(
                                "Lebensmittel",
                                titel[1],
                                items[6],
                                pictures[6],
                                descriptions[6],
                                colours1[0],
                                colours2[0],
                                colours3[0],
                                colours4[0],
                              ),
                              card(
                                "Richtungsangaben",
                                titel[1],
                                items[7],
                                pictures[7],
                                descriptions[7],
                                colours1[1],
                                colours2[1],
                                colours3[1],
                                colours4[1],
                              ),
                            ],
                          ),
                          Row(
                            children: [
                              card(
                                "Tiere",
                                titel[1],
                                items[8],
                                pictures[8],
                                descriptions[8],
                                colours1[2],
                                colours2[2],
                                colours3[2],
                                colours4[2],
                              ),
                              card(
                                "Über mich",
                                titel[1],
                                items[9],
                                pictures[9],
                                descriptions[9],
                                colours1[0],
                                colours2[0],
                                colours3[0],
                                colours4[0],
                              ),
                            ],
                          ),
                          Row(
                            children: [
                              card(
                                "wegweisung",
                                titel[1],
                                items[10],
                                pictures[10],
                                descriptions[10],
                                colours1[1],
                                colours2[1],
                                colours3[1],
                                colours4[1],
                              ),
                              card(
                                "Wochentage",
                                titel[1],
                                items[11],
                                pictures[11],
                                descriptions[11],
                                colours1[2],
                                colours2[2],
                                colours3[2],
                                colours4[2],
                              ),
                            ],
                          ),
                          Row(
                            children: [
                              thirdcard(
                                "Zahlen",
                                titel[1],
                                items[13],
                                pictures[13],
                                descriptions[13],
                                colours1[1],
                                colours2[1],
                                colours3[1],
                                colours4[1],
                              ),
                              card(
                                "Zeitangaben",
                                titel[1],
                                items[12],
                                pictures[12],
                                descriptions[12],
                                colours1[0],
                                colours2[0],
                                colours3[0],
                                colours4[0],
                              ),
                            ],
                          )
                        ],
                      ),

The back button only does a pushNamed navigation, because I haven't found anything that comes close to my desired functionality after trying a few dozen possible solutions.
Sadly none of them worked.


text:
Q: Mongoose Update Doesn't Run Before My Res.Send() I currently have a controller which is handling the onboarding of a user. When the user completes their onboarding flow, I update their status in Mongo from New to Active, then send them to a new page. As a method of security, I also have a middleware function on every authenticated route which checks if the user is logged in, as well as their status. If their status is New, I send them to the onboarding flow (because theoretically they haven't seen the onboarding flow).
As I run through my experience, when I submit the onboarding flow, I get redirected back to the beginning of the flow. I check Mongo and my status is no longer New, so I was confused why this was happening. Eventually I realized when I am sending the user to a new page, the authentication route is checking the user's status before my findOneAndUpdate() has had a chance to complete. So the user gets redirected back to the onboarding flow because the last query didn't finish in time.
Any idea how to fix this? I assume it has something to do with async/await but I'm not sure. Here's my code below, I'm working in Node.JS with an express framework. Also, in my post onboarding I am using a mapbox api to get the lat/long of their zip code, which is why I have the request.get() in the code.
Onboarding Controller
exports.postOnboarding = (req, res, next) => {

var data = req.params.data;
var final = data.split(',');

location = final[4].toString();
url = "https://api.mapbox.com/geocoding/v5/mapbox.places/" + location + ".json";

request.get(url)
.query({access_token: "private_key"})
.end(function(err, result) {

    User.findOneAndUpdate(
        {"credentials.userId": req.session.user.credentials.userId },
        { practiceSettings: {
            businessType: final[2],
            experienceType: final[0],
            fullFee: final[3]
        },
        credentials: {
            userType: "Active",
            active: true,
            userId: req.session.user.credentials.userId,
            provider: "local"
        },
        paySettings: {
            q1: "undeternmined"
        },
        license: final[1],
        zip: final[4],
        latLong: result.body.features[0].center
        }, (err, result) => {
            if (err) {
                console.log(err);
            } else {
                console.log("settings updated");
                res.redirect('/dashboard');
            }
        }
    )

}) };

Dashboard Route
router.get('/dashboard', isAuth, adminController.getDashboard);

isAuth Middleware
const User = require('../models/user');

module.exports = (req, res, next) => {

    if (!req.session.isLoggedIn) {
        return res.redirect('/login');
    } else if (req.session.user.credentials.userType == 'Unverified') {
        return res.redirect('/login?verified=false');
    } else if (req.url == '/onboarding') {
        return next();
    }

    User.findOne({"credentials.userId" : req.session.user.credentials.userId})
    .then(result => {

        res.locals.user = result;
        if (req.session.sidebarStatus == 'closed') {
            res.locals.sidebarStatus = 'closed';
        }

        if (result.credentials.userType == 'New') {
            return res.redirect('/onboarding');
        }

        next();
    })
}

And for reference, below is a snippet of my onboarding.ejs file which calls the post route. This isn't the whole thing, I have a lot of nested Sweet Alert modals, but this is the important part.
Swal.fire({
    text: "Question",
    width: "90%",
    input: "text",
    inputPlaceholder: "92805",
    inputValidator: (value) => {
        if (!value) {
        return 'You must fill in this field.'
        }

        if (value.length != 5) {
            return 'Please use a 5 digit zip-code as your answer.'
        }
    },
    showCancelButton: false,
    confirmButtonText: 'Submit',
    backdrop: '#FFFFFF',
    allowOutsideClick: false
    })
    .then((result5) => {
        res3 = result3.value.replace(",", "");
        final = [result1.value, result2.value, res3, result4.value, result5.value];
        $.ajax({
            url: "/post-onboarding/" + final,
            dataType: 'json',
            type: 'post',
            success: function (data) {
                if ( data.length ) {
                    Swal.fire({
                        title: 'Error!',
                        text: 'Something bad happened',
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                } else {
                    //redirect user
                }
            }
});


text:
Q: Does Firebase synchronise logged events when app is closed? What happens with logged events if there is no internet connection while the app is running and app is never opened after that?
Does Firebase use some kind of JobScheduler (and other alternative for iOS) to synchronised logged events when the the internet connection appears?

A: In the comments on the question, @SergGr and @Frank indicate that on iOS, the event are never uploaded.
On Android, my observations are that the events are logged to a shared system service (not part of the app) which handles the buffering and uploading. Thus, events logged when there is no internet connection are later uploaded by the service, regardless of whether the originating app is still running or not.
This behavior can be observed by enabling analytics logging and viewing the log output in an adb window.  The tag for the system service is FA-SVC.
Some examples of excerpted log output are included below.  I performed these steps for my test:

*

*Turned on Airplane Mode

*Ran app to generate events

*Put app in background, swiped from recent tasks list to kill it

*Disabled Airplane Mode

*Waited for FA-SVC to run and upload events (this might be as long as an hour)

*Examined buffer of the uploaded event data logged by FA-SVC to confirm that app events were included

// uploading seems occur about every hour
03-02 07:40:42.397 V/FA-SVC  ( 1889): Upload scheduled in approximately ms: 3599957
// the service detects connectivity changes
03-02 06:47:16.496 V/FA-SVC  ( 1889): NetworkBroadcastReceiver received action: android.net.conn.CONNECTIVITY_CHANGE
// this log marks the start of upload; followed by logs for each uploaded event
03-02 07:40:41.757 V/FA-SVC  ( 1889): Uploading data. app, uncompressed size, data: com.qbix.xxxx, 3450


text:
Q: Avoiding 301 redirect caching This is a follow up question to Using 301/303/307 redirects for dynamic short urls, where I try to determine the best method for implementing short url redirection when the destination url will change on a frequent basis.
While it seems that 301 and 307 redirects both perform the same way, the issue that concerns me is 301 redirect caching (as documented here)- is the best way to avoid this to use 307 redirects instead (I'm assuming 307 redirects will never cache?), or to explicitly send a no-cache header ("Cache-Control: no-cache, must-revalidate")?

A: Don't try to avoid 301 caching. If you don't want any user agent to cache your redirect, then simply don't use a 301 redirect. In other words, 301 caching is here to stay, and semantically, it's a permanent redirect, so if you're planning to change the destination URL, 301 is not the right status code to use. On the other hand, 307 responses are not cached by default.

A: In situations where you want the behaviour that a 301 redirect brings, like the updating of browser bookmarks and the change of URL in google bot, but at the same time want to track the redirects or perform some other kind of functionality you can always add the cache control headers to "no cache"
HTTP/1.0 301 Moved Permanently
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Expires: Sat, 26 Jul 1997 05:00:00 GMT
Location: http://example.com

In php it looks like this:
header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
header('Location:'.$url, true, 301);

Related:
https://stackoverflow.com/a/19003320/175071


text:
Q: Hang up on HTTP Get/Request I am not sure where/how my program is getting hung up. I am pretty confident it is in the sending or the receiving of the links... but even after searching on the internet for some help and also getting help from my professor, I am still lost, as to why this is not working.
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#define LENGTH 500

int main(int argc, char** argv)
{
  // holds the value of the command-line argument
  char link[LENGTH];
  strcpy (link , argv[1]);
  printf ("%s\n", link);

  // break up link into the host and path -- use the "/"
  char _host[LENGTH];
  char _path[LENGTH];
  int slashCount = 0;
  int i;

  for (i=0 ; i<strlen(link); i++)
  {
    printf ("%c , slashcount: %d\n", link[i], slashCount);
    if (link[i] == '/') slashCount ++;
    if (slashCount > 2)
    {
       // i is at the end of the host
       strncpy (_host , link , i);
       _host[i] = '\0';
       break;
    }

  } // end for

 if (slashCount == 2)
 {
    // given only a host, copy the entire string into the host
   strncpy(_host, link, i);
   _host[i] = '\0';
 }

 else  // get the path for slashCount of 3
 {
   for (i ; strlen(link); i++ )
   {
       strcat (_path, &link[i]);
       // if slash at the end of host name
       if (strlen(_path) == 1)
       {
           // set the file field to be index.html
           char t[11] = {'i','n','d','e','x','.','h','t','m','l','\0'};
           for (int c=0; c< 10 ; c++)
           strncpy(_path, t, 11);
       }
       break;
   }
 } // end if/else

 printf ("%s\n" , _host); /*success*/
 printf ("%s\n" , _path); /*success*/

 struct addrinfo hints;
 struct addrinfo * result, * rp;
 int sock_fd, s;

 hints.ai_socktype = SOCK_STREAM;
 memset(&hints,0,sizeof(struct addrinfo)); // setting the values to 0

 s = getaddrinfo("::1","http", &hints,&result); ///////////////
 if (0 != s)
 {
   perror("error populating address structure");
   exit(1);
 }
 printf ("entering tcp setup connections");

 // check the host name's IP address — has a dynamic configuration(DNS)
 // but does not change very frequently
 for (rp = result; rp != NULL; rp = rp->ai_next)
 {
   sock_fd = socket(rp->ai_family, rp->ai_socktype,
    rp->ai_protocol);
   if (sock_fd == -1)
      continue;

   if (connect(sock_fd, rp->ai_addr, rp->ai_addrlen) != -1)
     break;

   close(sock_fd);
 }

 if (rp == NULL)
 {
   // you didn't find a good ip address to connect with
   fprintf(stderr, "could not connect\n");
   exit(1);
 } // end for

 freeaddrinfo(result);

 // sending the request
 sprintf (link, "GET %s HTTP/1.0\r\n" "Host: %s\r\n\r\n", _path,    _host);
 if (send (sock_fd, link, strlen(link), 0 )< 0)
   fprintf (stderr, "Error with send\n");
 else
   fprintf (stderr, "Successfully send the fetch request\n");

 // responding to the send
 char buf[500];
 memset(&buf,0,sizeof(buf));
  /*  int recv_count = recv(sock_fd, buf, 500, 0);

 if(recv_count<0)
 {
   perror("Receive failed");
   exit(1);
 }

 printf("%s",buf); */
/*  while (0 > recv (sock_fd, buf, 500, 0))
 {
    printf ("%s", buf);
 }
 shutdown(sock_fd,SHUT_RDWR); */
 exit (1);
}

I understand that I have to send a get request, and I commented out the response part and saw that there was a successful entry into the tcp connection setup. I am just confused how the response should be setup. I understand how to use read/write, but I wanted to also try send/recv.
Any help is very appreciated.
The output that I am currently getting:
http://google.com/
h , slashcount: 0
t , slashcount: 0
t , slashcount: 0
p , slashcount: 0
: , slashcount: 0
/ , slashcount: 0
/ , slashcount: 1
g , slashcount: 2
o , slashcount: 2
o , slashcount: 2
g , slashcount: 2
l , slashcount: 2
e , slashcount: 2
. , slashcount: 2
c , slashcount: 2
o , slashcount: 2
m , slashcount: 2
/ , slashcount: 2
http://google.com
index.html
Successfully send the fetch request
entering tcp setup connections

A: The return value of recv() indicates Connection refused, which suggests issues with the setup of the socket.
You need to reverse the order of the two lines:
hints.ai_socktype = SOCK_STREAM;
memset(&hints,0,sizeof(struct addrinfo)); // setting the values to 0

so that you assign the ai_socktype after setting the memory to zeros.
On the getaddrinfo() call pass as first argument the string link received from cli (::1 is an alias for localhost).
s = getaddrinfo(link,"http", &hints,&result); ///////////////

Changing the code results in:
woof@fth ~ % ./test.o google.com
google.com
sock_fd=3
socket opened
Successfully sent the fetch request
HTTP/1.0 404 Not Found
Content-Type: text/html; charset=UTF-8
X-Content-Type-Options: nosniff
Date: Sun, 25 Jan 2015 11:07:09 GMT
Server: sffe
Content-Length: 1425
X-XSS-Protection: 1; mode=block
Alternate-Protocol: 80:quic,p=0.02

<!DOCTYPE html>
<html lang=en>
  <meta charset=utf-8>
  <meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width">
  <title>Error 404 (Not Found)!!1</title>
  <style>
    *{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}%

which means the server responded.
The file was not found because in the line
sprintf (link, "GET %s HTTP/1.0\r\n" "Host: %s\r\n\r\n", _path,    _host);

you request a non-existing path; if you try with
sprintf (link, "GET / HTTP/1.0\n\n");

you should see something different (probably another error). If you want to get a different path you need to insert it properly inside the request (work on identifying it from the input string).

The code I compiled is almost the same as yours:
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#define LENGTH 500

int main(int argc, char** argv) {
    // holds the value of the command-line argument
    char link[LENGTH];
    strcpy (link , argv[1]);
    printf ("%s\n", link);

    // break up link into the host and path -- use the "/"
    char _host[LENGTH];
    char _path[LENGTH];
    int slashCount = 0;
    int i,c;

    for (i=0 ; i<strlen(link); i++) {

        if (link[i] == '/')
            slashCount ++;

        if (slashCount > 2) {
            // i is at the end of the host
            strncpy (_host , link , i);
            _host[i] = '\0';
            break;
        }
    }

    if (slashCount == 2) {
        // given only a host, copy the entire string into the host
        strncpy(_host, link, i);
        _host[i] = '\0';
    }
    else {
        // get the path for slashCount of 3
        for (i ; strlen(link); i++ ) {
            strcat (_path, &link[i]);
            // if slash at the end of host name
            if (strlen(_path) == 1)
            {
                // set the file field to be index.html
                char t[11] = {'i','n','d','e','x','.','h','t','m','l','\0'};
                strncpy(_path, t, 11);
            }
            break;
        }
    } // end if/else

    struct addrinfo hints;
    struct addrinfo *result, *rp;
    int sock_fd, s;

    memset(&hints,0,sizeof(struct addrinfo)); // setting the values to 0
    hints.ai_socktype = SOCK_STREAM; // tcp socket

    // create addrinfo structure with parameters to initialize a socket
    s = getaddrinfo("::1","8080", &hints,&result); ///////////////

    if( s!=0 ) {
        perror("error populating address structure");
        exit(1);
    }

    char temp[5000];

    // check the host name's IP address — has a dynamic configuration(DNS)
    // but does not change very frequently
    for( rp=result; rp!=NULL; rp=rp->ai_next ) {
        sock_fd = socket(rp->ai_family, rp->ai_socktype,rp->ai_protocol);
        fprintf(stderr,"sock_fd=%d\n",sock_fd);

        if (sock_fd == -1)
            continue;

        // exit loop on success
        if( connect(sock_fd, rp->ai_addr, rp->ai_addrlen)==0 )
            break;
        else
            close(sock_fd);
    }

    if( rp==NULL ) {
        // you didn't find a good ip address to connect with
        fprintf(stderr, "could not connect\n");
        exit(1);
    }
    else
        printf("socket opened\n");

    freeaddrinfo(result);

    // formatting the request string
    sprintf (link, "GET %s HTTP/1.0\r\n" "Host: %s\r\n\r\n", _path,    _host);
    // sending the request
    if( send(sock_fd, link, strlen(link), 0)<0 )
        fprintf(stderr, "Error with send\n");
    else
        fprintf (stderr, "Successfully sent the fetch request\n");

    // response buffer
    char buf[500];
    memset(&buf,0,sizeof(buf));

    int recv_count = recv(sock_fd, buf, 500, 0);

    if( recv_count<0 ){
       perror("Receive failed");
       exit(1);
    }

    printf("%s",buf);
/*  while (0 > recv (sock_fd, buf, 500, 0))
 {
    printf ("%s", buf);
 }
 shutdown(sock_fd,SHUT_RDWR); */
    exit (0);
}

Changed the function call and restored the sprintf formatting the GET request. You should launch on a separate terminal the command
echo "Here is a message" | nc -l -6 8080

which suspends execution until you receive a request on the port (flag -l, see the netcat manual for more on this).
The request is printed on the netcat terminal and the process terminates, while on the terminal where you launched the compiled code you should see the message echoed and piped inside netcat.


text:
Q: Binding Converter how to pass a parameter to function In my window.xaml I have the following code:
 xmlns:converters="clr-namespace:HMIPlc.Helpers"

 <Window.Resources>
    <ResourceDictionary>
        <converters:ColorConverter x:Key="ColorOnChange"/>
    </ResourceDictionary>
</Window.Resources>

<Rectangle Fill="{Binding Path=varUnit.InSimulation, Converter={StaticResource ColorOnChange}}"/>

I want to give also a value in a string "Yellow" or "Orange" to the function, so I can use the same function for different rectangles with different colors.
My ColorConverter.cs class inside the Helpers directory:
public class ColorConverter : IValueConverter
{
    public ColorConverter()
    {
    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        bool tempBool = (bool)value;
        if(tempBool == true)
        {
            return new SolidColorBrush(Colors.Orange);
        } else
        {
            return new SolidColorBrush(Colors.White);
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

So that I can determine in my XAML if the color has to be orange or yellow. Is there any good method to do this?

A: When you want to provide additional values to a converter, you can either:
a) Add additional properties on the converter which can then be assigned in XAML:
public class ColorConverter : IValueConverter
{
    public Color BackupColor { get; set; }

    public ColorConverter()
    {

    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        bool tempBool = (bool)value;
        if(tempBool == true)
        {
            return new SolidColorBrush(Colors.Orange);
        } else
        {
            return new SolidColorBrush(Colors.White);
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

...
<converters:ColorConverter x:Key="ColorOnChange" BackupColor="Yellow"/>
...

b) Leverage the ConverterParameter which is usually a string literal:
<Rectangle Fill="{Binding Path=varUnit.InSimulation, Converter={StaticResource ColorOnChange}, CommandParameter='Yellow'}"/>

A: If you want to bind multiple values, use a MultiValueConverter. I use the more general type Brush here, so you are not limited to binding a SolidColorBrush.
public class ColorConverter : IMultiValueConverter
{
   public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
   {
      if (values.Length != 3 ||
          !(values[0] is bool value) ||
          !(values[1] is Brush brushTrue) ||
          !(values[2] is Brush brushFalse))
         return Binding.DoNothing;

      return value ? brushTrue : brushFalse;
   }

   public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
   {
      throw new NotImplementedException();
   }
}

Then use a MultiBinding and specify the property to be bound, as well as the brushes. In order to reference a built-in brush, you can use the static Brushes type with x:Static.
<Rectangle>
   <Rectangle.Fill>
      <MultiBinding Converter="{StaticResource ColorOnChange}">
         <Binding Path="varUnit.InSimulation"/>
         <Binding Source="{x:Static Brushes.Orange}"/>
         <Binding Source="{x:Static Brushes.White}"/>
      </MultiBinding>
   </Rectangle.Fill>
</Rectangle>

A: You could set the CommandParameter property to a Brush or Color and cast the "parameter" argument in your converter:
public class ColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        Color color = (Color)parameter;
        bool tempBool = (bool)value;
        if (tempBool == true)
        {
            return new SolidColorBrush(color);
        }
        else
        {
            return new SolidColorBrush(color);
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

XAML:
<Rectangle Fill="{Binding Path=varUnit.InSimulation, Converter={StaticResource ColorOnChange},
        ConverterParameter={x:Static Colors.Orange}}"/>


text:
Q: If $x$ is a positive rational but not an integer, is $x^x$ irrational?
Let $x$ be positive, rational, but not an integer. That means $x$ can be written as $\frac{p}{q}$ with $p,q$ coprime, $p,q \neq 0$ and $q \neq 1$. Is $x^x$ always irrational?

I think that this has to be the case, but I can't prove it.
$x^x = (\frac{p}{q})^\frac{p}{q} = \frac{p^\frac{p}{q}}{q^\frac{p}{q}}$
I know that $p^\frac{p}{q}$ and $q^\frac{p}{q}$ can't both be rational, but there are cases where the division of two irrational numbers gives us an rational number. For example $\frac{\sqrt{2}}{\sqrt{2}} = 1$

A: You have $y=x^x=\left(\cfrac pq\right)^{\frac pq}=\left(\cfrac {p^p}{q^p}\right)^{\frac 1q}$ so that $$y^q=\frac {p^p}{q^p}$$
Hence the rational fraction $y$ is a $p^{th}$ power - say $y=z^p$
Then $z^q=\frac pq$, and $\frac pq$ is a $q^{th}$ power. Now $q$ is an integer which is a $q^{th}$ power of an integer. But for $q\gt 1$ we have $2^q\gt q$.


text:
Q: ¿Como puedo añadir un intent en un fragment.class? Tengo un problema en un fragment.class y es que no puedo añadir intents ya que me dan errores y si los pongo en MainActivity no me da errores.
para que tenga una idea, intent que quiero añadir es este:
public void open2 (View view){

    Intent open2 = getPackageManager().getLaunchIntentForPackage("com.google.android.googlequicksearchbox");
    startActivity(open2);
}

y me da error en getPackageManager.

A: Intent open2 = new Intent(getActivity().getPackageManager().getLaunchIntentForPackage("com.google.android.googlequicksearchbox"));
open2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(open2);

A: Si deseas realizar un Intent dentro de un Fragment es necesario tener un contexto, si te encuentras dentro dentro de un Fragment el contexto lo puedes obtener de la activity que contiene el Fragment usando getActivity():
public void open2 (View view){

    Intent open2 = getActivity().getPackageManager().getLaunchIntentForPackage("com.google.android.googlequicksearchbox");
    startActivity(open2);
}


text:
Q: differentiate between two input boxes max and min value

    Min Stock Level

        <input type="text" name="minStock" min="0" ng-model="item.MinStockLevel" ng-pattern="/^[0-9]+(\.[0-9]{1,6})?$/" required />

            Price is Required
            Not Valid

this is first text box where enter min value.

     Max Stock Level

         <input type="text" name="maxStock" ng-     model="item.MaxStockLevel" min=" {{ item.MinStockLevel + 1 }}" ng-pattern="/^[0-9]+(\.[0-9]{1,6})?$/" required />

              Price is Required
               Not Valid

it is second input box. i want to differentiate between two boxes min stock level and max stock level values.  where user can enter max value greater then min value and min value less than max value. how can i validate it?

A: Seems like the issue was with input type="text", which should've been input type="number", since min and max apply to numbers, and not text.


text:
Q: Django SItemap Index NoReverseMatch at /sitemap.xml I'm trying to implement Sitemap Index but I'm getting the below error on sitemap.xml. sitemap-posts.xml and sitemap-categories.xml works fine.
Error
NoReverseMatch at /sitemap.xml

Reverse for 'django.contrib.sitemaps.views.sitemap' with arguments '()' and keyword arguments '{'section': 'categories'}' not found. 0 pattern(s) tried: []

sitemap.py
from django.contrib.sitemaps import Sitemap

from .models import Post, Category

class PostSitemap(Sitemap):
    changefreq = 'daily'
    priority = 0.5

    def items(self):
        return Post.objects.published()

    def lastmod(self, obj):
        return obj.mod_date

class CategorySitemap(Sitemap):
    changefreq = 'daily'
    priority = 0.5

    def items(self):
        return Category.objects.all()

    def lastmod(self, obj):
        return obj.created_date

urls.py
from django.conf.urls import url
from django.contrib.sitemaps import views as sitemap

from . import views
from .sitemaps import PostSitemap, CategorySitemap

sitemaps = {
    'posts': PostSitemap,
    'categories': CategorySitemap,
}

urlpatterns = [
    url(r'^sitemap\.xml$', sitemap.index, { 'sitemaps': sitemaps },
        name='app1-sitemap'),
    url(r'^sitemap-(?P<section>.+)\.xml$', sitemap.sitemap, { 'sitemaps': sitemaps },
        name='django.contrib.sitemaps.views.sitemap1'),
]

Please help me to fix this error.

A: Change name from 'django.contrib.sitemaps.views.sitemap1' to 'sitemaps'. Apparently it uses that name for resolution.
name='django.contrib.sitemaps.views.sitemap1'

My urls look exactly like this and it works right, when I changed the name, I got an error close to yours.
from django.contrib.sitemaps.views import sitemap, index
    urlpatterns += [
            url(r'^sitemap\.xml$', cache_page(86400)(index), {'sitemaps': sitemaps, 'sitemap_url_name': 'sitemaps'}),
            url(r'^sitemap-(?P<section>.+)\.xml$', cache_page(86400)(sitemap), {'sitemaps': sitemaps}, name='sitemaps' )
        ]

sitemap_url_name required because I'm caching.

A: I found the name of second URL conf. should be
name='django.contrib.sitemaps.views.sitemap'

which refers to the official doc
https://docs.djangoproject.com/en/1.11/ref/contrib/sitemaps/#creating-a-sitemap-index
instead of what you use
name='django.contrib.sitemaps.views.sitemap1'

and it works on my computer.


text:
Q: Generate report from a table I have a table like:
+====+========+========+
| Id |   name |  value |
+====+========+========+
|  1 |   a    |      7 |
+----+--------+--------+
|  2 |   c    |      7 |
+----+--------+--------+
|  1 |   g    |      1 |
+----+--------+--------+
|  2 |   c    |      2 |
+----+--------+--------+
|  4 |   g    |      5 |
+----+--------+--------+
|  6 |   t    |      4 |
+----+--------+--------+

I need to write two (2) queries to generate two reports, according to this two conditions:

Report Output1=if id  and name same (id,name,val)
  Report Output2=if id same but different name(id,name,val)

How to write those two queries?

A: Your conditions is not clear, but mybe this what you want:
DECLARE @T TABLE (Id INT, Name VARCHAR(25), Value INT);
DECLARE @YourId INT = 1;
DECLARE @YourName VARCHAR(25) ='a';
/**/
INSERT INTO @T VALUES
(1, 'a', 7),
(2, 'c', 7),
(1, 'g', 1),
(2, 'c', 2),
(4, 'g', 5),
(6, 't', 4);
/*First query*/
SELECT *
FROM @T
WHERE ID = @YourID AND Name = @YourName;
/*Second query*/
SELECT *
FROM @T
WHERE ID = @YourID;

If you want the result of both queries in one result, then you can use UNION ALL as:
SELECT *
FROM @T
WHERE ID = @YourID AND Name = @YourName

UNION ALL

SELECT *
FROM @T
WHERE ID = @YourID;

Demo.

A: Well, I am not sure, what OP wanted, but maybe it was something like this?
// records where id and value are the same
SELECT * FROM @T WHERE ID=Value;

// other records having the same ids as abobe, but DIFFERENT values
SELECT * FROM @T WHERE ID IN
 (SELECT ID FROM @T WHERE ID=Value)
  AND Id!=Value;

Results:
    Id  Name    Value
     1  g       1
     2  c       2

    Id  Name    Value
     1  a       7
     2  c       7

Thanks to @Sami for providing the fiddle which I modified into this DEMO.


text:
Q: The method 'Union' is not supported. Declaring type: System.Linq.Queryable (C#) I have two IQueryables that i need to merge. This is my code:
IQueryable<SearchResultsItem> resourceQueriable = GetIndexQueriable(ResourceIndexName);
IQueryable<SearchResultsItem> resourceQueriableResults = resourceQueriable.Where(x => x.DatabaseName == Database);

IQueryable<SearchResultsItem> resourcePageQueriable = GetIndexQueriable(ResourcePageIndexName);
IQueryable<SearchResultsItem> resourcePageQueriableResults =
    resourcePageQueriable.Where(x => x.DatabaseName == Database);

string ResourceTypeGuid = ItemReference.ItemReference.BBB_ResourceTypes_ProductGuide.InnerItem.ID.ToString().ConvertToShortId();

resourceQueriableResults = resourceQueriableResults.Where(x => x.ResourceType == ResourceTypeGuid);
resourcePageQueriableResults = resourcePageQueriableResults.Where(x => Boolean.Parse(x.IncludeInGuides));

IQueryable<SearchResultsItem> concatResults = resourceQueriableResults.Union(resourcePageQueriableResults);

IEnumerable<KeyValuePair<string, string>> namePathPairs =
    concatResults
        .Where(x => x.DatabaseName == Database)
        .OrderBy(y => y.NavTitle)
        .ToList() //Enumerate the query before translating it.
        .Select(x => new KeyValuePair<string, string>(x.NavTitle.CleanNavTitle(), x.Url));

return namePathPairs;

The error is thrown on IEnumerable<KeyValuePair<string, string>> namePathPairs = concatResults....
Why is it throwing this error, and how can I merge my two IQueryables? I previously only had one IQueryable, and this worked fine
IEnumerable<KeyValuePair<string, string>> namePathPairs =
            resourceQueriable
                .Where(x => x.DatabaseName == Database)
                .OrderBy(y => y.NavTitle)
                .ToList() //Enumerate the query before translating it.
                .Select(x => new KeyValuePair<string, string>(x.NavTitle.CleanNavTitle(), x.Url));

But now that I'm using the merged IQueryable on that line, it's not working.


text:
Q: Scroll event firing too many times. I only want it to fire a maximum of, say, once per second I have a page with "infinite scroll". It calculates the difference between the end of the page and the current page and loads more content if this difference is small enough. The code is soemthing like this using jQuery:
$(window).on('scroll', function() {
    if (window.pageYOffset > loadMoreButton.offsetTop - 1000)
        # load more content via ajax
}

Now, the problem is that every time I scroll, this event fires multiple times per scroll. I would like fire at most every x milliseconds. How would I do this?

A: var now = new Date().getTime();
$(window).scroll( function () {
    if (window.pageYOffset > loadMoreButton.offsetTop - 1000)
    {
        if (new Date().getTime() - now > 1000)
        {
            console.log("Task executed once per second");
            now = new Date().getTime();
        }
    }
});

Or
You can use Throttling fonction calls:
throttling-function-calls
function throttle(fn, threshhold, scope) {
  threshhold || (threshhold = 250);
  var last,
      deferTimer;
  return function () {
    var context = scope || this;

    var now = +new Date,
        args = arguments;
    if (last && now < last + threshhold) {
      // hold on to it
      clearTimeout(deferTimer);
      deferTimer = setTimeout(function () {
        last = now;
        fn.apply(context, args);
      }, threshhold);
    } else {
      last = now;
      fn.apply(context, args);
    }
  };
}

You can call it like this:
$('body').on('mousemove', throttle(function (event) {
  console.log('tick');
}, 1000));

A: Here is a solution that doesn't require the use of an extra JS library or plugin, that aims for simplicity. It might not be as efficient as other implementations but it is definitely a step up from firing your main event every time you scroll.
This was taken from this blog post by Danny Van Kooten. Which I have used in delaying my onscroll() events for my back-to-top button on my blog.
var timer;
$(window).scroll(function() {
    if(timer) {
        window.clearTimeout(timer);
    }
    timer = window.setTimeout(function() {
       // actual code here. Your call back function.
    console.log( "Firing!" );
    }, 100);
});

You can also further improve performance by moving out variables out of the callback function to avoid unnecessary recalculations, for example the value of $(window).height() or height of some static div element that won't change once the page is loaded.
Here's an example that is adapted from my use case.
var scrollHeight = $("#main-element").height(); //never changes, no need to recalculate.
$(window).on('scroll', function() {
    if (timer)
        window.clearTimeout(timer);
    timer = window.setTimeout(function() {
        var scrollPosition = $(window).height() + $(window).scrollTop();
        if ($(window).scrollTop() < 500)
            $(".toggle").fadeIn(800);
        else
            $(".toggle").fadeOut(800);
    }, 150); //only fire every 150 ms.
});

This limits the actual function  to only execute every 150ms, or else reset the timer back to 0 if 150ms has not passed. Tweak the value to suit what you need.

A: Check out the Underscore.js library's "throttle" method.
http://underscorejs.org/#throttle
The example it gives is exactly what you're asking about - limiting how often you have to handle scroll events.

A: One way to solve this problem is to define a time interval and only process a scroll event once within that time interval.  If more than one scroll event comes in during that time interval, you ignore it and process it only when that time interval has passed.
var scrollTimer, lastScrollFireTime = 0;

$(window).on('scroll', function() {

    var minScrollTime = 100;
    var now = new Date().getTime();

    function processScroll() {
        console.log(new Date().getTime().toString());
    }

    if (!scrollTimer) {
        if (now - lastScrollFireTime > (3 * minScrollTime)) {
            processScroll();   // fire immediately on first scroll
            lastScrollFireTime = now;
        }
        scrollTimer = setTimeout(function() {
            scrollTimer = null;
            lastScrollFireTime = new Date().getTime();
            processScroll();
        }, minScrollTime);
    }
});

This will fire the first scroll event immediately and then get you a scroll event approximately once every 100ms while the scrollbar is being moved and then one final event after the scrollbar stops moving.  You can adjust the frequency of the event by changing the argument to the setTimeout (what is currently set to 100).
There is a demo here: http://jsfiddle.net/jfriend00/EBEqZ/ which you need to open a debug console window, start moving the scrollbar in the content window and then watch the time of each scroll event in the debug console window.  On my version of Chrome, they are set for a minimum spacing of 100ms and they seem to occur every 100-200ms.

A: There is a cool explanation from John Resig, the creator of jQuery to resolve this situation.
var outerPane = $details.find(".details-pane-outer"),
    didScroll = false;

$(window).scroll(function() {
    didScroll = true;
});

setInterval(function() {
    if ( didScroll ) {
        didScroll = false;
        // Check your page position and then
        // Load in more results
    }
}, 250);

The source:
http://ejohn.org/blog/learning-from-twitter/

A: var isWorking = 0;

$(window).on('scroll', function()
{
    if(isWorking==0)
    {
         isWorking=1;
         if (window.pageYOffset > loadMoreButton.offsetTop - 1000)
         # load more content via ajax
         setTimeout(function(){isWorking=0},1000);
    }
}

A: the scroll fire multiple times is correct and you should able to get the scroll position differently each time. I think you need to set a timer when you first get in the scroll event like you mentioned x milliseconds, and also record the time stamp, and then next time scroll event fire, check the last trigger time and ignore it if it's within x milliseconds, and do the real job in your Timer action.

A: One does not need a ton of local variables for a decent throttle function. The purpose of a throttle function is to reduce browser resources, not to apply so much overhead that you are using even more. As proof of evidence of this claim, I have devised a throttle function that has only 5 'hanging' variables referenes in its scope. Additionally, my different uses for throttle functions require many different circumstances for them. Here is my list of things that I believe 'good' throttle function needs.

*

*Immediately calls the function if it has been more than interval MS since the last call.

*Avoids executing function for another interval MS.

*Delays excessive event firing instead of dropping the event altogether.

*Updates the delayed event object on successive calls so that it doesn't become 'stale'.

And, I believe that the following throttle function satisfies all of those.
function throttle(func, alternateFunc, minimumInterval) {
    var executeImmediately = true, freshEvt = null;
    return function(Evt) {
        if (executeImmediately) { // Execute immediatly
            executeImmediately = false;
            setTimeout(function(f){ // handle further calls
                executeImmediately = true;
                if (freshEvt !== null) func( freshEvt );
                freshEvt = null;
            }, minimumInterval);
            return func( Evt );
        } else { // Delayed execute
            freshEvt = Evt;
            if (typeof alternateFunc === "function") alternateFunc( Evt );
        }
    };
}

Then, to wrap this throttle function around DOM event listeners:
var ltCache = [];
function listen(obj, evt, func, _opts){
    var i = 0, Len = ltCache.length, lF = null, options = _opts || {};
    a: {
        for (; i < Len; i += 4)
            if (ltCache[i] === func &&
              ltCache[i+1] === (options.alternate||null) &&
              ltCache[i+2] === (options.interval||200)
            ) break a;
        lF = throttle(func, options.alternate||null, options.interval||200);
        ltCache.push(func, options.alternate||null, options.interval||200, lF);
    }
    obj.addEventListener(evt, lF || ltCache[i+3], _opts);
};
function mute(obj, evt, func, options){
    for (var i = 0, Len = ltCache.length; i < Len; i += 4)
        if (ltCache[i] === func &&
          ltCache[i+1] === (options.alternate||null) &&
          ltCache[i+2] === (options.interval||200)
        ) return obj.removeEventListener(evt, ltCache[i+3], options);
}

Example usage:

function throttle(func, alternateFunc, minimumInterval) {
    var executeImmediately = true, freshEvt = null;
    function handleFurtherCalls(f){
        executeImmediately = true;
        if (freshEvt !== null) func( freshEvt );
        freshEvt = null;
    };
    return function(Evt) {
        if (executeImmediately) { // Execute immediatly
            executeImmediately = false;
            setTimeout(handleFurtherCalls, minimumInterval);
            return func( Evt );
        } else { // Delayed execute
            freshEvt = Evt;
            if (typeof alternateFunc === "function") alternateFunc( Evt );
        }
    };
}
var ltCache = [];
function listen(obj, evt, func, _opts){
    var i = 0, Len = ltCache.length, lF = null, options = _opts || {};
    a: {
        for (; i < Len; i += 4)
            if (ltCache[i] === func &&
              ltCache[i+1] === (options.alternate||null) &&
              ltCache[i+2] === (options.interval||200)
            ) break a;
        lF = throttle(func, options.alternate||null, options.interval||200);
        ltCache.push(func, options.alternate||null, options.interval||200, lF);
    }
    obj.addEventListener(evt, lF || ltCache[i+3], _opts);
};
function mute(obj, evt, func, options){
    for (var i = 0, Len = ltCache.length; i < Len; i += 4)
        if (ltCache[i] === func &&
          ltCache[i+1] === (options.alternate||null) &&
          ltCache[i+2] === (options.interval||200)
        ) return obj.removeEventListener(evt, ltCache[i+3], options);
}
var numScrolls = 0, counter = document.getElementById("count");
listen(window, 'scroll', function whenbodyscrolls(){
    var scroll = -document.documentElement.getBoundingClientRect().top;
    counter.textContent = numScrolls++;
    if (scroll > 900) {
      console.log('Body scrolling stoped!');
      mute(window, 'scroll', whenbodyscrolls, true);
    }
}, true);

\/ Scroll Down The Page \/

# Throttled Scrolls: 0

By default, this throttles the function to at most one call every 200ms. To change the interval to a different number of milliseconds, then pass a key named "interval" in the options argument and set it to the desired milliseconds.


text:
Q: Why is $\log_n(2)\cdot\log_n(4)\cdots\log_n(2n-2)\leqslant 1$?
Prove that $\log_n(2)\cdot\log_n(4)\cdots\log_n(2n-2)\leqslant 1$.

I thought I might attack it by induction:
\begin{align*}
        \prod_{k=1}^{n}\log_{n+1}2k &= \bigg(\prod_{k=1}^{n-1}\log_{n}2k\bigg)\big(\log_{n+1}(2n-2)\big)\big(\log_{n+1} n\big)^{n-1}\\[5pt]
        &\leqslant \big(\log_{n+1}(2n-2)\big)\big(\log_{n+1} n\big)^{n-1} \qquad \text{(by IH)},
    \end{align*}
and got stuck, since it's not obvious why this should be at most 1.
My intuition is that $\log_{n+1}(2n-2)$ is slightly above 1, but $\log_{n+1} n$ is slightly below 1, so repeatedly multiplying the former by the latter $n-1$ times should be enough to make everything at most 1.
But I can't seem to get the proof to work. I appreciate any help with this.

A: We prove $$\sqrt{\log_n(2k)\cdot\log_n(2n-2k)}\leq 1, \qquad 1\leq k\leq n-1.$$
Indeed, by AM-GM, we have
\begin{align*}
\sqrt{\log_n(2k)\cdot\log_n(2n-2k)}&\leq\frac{\log_n(2k)+\log_n(2n-2k)}2\\&=\frac{\log_n((2k)(2n-2k))}2\leq\frac{\log_nn^2}{2}=1,
\end{align*}
where we used that $(2k)(2n-2k)\leq\left(\frac{2k+2n-2k}2\right)^2=n^2$, which follows again from AM-GM.
As a result, we have
$$\log_n(2k)\cdot\log_n(2n-2k)\leq 1,\qquad 1\leq k\leq n-1.$$
Hence
\begin{align*}
\left(\log_n(2)\cdot\log_n(4)\cdots\log_n(2n-2)\right)^2&=\prod_{k=1}^{n-1}\left(\log_n(2k)\cdot\log_n(2n-2k)\right)\leqslant 1,
\end{align*}
and therefore
$$\log_n(2)\cdot\log_n(4)\cdots\log_n(2n-2)\leq 1.$$


text:
Q: AndEngine + Box2D on Android- how portable is it? I'm considering using AndEngine for a physics-based game on Android. A number of the examples (especially the ones I'd be basing my code on) depend on the Box2D extension.
I was surprised to learn that this extension relies on native code for its Box2D implementation, rather than using JBox2D.
How does this limit AndEngine's portability? Will it work on all Android devices?

A: It won't run on non-ARM devices, like some currently very rare x86 netbooks that have a ported Android version running on them.

A: Yes, it should work on all android devices, as long as you include it in your reference library when building the apk.


text:
Q: PHP Fatal error: Uncaught Error: [] operator not supported for strings I realise that this question has been asked a number of times but I am yet to find a solution to this problem.
I am using pChart (pData v2.1.4). It works fine on the hosting site which is running php v5.6.30 but I getting a fatal error with the same code on XAMMP which is running php v7.2.5.
The error refers to this line in pData: (NOTE: pData is a class written by a third party and so not my code)
function convertToArray($Value)
    { $Values = ""; $Values[] = $Value; return($Values); }

Any suggestions as to how to resolve the problem? I have tried declaring $Values as an array earlier in the code but this seemed to cause more errors.
Also, is this php version related and an error that I am going to start getting if my hosting site moves on to a newer version php?

A: You have declared $Values as string:
$Values = "";

Fix replacing with array:
function convertToArray($Value)
{
    $Values = [];
    $Values[] = $Value;
    return $Values;
}

But, in my opinion, there is no reason to use this function.
In your code, just define an array of the same variable with:
$Value = [$Value];

It will do the same as your function.

A: You can't convert string to array ($Values = ""; $Values[] = $Value;), so right variant:
function convertToArray($value) {
    return [$value];
}

A: Values should declared as Array Try this.
function convertToArray($Value){
 $Values = [];
 $Values[] = $Value;
 return $Values;
}

A: Try this,
function convertToArray($Value){
   $Values = array(); // initialize

   if ( isset($Value) ) $Values[] = $Value;

   return($Values);
}

Let me know if it works or not.


text:
Q: What is "table_id" in MySQL binary log events? Is there any description for table_id in MySQL binary log events? Is it a unique value?

A: Found the answer in this post

This value comes from an incrementing global counter in sql/sql_base.cc. It increments every time a table is added to the cache of open tables that is limited in size by the global variable open_table_cache... so if that value is smaller than the number of tables being periodically accessed, you should see it increment more frequently. All of the tables will have a new id on the next generated binlog event after a FLUSH TABLES.


text:
Q: How do I set up navigator using Getx and Auto Route? Problem:
I am having trouble setting up navigation using GetX and AutoRoute.
Code Setup:
According to the GetX documentation, if you want to use GetX navigation you have to replace MaterialApp() with GetMaterialApp(). You also set the routes.
void main() {
  runApp(
    GetMaterialApp(
      initialRoute: '/',
      getPages: [
        GetPage(name: '/', page: () => MyHomePage()),
        GetPage(name: '/second', page: () => Second()),
        GetPage(
          name: '/third',
          page: () => Third(),
          transition: Transition.zoom
        ),
      ],
    )
  );
}

The AutoRoute example uses MaterialApp.router() to set up the routerDelegate and routeInformationParser.
   final _appRouter = AppRouter()
   ...
  Widget build(BuildContext context){
      return MaterialApp.router(
             routerDelegate: _appRouter.delegate(...initialConfig),
             routeInformationParser: _appRouter.defaultRouteParser(),
         ),
  }

Here is how I set up the navigation according to Getx and AutoRoute:
void main() {
 configureDependencies();
 runApp(Portfolio());
}

class Portfolio extends StatelessWidget {
  final _appRouter = AppRouter.Router();
  @override
  Widget build(BuildContext context) {
  return GetMaterialApp.router(
      routerDelegate: _appRouter.delegate(),
      routeInformationParser: _appRouter.defaultRouteParser(),
      builder: (context, extendedNav) => Theme(
          data: ComplexReduxTheme.complexReduxLightTheme,
          child: extendedNav ?? Container(color: Colors.red),
         ),
      );
    }
  }

I am using GetMaterialApp.router which returns a GetMaterialApp. Despite this, I get the error "You are trying to use contextless navigation without a GetMaterialApp or Get.key.". I have tried setting up the navigator key and setting Get.testMode = true but nothing happens(no error) when I try to navigate to another screen.
Desired Result:
I should be able to navigate to the desired screen via Get.toNamed().
Current Result:
I get the following error from GetX when trying to navigate to another screen using Get.toNamed() : "You are trying to use contextless navigation without
a GetMaterialApp or Get.key.
If you are testing your app, you can use:
[Get.testMode = true], or if you are running your app on
a physical device or emulator, you must exchange your [MaterialApp]
for a [GetMaterialApp]."
AutoRoute Version: 2.2.0
Get Version: 4.1.4

A: You don't need external routing plugin, GetX already did that for you, and if you want to navigate, just use Get.toNamed("/some-page") and it will show you the page you wanted. Same goes to nested route.
For Example
GetPage(
  name: '/third',
  page: () => Third(),
  transition: Transition.zoom,
  children: [
    GetPage(
      name: '/child-of-third',
      page: () => ChildOfThird(),
    ),
   ],
),

// You access it like this
Get.toNamed("/third");

// And this one, for the nested page
Get.toNamed("/third/child-of-third");

The reason you got the error is when you use external routing plugin in GetX, it will generate their own code, with their own context in their own ecosystem. GetX doesn't know which context does the plugin use since it was outside of its lifecycle.

A: I was facing the same issue when combining both getx and auto router in my case i needed nested navigation as well I created a work around like this
I created initial bindings and passed appRouter to it and saved it in getx routing controller that i was using to a method like Get.toNamed because with initial appRouter you don't need context you can navigate like this
// main app widget
class _myAppState extends State<MyApp> {

    final _appRouter = AppRouter();
    @override
    Widget build(BuildContext context) {
       return GetMaterialApp.router(
          routerDelegate: _appRouter.delegate(),
          routeInformationParser: _appRouter.defaultRouteParser(),
          initialBinding: InitialBinding(router: _appRouter,),
       );
    }
}

// initial binding to store to store app router
class InitialBinding extends Bindings {
    AppRouter router;
    InitialBinding({required this.router,});
    @override
    void dependencies() {
       Get.put(NavRoutesController(router: router,),permanent: true);
    }
}

// router controller

class NavRoutesController extends GetxController {
   AppRouter router;
   NavRoutesController({required this.router,});

   void toNamed(String route){
      router.pushNamed(route);
   }

}

//to navigate use

final router = Get.find<RouterController>();
router.toNamed("/some")
//or

Get.find<RouterController>().toNamed("/some")
// you can get base context as well from AppRouter like this
Get.find<RouterController>().router.navigatorKey.currentState.context


text:
Q: Android - Duplicate class found in modules protobuf-java-3.8.0.jar and protobuf-lite-3.0.1.jar I'm using Google speech github android project. After upgrading all the files versions finally it managed to get down to a single issue now and I could not solve it.
Here error the message:
Duplicate class com.google.protobuf.AbstractMessageLite found in modules protobuf-java-3.8.0.jar (com.google.protobuf:protobuf-java:3.8.0) and protobuf-lite-3.0.1.jar (com.google.protobuf:protobuf-lite:3.0.1)

Theres hundreds more lines with similar warning.
To solve this I tried many other versions of "io.grpc:grpc-protobuf-lite:1.21.0" and "com.google.protobuf:protobuf-java:3.8.0" by changing their numbers but nothing matched those methods and I keep getting that error message.
The strange fact is: upgrading "io.grpc:grpc-protobuf-lite: ---" of 3.0.1 gives this error: ERROR: Failed to resolve: io.grpc:grpc-protobuf-lite:3.0.1
Show in Project Structure dialog
Affected Modules: app
 but keeping it to the version of 1.21.0 doesn't give any error but will show that duplicate error message that clearly has the version of 3.0.1 that is supposed to be not present.
Heres the dependencies list in my gradle:
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])

// Support libraries
implementation "com.android.support:design:$supportLibraryVersion"
implementation "com.android.support:cardview-v7:$supportLibraryVersion"
implementation "com.android.support:recyclerview-v7:$supportLibraryVersion"

// gRPC
implementation "io.grpc:grpc-okhttp:$grpcVersion"
implementation "io.grpc:grpc-stub:$grpcVersion"
implementation "io.grpc:grpc-protobuf-lite:3.0.1"

implementation 'javax.annotation:javax.annotation-api:1.2'
implementation 'com.google.protobuf:protobuf-java:3.8.0'

// OAuth2 for Google API
implementation('com.google.auth:google-auth-library-oauth2-http:0.16.0') {
    exclude module: 'httpclient'
}

// Tests
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'}

How can I solve this duplication error message?

A: Sometimes deleting the duplicated R.java and BuildConfig files may resolve the issue but if it doesn't help me because it was always recreating it and showing the above error.
I had the same issue What helped me is understanding why the files were duplicated at the first places. But I realise it was because I mistakenly made a loop dependency between my modules in the project.
By doing this when compiler started creating class for one of the modules it already compiled as a dependency it showed the error.
So Removing the unneeded dependency and recompiling the project fixed the problem.


text:
Q: Windows Application Form : How to set the zoom level of the webBrowser? I was looking for a way to set the zoom level of my Windows Form Application in which I have navigate some urls. So I open the urls using:

webBrowser1.Navigate("url")

and I want to set the zoom level of the webBrowser1 that depends on the url I have chosen. I have seen the below link but none of them have worked :
https://social.msdn.microsoft.com/Forums/en-US/69f57099-428a-4b17-9b8e-c05ec269c480/zoom-inout-while-designing-forms-in-windows-forms-designer?forum=winformsdesigner&fbclid=IwAR3aZdGsVf4lE5Lw9E3x7grp1dYoWZIUHmhVzJmU8S2BzzwnzaV20Hv5HoE
https://weblog.west-wind.com/posts/2016/Aug/22/Detecting-and-Setting-Zoom-Level-in-the-WPF-WebBrowser-Control
Problems having content in webbrowser scale automatically in Windows Form Application

A: Please try this
webBrowser1.Document.Body.Style = "zoom:50%";


text:
Q: How to route SP3423? maybe is a very simply question but I would like to know how I should route this component. This component is a ESD Protection for USB, and I should route as symetrical as I could, but with this pinout and footprint, How I should to route? Put the traces under NC's pins?
Thank you so much!

A: If you open the datasheet from where you copy-pasted those two pictures, next to them is the example PCB picture which basically verifies your guess how to wire it.
Yes, route the traces via NC pins.


text:
Q: Using awk with column number in a bash script I'm using a command like this to get some connections from nf_conntrack:
awk '($3 == "tcp") && ($6 != "TIME_WAIT") && ($10 == "dport=1234")' /proc/net/nf_conntrack

How to use this command inside of a bash script and also add a script argument to it?
If I just do:
awk '($3 == "tcp") && ($6 != "TIME_WAIT") && ($10 == "dport=$1")' /proc/net/nf_conntrack

It will suppose all $1,$3,$6,... are script arguments and fail.
How do I separate awk column numbers from the script arguments to use this command properly?

A: It is not necessary, but it is the rule of thumb to explicitly declare variables you want to pass from your env to awk
awk -v myvar="dport=$1" '($3 == "tcp") && ($6 != "TIME_WAIT") && ($10 == myvar)' /proc/net/nf_conntrack


text:
Q: First 2 cookies work, third does not This has got me puzzled, and although it's likely an oversight, I need some fresh eyes please.
session_start();

if( !isset( $_COOKIE['cookie1'] ) ) {

  if( !isset ( $_GET['getvar1'] ) ) {

    $_SESSION['var1'] = 0;

  } else {

      $var1 = (int) $_GET['getvar1'];

      $_SESSION['var1'] = $var1;

      setcookie('cookie1', $var1, ( time() + 604800 ), '/', '.domain.com', false, true );
  }

} else {

    $_SESSION['var1'] = $_COOKIE['cookie1'];

}

First several work [cookie(n)/getvar(n)/var(n)], but then the next doesn't work. I copied the first statement twice, renaming – which was the first place I checked and had checked by another colleague.
I've even checked some of the sites that check where you are on your cookie limits and still nothing.
Thanks.


text:
Q: block calls by area code in twilio laravel I just want to block call by area code like 404, 706 etc please let me know how to block twilio calls by area code. I have done block calls of specific number but i couldn't find the block calls by area code.
If anyone know please let me know.
Thanks.

A: To block outbound call by area code, check that the number you are attempting to dial is not in that area code before calling the Twilio calls resource.


text:
Q: Amazon S3 console: download multiple files at once When I log to my S3 console I am unable to download multiple selected files (the WebUI allows downloads only when one file is selected):
https://console.aws.amazon.com/s3
Is this something that can be changed in the user policy or is it a limitation of Amazon?

A: I believe it is a limitation of the AWS console web interface, having tried (and failed) to do this myself.
Alternatively, perhaps use a 3rd party S3 browser client such as http://s3browser.com/

A: If you have Visual Studio with the AWS Explorer extension installed, you can also browse to  Amazon S3 (step 1), select your bucket (step 2), select al the files you want to download (step 3) and right click to download them all (step 4).

A: Selecting a bunch of files and clicking Actions->Open opened each in a browser tab, and they immediately started to download (6 at a time).

A: If you use AWS CLI, you can use the exclude along with --include and --recursive flags to accomplish this
aws s3 cp s3://path/to/bucket/ . --recursive --exclude "*" --include "things_you_want"

Eg.
--exclude "*" --include "*.txt"

will download all files with .txt extension. More details - https://docs.aws.amazon.com/cli/latest/reference/s3/

A: The S3 service has no meaningful limits on simultaneous downloads (easily several hundred downloads at a time are possible) and there is no policy setting related to this... but the S3 console only allows you to select one file for downloading at a time.
Once the download starts, you can start another and another, as many as your browser will let you attempt simultaneously.

A: In case someone is still looking for an S3 browser and downloader I have just tried Fillezilla Pro (it's a paid version). It worked great.
I created a connection to S3 with Access key and secret key set up via IAM. Connection was instant and downloading of all folders and files was fast.

A: Using AWS CLI, I ran all the downloads in the background using "&" and then waited on all the pids to complete. It was amazingly fast. Apparently the "aws s3 cp" knows to limit the number of concurrent connections because it only ran 100 at a time.
aws --profile $awsProfile s3 cp "$s3path" "$tofile" &
pids[${npids}]=$! ## save the spawned pid
let "npids=npids+1"

followed by
echo "waiting on $npids downloads"
for pid in ${pids[*]}; do
    echo $pid
    wait $pid
done

I downloaded 1500+ files (72,000 bytes) in about a minute

A: It is not possible through the AWS Console web user interface.
But it's a very simple task if you install AWS CLI.
You can check the installation and configuration steps on Installing in the AWS Command Line Interface
After that you go to the command line:
aws s3 cp --recursive s3://<bucket>/<folder> <local_folder>

This will copy all the files from given S3 path to your given local path.

A: I wrote a simple shell script to download NOT JUST all files but also all versions of every file from a specific folder under AWS s3 bucket. Here it is & you may find it useful
# Script generates the version info file for all the
# content under a particular bucket and then parses
# the file to grab the versionId for each of the versions
# and finally generates a fully qualified http url for
# the different versioned files and use that to download
# the content.

s3region="s3.ap-south-1.amazonaws.com"
bucket="your_bucket_name"
# note the location has no forward slash at beginning or at end
location="data/that/you/want/to/download"
# file names were like ABB-quarterly-results.csv, AVANTIFEED--quarterly-results.csv
fileNamePattern="-quarterly-results.csv"

# AWS CLI command to get version info
content="$(aws s3api list-object-versions --bucket $bucket --prefix "$location/")"
#save the file locally, if you want
echo "$content" >> version-info.json
versions=$(echo "$content" | grep -ir VersionId  | awk -F ":" '{gsub(/"/, "", $3);gsub(/,/, "", $3);gsub(/ /, "", $3);print $3 }')
for version in $versions
do
    echo ############### $fileId ###################
    #echo $version
    url="https://$s3region/$bucket/$location/$fileId$fileNamePattern?versionId=$version"
    echo $url
    content="$(curl -s "$url")"
    echo "$content" >> $fileId$fileNamePattern-$version.csv
    echo ############### $i ###################
done

A: Also you could use the --include "filename" many times in a single command with each time including a different filename within the double quotes, e.g.
aws s3 mycommand --include "file1" --include "file2"

It will save your time rather than repeating the command to download one file at a time.

A: Also if you are running Windows(tm), WinSCP now allows drag and drop of a selection of multiple files. Including sub-folders.
Many enterprise workstations will have WinSCP installed for editing files on servers by means of SSH.
I am not affiliated, I simply think this was really worth doing.

A: In my case Aur's didn't work and if you're looking for a quick solution to download all files in a folder just using the browser, you can try entering this snippet in your dev console:
(function() {
    const rows = Array.from(document.querySelectorAll('.fix-width-table tbody tr'));
    const downloadButton = document.querySelector('[data-e2e-id="button-download"]');
    const timeBetweenClicks = 500;

    function downloadFiles(remaining) {
        if (!remaining.length) {
            return
        }

        const row = remaining[0];
        row.click();
        downloadButton.click();

        setTimeout(() => {
            downloadFiles(remaining.slice(1));
        }, timeBetweenClicks)
    }

    downloadFiles(rows)
}())

A: I have done, by creating shell script using aws cli (i.e : example.sh)
#!/bin/bash
aws s3 cp s3://s3-bucket-path/example1.pdf LocalPath/Download/example1.pdf
aws s3 cp s3://s3-bucket-path/example2.pdf LocalPath/Download/example2.pdf

give executable rights to example.sh (i.e sudo chmod 777 example.sh)
then run your shell script ./example.sh

A: I think simplest way to download or upload files is to use aws s3 sync command. You can also use it to sync two s3 buckets in same time.
aws s3 sync <LocalPath> <S3Uri> or <S3Uri> <LocalPath> or <S3Uri> <S3Uri>

# Download file(s)
aws s3 sync s3://<bucket_name>/<file_or_directory_path> .

# Upload file(s)
aws s3 sync . s3://<bucket_name>/<file_or_directory_path>

# Sync two buckets
aws s3 sync s3://<1st_s3_path> s3://<2nd_s3_path>

A: What I usually do is mount the s3 bucket (with s3fs) in a linux machine and zip the files I need into one, then I just download that file from any pc/browser.
# mount bucket in file system
/usr/bin/s3fs s3-bucket -o use_cache=/tmp -o allow_other -o uid=1000 -o mp_umask=002 -o multireq_max=5 /mnt/local-s3-bucket-mount

# zip files into one
cd /mnt/local-s3-bucket-mount
zip all-processed-files.zip *.jpg

A: import os
import boto3
import json

s3 = boto3.resource('s3', aws_access_key_id="AKIAxxxxxxxxxxxxJWB",
                    aws_secret_access_key="LV0+vsaxxxxxxxxxxxxxxxxxxxxxry0/LjxZkN")
my_bucket = s3.Bucket('s3testing')

# download file into current directory
for s3_object in my_bucket.objects.all():
    # Need to split s3_object.key into path and file name, else it will give error file not found.
    path, filename = os.path.split(s3_object.key)
    my_bucket.download_file(s3_object.key, filename)


text:
Q: Replace state of multiple slices using redux toolkit How could you replace the state of a store consisting of multiple slices with some other, new state in react using redux toolkit?
You can revert the whole store to its initial state using extraReducers: could the same mechanism be used to change the store state to something else then the initial state?
For example, you would have something like this:
const aSlice = createSlice({
  name: 'a',
  initialState: {a: 1},
  reducers: {
    someReducer(state, action) {...}
  }
})
const bSlice = createSlice({
  name: 'b',
  initialState: {b: 'foo'},
  reducers: {}
})

const store = configureStore({
  reducer: {
    aReducer: aSlice.reducer,
    bReducer: bSlice.reducer,
  }
});

export type RootState = ReturnType<typeof store.getState>

In a react component you can update the state with:
const dispatch = useDispatch();
dispatch(someReducer({...}));

How would you replace the state of the whole store with something like this:
{
  "aReducer": {"a": 2},
  "bReducer": {"b": "bar"},
}

A: You can use extraReducer for that.
You can pass an arbitrary payload (like {"a": 2, "b": "bar"} to the created action. With createAction you can have actions which don't "belong" to a specific slice, see: https://redux-toolkit.js.org/api/createAction and implement extraReducers in both slices which only use their part of the payload.

A: You can indeed use extraReducers with typesafety, as suggested by dermeck.
A minimal example would be:

import {combineReducers, configureStore, createAction, createSlice, PayloadAction} from "@reduxjs/toolkit";

export const replaceWith = createAction<RootState>('REPLACE_WITH');

const initialState: { a: number } = {
  a: 0
}

export const aSlice = createSlice({
  name: 'a-slice',
  initialState,
  reducers: {
    reduce(state, action: PayloadAction<number>) {
      return {a: action.payload}
    }
  },
  extraReducers: (builder) => {
    builder.addCase(replaceWith, (_, action) => {
      return {
        ...action.payload.aReducer,
      };
    });
  },
});

export const bSlice = createSlice({
  name: 'b-slice',
  initialState: {},
  reducers: {/* TODO */},
  extraReducers: (builder) => {/* TODO */},
});

const rootReducer = combineReducers({
  aReducer: aSlice.reducer,
  bReducer: bSlice.reducer
});

const store = configureStore({
  reducer: rootReducer,
});

export type RootState = ReturnType<typeof rootReducer>;

And finally, in your React component, you can do something like:
const dispatch = useDispatch();
dispatch(replaceWith(newState));

A: Reducers, by definition, only have access to the section of state that they own. So, if I have {users: usersReducer, posts: postsReducer}, the usersReducer has no access to the posts state slice at all. How can I access state of another slice in redux with redux-toolkit?.
So you have to dispatch two actions of two slices and every individual reducer will update its state individually.


text:
Q: How to use variable content in WebStorm file templates I have this file template in WebStorm 2018.2:
#set($TestSuiteName = ${StringUtils.removeAndHump(${NAME}, "-")})

describe("#[[$TestSuiteName$]]#", () => {

    it("should work", () =>
    {
        #[[$END$]]#
    });
});

The important point of this question is the #[[$TestSuiteName$]]# part of the template.  What I want to achieve is, that $TestSuiteName is replaced by the value calculated in the first template line and is selected for editing but can be accepted by pressing return.
All the template does right now is to print out "TestSuiteName" for the #[[$TestSuiteName$]]# expression, which is not what I want.  What it does right is to select the text "TestSuiteName" which it takes when I press return.
When I change the template to
#set($TestSuiteName = ${StringUtils.removeAndHump(${NAME}, "-")})

describe("$TestSuiteName", () => {

    it("should work", () =>
    {
        #[[$END$]]#
    });
});

then the filename is correctly camel-humped but it is not selected and the cursor jumps immediatly to the #[[$END$]]# location.
What would be the correct way of getting the camel-humped filename selected for editing?

A: There is no way to do this currently:(
$VAR$ syntax has a special meaning in Webstorm templates - it's a kind of live template variable, a placeholder that allows placing cursor at certain position and editing a value when applying the template. To make such placeholders work, #[[$VAR$]]# syntax is used to avoid conflicts with velocity variables (text in #[[]]# is rendered as is - see http://velocity.apache.org/engine/1.7/user-guide.html#literals). That's why you get variable name instead of camel-humped file name when using #[[$TestSuiteName$]]#.
We plan to provide a possibility to use the full power of live templates (live template functions, predefined variables, default values, etc.) in file templates. If you miss it, please vote for IDEA-161937, IDEA-173721 and linked tickets


text:
Q: How to copy array keys to another array, and replace values with empty array? I have an array, f. e.:
$arr = array(
    4 => 'some value 1',
    7 => 'some value 2',
    9 => 'some value 3',
    12 => 'some value 4',
    13 => 'some value 5',
    27 => 'some value 6',
    41 => 'some value 7'
)

I need to create another array, where values will be array, but the keys will be the same; like this:
$arr = array(
    4 => array(),
    7 => array(),
    9 => array(),
    12 => array(),
    13 => array(),
    27 => array(),
    41 => array()
)

Is there some build-in function in PHP for do that? array_keys() didn't help me:
var_dump(array_keys($arr));

Returned:
array(7) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(2)
  [3]=>
  int(3)
  [4]=>
  int(4)
  [5]=>
  int(5)
  [6]=>
  int(6)
}

A: This should work for you:
Just array_combine() your array_keys() from the old array, with an array_fill()'ed array full of empty arrays.
<?php

    $newArray = array_combine(array_keys($arr), array_fill(0, count($arr), []));
    print_r($newArray);

?>

output:
Array
(
    [4] => Array ()
    [7] => Array ()
    [9] => Array ()
    [12] => Array ()
    [13] => Array ()
    [27] => Array ()
    [41] => Array ()

)

A: Try this . You can use array_fill_keys() for more info follow this link
$arr = array(
    4 => 'some value 1',
    7 => 'some value 2',
    9 => 'some value 3',
    12 => 'some value 4',
    13 => 'some value 5',
    27 => 'some value 6',
    41 => 'some value 7'
);
$keys=array_keys($arr);

$filledArray=array_fill_keys($keys,array());
print_r($filledArray);

A: Change values to array saving keys:
$arr2 = array_map(function ($i){
    return array();
}, $arr);

result
Array
(
    [4] => Array ( )
    [7] => Array ( )
    [9] => Array ( )
    [12] => Array ( )
    [13] => Array ( )
    [27] => Array ( )
    [41] => Array ( )

)

A: Try this:
foreach($arr as $key => $value) {
  $array[$key] = array('a','b','c');
}


text:
Q: simulate Lazy in Java8 I wrote the following code to simulate Lazy<T> in Java:
import java.util.function.Supplier;

public class Main {

    @FunctionalInterface
    interface Lazy<T> extends Supplier<T> {
        Supplier<T> init();
        public default T get() { return init().get(); }
    }

    static <U> Supplier<U> lazily(Lazy<U> lazy) { return lazy; }
    static <T>Supplier<T> value(T value) { return ()->value; }

    private static Lazy<Thing> thing = lazily(()->thing=value(new Thing()));
    public static void main(String[] args) {

        System.out.println("One");
        Thing t = thing.get();
        System.out.println("Three");

    }
    static class Thing{ Thing(){System.out.println("Two");}}
}

but I get the following warning:

"value (T) in Main cannot be applied to (com.company.Main.Thing)
  reason: no instance(s) of type variable(s) T exist so that Supplier<T>
  conforms to Lazy<Thing>"

could you please help me find out what the problem is?
thanks in advance!

A: Lazy is a subclass of Supplier and you are trying to cast it otherways.
Changing
private static Lazy<Thing> thing = lazily(() -> thing = value(new Thing()));

to
private static Supplier<Thing> thing = lazily(() -> thing = value(new Thing()));

should work.

A: value() returns a Supplier, while thing field has type Lazy<Thing>. You cannot assign a Supplier to a Lazy (with whatever parametrization) because not all Supplier instances are Lazy instances.
Further, lazily() return value (which is a Supplier) is tried to be assigned to the thing, and this is not gonna work for the same reason.
We can change lazily type to Lazy and remove that inline thing= assignment (which is inside thing initializer expression) to make it compile:
static <U> Lazy<U> lazily(Lazy<U> lazy) { return lazy; }
static <T> Supplier<T> value(T value) { return ()->value; }

private static Lazy<Thing> thing = lazily(()->value(new Thing()));

But I'm not sure whether this is what you wanted to get.
If you just wanted a lazy behaviour, Supplier itself is already capable of acting lazy as get() is only executed when requested to and not when a Supplier is created.
If you want a caching logic (only compute once, and only compute it needed), you could use something like this:
public class CachingSupplier<T> implements Supplier<T> {
    private final Supplier<T> supplier;
    private T cachedValue;
    private boolean computed = false;

    public CachingSupplier(Supplier<T> supplier) {
        this.supplier = supplier;
    }

    public T get() {
        if (!computed) {
            cachedValue = supplier.get();
            computed = true;
        }
        return cachedValue;
    }
}

If you want to guarantee that supplier.get() gets called at maximum once, you could apply some synchronization:
    if (!computed) {
        synchronized (this) {
            if (!computed) {
                cachedValue = supplier.get();
                computed = true;
            }
        }
    }
    return cachedValue;

Here, a double-checked locking is used.


text:
Q: malayalam word sense disambiguation in python # encoding=utf-8
file=open("mm.txt","r+")
wordcount={}
for word in file.read().split():
    if word not in wordcount:
        wordcount[word] = 1
    else:
        wordcount[word] += 1
print (word,wordcount)
file.close();

This work fine for english sentence
how to work this code for malayalam sentence

A: You have to include encoding (utf-8) while opening the file
import codecs
with codecs.open("mm.txt",encoding="utf-8") as f:
   wordcount={}
     for word in f.read().split():

this will work


text:
Q: Get object type from Entity Framework ObjectStateEntry Within my overriding function for Entity Frameworks SaveChanges() function I am attempting to serialize the original entity and the modified entity, however I am having a hard time trying to deduce what the object type is so that I can pass it as a parameter to the XmlSerializer object.
Public Overrides Function SaveChanges() As Integer
    ChangeTracker.DetectChanges()

    Dim ctx As ObjectContext = DirectCast(Me, IObjectContextAdapter).ObjectContext
    Dim objectStateEntryList As List(Of ObjectStateEntry) = ctx.ObjectStateManager.
        GetObjectStateEntries(EntityState.Added Or EntityState.Modified Or EntityState.Deleted).ToList()

    For Each Entry As ObjectStateEntry In objectStateEntryList
        If Not Entry.IsRelationship Then
            Dim objectType As String = Entry.Entity.GetType.Name.Split("_").First
            Select Case Entry.State
                Case EntityState.Modified
                    For Each propertyName As String In Entry.GetModifiedProperties()
                        Dim ser As New XmlSerializer(Entry.Entity.GetType)
                        Dim sw As New IO.StringWriter
                        ser.Serialize(sw, Entry.OriginalValues)
                        Dim serializedObject As String = sw.ToString
                    Next
            End Select

        End If
    Next

    Return MyBase.SaveChanges()
End Function

I attempted the above, but to not avail.

A: Try this
Dim originalType = ObjectContext.GetObjectType(Entry.Entity.GetType())

GetObjectType is a static method.
Then just convert entity object to new type
Dim convertedEntity = Convert.ChangeType(Entry.Entity, originalType)

Convert.ChangeType is also static, stored in System.