text:
Q: Image fullscreen on click (Wordpress Image carussell) I have a similar problem like this (link). I want to edit my image carussel on my wordpress page, so that when I click on an image, it will be shown in full screen. If possible with close button.
The HTMl is:

  <title>Fullscreen Image</title>

Can someone give me an example for CSS or JS how I can do it (I do not know a lot of JS or jQuery)?
Thanks in advance

A: You need to perform a few tricky operations. First, you need to be able to show things on full-screen. I did this by setting the backgroundImage of body and hiding everything else once body gets the fullscreen class. But we need to avoid propagating the event, so, if the image is clicked in fullscreen mode, then we can restore the normal view.

    function makeFullScreen(event, image) {
        event.stopPropagation();
        event.source;
        document.body.style.backgroundImage = `url("${image.src}")`;
        document.body.classList.add("fullscreen");
    }

    function hideFullScreen() {
        document.body.style.backgroundImage = '';
        document.body.classList.remove("fullscreen");
    }
body.fullscreen {
    background-size: cover;
    background-repeat: no-repeat;
}

body.fullscreen * {
    display: none;
}

  <title>Fullscreen Image</title>


text:
Q: Disappear text when button is clicked (JQUERY) So I am making a small PHP Javascript and JQUERY Chatbox and so far its working pretty good but im trying to "Fancy it up".  It asks you, the user, for your Name and once you type your name in to the input box you are supposed to click Enter which brings you to the chat box.  Here is the code for the Chatbox.
http://pastebin.com/DgQEC9rV
You can find the Send button in the PHP at the top of the page.
But I was wondering how to make the Send button and the whole box it is in disappear with JQUERY and have the chat box still load in regularly.
A live example of the chat right now. --> http://www.carlosmayers.com/knil/chat/
I know just looking at the code might make this question seem very unapproachable but I know someone here can help me!  Thanks.

A: If i intepreted your question right you just want to hide the hole chatbox. But it should still update itself.
So with jQuery you do this: $("#wrapper").attr("style", "display: none");
Whereas #wrapper is the div with the id (# := css-Selector) "wrapper" in your document.
jQuery now sets its style to "display: none", but the Chatbox will still be updated!
If you have Chrome, feel free to test it in the console first.
You could also use $("#wrapper").hide();

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to connect to users of same app via Bluetooth I'm writing an App that allows its users to automatically exchange data with other nearby users over BlueTooth. Normally, the two users would have to manually pair with each other before this could happen.
I was wondering if there was a way to bypass this step and automatically discover and connect to nearby users of my app, perhaps using some kind of app id signature for security?
Thank you!

A: I see from your comment that you have already discovered the solution to the 'connect' part of your question: the API's for creating an insecure connection without manual pairing.
But that still leaves discovery.  In order to create a connection you need the Bluetooth address (bd addr) of the target.  To do this, you will need to get one user's phone into discoverable mode, and then do a discovery on the other phone.  This can't be done silently - your app can invoke these modes, but this will cause the phone to prompt the user.  No so bad, but probably not as automatic as you want.
If the two phones are on the same network, they could exchange bd_addr over the network - eliminating the need for discovery.  Or this could happen with a server as an intermediary, but this is a lot more work if you don't already plan to have a server.


text:
Q: getting profile picture from Facebook too slow I'm trying to get the user's profile picture form Facebook, to display it on his Account screen. It works, but the problem is, it's too slow. The screen will load, and a good half a second later, the profile picture loads. Here is my viewDidLoad code, where I make the graph API request:
override func viewDidLoad() {
    super.viewDidLoad()

    currentUser = User.CurrentUser

    editProfileButton.layer.cornerRadius = 2.5

    // checking for logged in user
    let defaults = NSUserDefaults.standardUserDefaults()

    if FBSDKAccessToken.currentAccessToken() != nil {
        // logged in through facebook, do nothing
        updateCurrentUser()
    } else {
        // log in
        presentLoginViewController()
    }

    userNameLabel.text = currentUser.first_name + " " + currentUser.last_name
    userPhoneLabel.text = currentUser.phone_number

    //getting profile picture: too slow for now.
    if FBSDKAccessToken.currentAccessToken().hasGranted("user_photos") {
        let userId = FBSDKProfile.currentProfile().userID
        let graphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"picture.type(large)"])
        graphRequest.startWithCompletionHandler({(connection: FBSDKGraphRequestConnection!, response: AnyObject?, error: NSError!) in
            if error != nil {
                // error
            }

            if let resultDic = response as? NSDictionary {
                let data = resultDic["picture"] as? NSDictionary
                let dataDict = data!["data"] as? NSDictionary
                let imageStringUrl = dataDict!["url"] as? String
                let imageUrl = NSURL(string: imageStringUrl!)
                let imageData = NSData(contentsOfURL: imageUrl!)
                self.currentUser.profilePicture = UIImage(data: imageData!)
                self.userPicImageView.image = self.currentUser.profilePicture
            }
        })
    }

    // user profile picture set up
    userPicImageView.clipsToBounds = true
    userPicImageView.contentMode = .ScaleAspectFill
    userPicImageView.layer.cornerRadius = userPicImageView.frame.height / 2.67
}

Anyway I can make it faster?

A: For starters, putting the FBSDKGraphRequest call further back in the life cycle is definitely not going to help you get your data faster. viewDidLoad is a good place to put it - if you have to start it within a particular screen.
Next, you doing the image fetching asynchronously will help improve user experience. The code that you currently have will block the main thread, since the downloading process is on the main thread. I suggest you read up on NSURLSession to deal with obtaining the images.
Techniques to get photos faster
There are a couple of reliable ways to get your photos "faster". One way is to grab a smaller image, if acceptable.
If you must have a large image, a good method is to abstract the network call in another class, and initialize the process as early as possible, for instance, in the didFinishLaunchingWithOptions method of the AppDelegate.
For instance, you can have a class:
class FacebookDetails {
    static let sharedInstance = FacebookDetails()
    var image: UIImage?

    private init() {
        populateImage()
    }
    func populateImage() {
        let graphRequest = FBSDKGraphRequest... //continue with populating image
    }
}

Now you can initialize this class as early as possible in your application life cycle:
  func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    FacebookDetails.sharedInstance
    return true
  }

When you get to the view controller that requires the image, call FacebookDetails.sharedInstance.image to retrieve the already loaded image (image load times is still subjected to network strength), but it's a method to start loading your images as early as possible in your application life cycle.


text:
Q: Relations in Angular (Error 400 - Bad Request) I have quite a big problem with adding data to the table connected with the Spring database. Namely, just adding to the table works fine, only when I don't choose anything from the Combo Box. When I choose, I get this message:
zone-evergreen.js:2952 POST http://localhost:4200/api/cars 400 (Bad Request)

HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: "Bad Request", url: "http://localhost:4200/api/cars", ok: false, …}

I am aware that this is a problem with the link and most likely with a relationship, but I have no idea how to solve this problem.

My models look like this:
http-cars.model.ts
export class carStatus {
  id: number;
  name: string;
}

//carStatus.model.ts (TypeScript)

export class carType {
  id: number;
  name: string;
}

//carType.model.ts (TypeScript)

To better understand the problem, I will give services and the vehicle adding component (if you need more files, please write):
add-dialog1.component.ts
http-cars.service.ts
car-status.service.ts (carType has the same service only with changed variables and names)
config.service.ts (all included functions link to a link from proxy.conf.json)
{
  "/api": {
    "target": "xxx(link)",
    "secure": false,
    "changeOrigin": true,
    "logLevel": "debug"
  }

}

And finally HTML:
add-dialog1.component.html
If anyone has an idea why adding data without using a combo box works fine, and if I choose something from these two combo boxes (or one of them) the above error appears, please write what I made the error and how I can solve it. Buddy responsible for Spring said
that everything is fine on his part and when he sends data via Postman it works for him, but in my table in combobox columns shows "[object object]". here is an example of a query and part of my table:
Postman Query
Part of table
Please be forgiving. This is my second question and I have no experience asking questions here, and I am mostly looking for answers on this page. If I did something incompatible with your netiquette, please
let me know. I can't find any solution to the problem and what I tried didn't work and I need help.

A: I would start by looking at the information available in the "network" tab, usually in the console window or menu of your browser.
Second, I would attempt to issue the command to the backend using a curl command. The ability to do that would tell you whether the problem is in your frontend or backend or http command.


text:
Q: Local variables and elif I would like to know why the compiler writes:

local variable 'randomindexmother1' referenced before assignment

I have been searching and I do not need to treat the randomindexfather1 as a global variable. Therefore, I think that is a mater of the elif statements.
def generation(listPaths):
    # This function will give us the new generation of kids
    # we will introduce the survived paths
    # This function will take as input the list sorted paths and sorted fitnesses of each path
    # listP will be a list produced in a while statmentself.
    rand1 = 0
    rand2 = 0
    lunusedindex = []
    newpaths = []
    i = 0
    fpoint = listPaths[0][0][0]
    lpoint = listPaths[0][0][-1]
    mother = []
    father = []
    kid1 = []
    srtlist = []
    # this is going to be the random number between the fitness of the maximum path fitness and the minimum of
    # the half population
    leng = len(listPaths)
    lunusedindex = range(leng)
    while i < leng / 2:
        # here we select an aleatory father and an aleatory mother
        rand1 = random.choice(lunusedindex)
        rand2 = random.choice(lunusedindex)
        if rand1 == rand2:
            while rand1 == rand2:
                rand1 = random.choice(lunusedindex)
        # here we delete the mother and the father selected to not repeat a father and mother
        del lunusedindex[rand1]
        if rand1 < rand2:
            del lunusedindex[rand2 - 1]
        else:
            del lunusedindex[rand2]
        k = 0
        while k < 2:
            mother = copy.deepcopy(listPaths[rand1][0])
            father = copy.deepcopy(listPaths[rand2][0])
            del mother[0]
            del mother[-1]
            del father[0]
            del father[-1]
            indexfather = range(len(father))
            indexmother = range(len(mother))
            kid1.append(fpoint)
            j = 0
            ref = 0
            rem = 0
            while j < len(father) or len(mother):
                # with this statment we ensuring that less points are going to be repeated and if mother or father
                # become empty, this means that all the points are used but some of them can be repeated
                if len(indexfather) <= 2:
                    randomindexfather1 = random.randint(indexfather[0], indexfather[1 - ref])
                    del indexfather[0:randomindexfather1 + 1]
                    ref += 1
                    if len(indexfather) == 0:
                        randomindexfather2 = randomindexfather1 + 1
                    else:
                        randomindexfather2 = random.randint(indexfather[0], indexfather[1 - ref])

                elif len(indexmother) <= 2:
                    randomindexmother1 = random.randint(indexmother[0], indexmother[1 - rem])
                    del indexmother[0:randomindexmother1 + 1]
                    rem += 1
                    if len(indexmother) == 0:
                        randomindexmother2 = randomindexmother1 + 1
                    else:
                        randomindexmother2 = random.randint(indexmother[0], indexmother[1 - rem])

                elif len(indexfather) > 2:
                    randomindexfather1 = random.randint(indexfather[0], (len(indexfather) - 2))
                    del indexfather[0:randomindexfather1 + 1]
                    randomindexfather2 = random.randint(indexfather[0], (len(indexfather) - 1))

                elif len(indexmother) > 2:
                    randomindexmother1 = random.randint(indexmother[0], (len(indexmother) - 2))
                    del indexmother[0:randomindexmother1 + 1]
                    randomindexmother2 = random.randint(indexmother[0], (len(indexmother) - 1))

                kid1.extend(father[randomindexfather1:randomindexfather2])
                kid1.extend(mother[randomindexmother1:randomindexmother2])
                del father[randomindexfather1:randomindexfather2]
                del mother[randomindexmother1:randomindexmother2]
                j += 1
                # with this code we take parts of the parents until they will be empty,the problem is that points are going to be repeated
            kid1.append(lpoint)
            for x in kid1:
                inde = random.uniform(0, len(kid1) - 1)
                if kid1[inde] in kid1:
                    del kid1[inde]
            distances = []
            totdist = 0
            z = 1
            while z < len(kid1) - 1:
                # menys 1 ja que tenim len(kid1)-1 intervals
                distances.append(distpoint(kid1[z - 1], kid1[z]))
                totdist = sum(distances)
            newpaths.append([kid1, totdist])
            k += 1
        i += 1
    srtlist = sorted(newpaths, key=operator.itemgetter(1))
    return srtlist

x = [[[[3, 4], [2, 4], [5, 8], [2, 4], [4, 5]], 5], [[[3, 4], [6, 8], [4, 6], [6, 4], [4, 5]], 4]]
Y = generation(x)
print Y

A: You have execution paths that doesn't set randomindexmother1 uses it nonetheless. Assume len(indexfather) <= 2 then you don't execute the other clauses and hit kid1.extend(mother[randomindexmother1:randomindexmother2]) without setting the variable. Looks like a bug in your program logic.


text:
Q: change the variable if specific param is present in url how can I use this.router.url to check if my my URL contain specific parameter such as id?
In one instance i am using following if url has profile to change search icon. i want to same for user/videos/:id but only when the id param is present in url
    if (this.url.includes("profile")) {
      this.searchIcon = true;
    }

A: For a quick fix you could use the paramMap snapshot from ActivatedRoute.
import { ActivatedRoute } from '@angular/router';
...
export class SomeComponent implements OnInit {
  id: any;
  constructor(private _activatedRoute: ActivatedRoute) { }

  ngOnInit() {
    this.id = this._activatedRoute.snapshot.paramMap.get('id');
    if (!!this.id) {
      // `id` defined
    } else {
      // `id` undefined
    }
  }
}


text:
Q: org.apache.thrift.protocol.TProtocolException: Bad version in readMessageBegin I'm trying to connect cassandra with zeppelin. Every time I try to execute a query I get the following error. What should I do?
 %cassandra
select * from rawtweet1

org.apache.thrift.protocol.TProtocolException: Bad version in readMessageBegin
        at org.apache.thrift.protocol.TBinaryProtocol.readMessageBegin(TBinaryProtocol.java:223)
        at org.apache.thrift.TServiceClient.receiveBase(TServiceClient.java:69)
        at org.apache.zeppelin.interpreter.thrift.RemoteInterpreterService$Client.recv_createInterpreter(RemoteInterpreterService.java:184)
        at org.apache.zeppelin.interpreter.thrift.RemoteInterpreterService$Client.createInterpreter(RemoteInterpreterService.java:168)
        at org.apache.zeppelin.interpreter.remote.RemoteInterpreter.init(RemoteInterpreter.java:172)
        at org.apache.zeppelin.interpreter.remote.RemoteInterpreter.getFormType(RemoteInterpreter.java:328)
        at org.apache.zeppelin.interpreter.LazyOpenInterpreter.getFormType(LazyOpenInterpreter.java:105)
        at org.apache.zeppelin.notebook.Paragraph.jobRun(Paragraph.java:260)
        at org.apache.zeppelin.scheduler.Job.run(Job.java:176)
        at org.apache.zeppelin.scheduler.RemoteScheduler$JobRunner.run(RemoteScheduler.java:328)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)

A: The problem was in the configuration of the Cassandra interpreter. I had to change it back to the default settings and than everything worked.


text:
Q: Calculate Topographic wetness index in SAGA i am currently working on a project which involves the quantification of the wetness in certain areas. However it produces quite different results from what i expected. I'll describe the steps i have taken.
To do so i used the ASTER global DEMv2 and clipped it to the parts to be examined. I have to clip the raster, because using the original DEM results in various errors saying "memory allocation failed".

Then i calculated the slope and Catchement area via the SAGA function Catchment Area (Mass-Flux-Method, parameter: flow-spit method area cell). I also tried the Parallel and recursive method, however the results are mostly the same.
Then i calculated the Topographic Wetness Index, but the results look very mixed (somewhere between a rainbow and random fuzzy bits) and values are always negative.

I expected that the resulting raster should look like and display index values like the following image in the pdf PDF, page 14.
Has someone here experience with the quantification of topographic wetness in an area and could provide a tutorial how to do it right?
I would appreciate using SAGA or QGIS, but i also have ArcGis 9 at Hand.
By the way:
If i just use the calculate the SAGA wetness index with the clipped elevation data above, SAGA always keeps crashing (i believe because of the large no-data areas, because smaller smarts work)

A: First, you need to calculate at least the slope. F.ex I have the following data:

Then put the correct data as variables to the module:

And at last you should get the result:

UPDATE
With Catchment Area as input

the results are:


text:
Q: Sourcing current with sink LED driver I'm using an existing keypad with 8 LEDs that source power. I was hoping to use and LED driver of sorts, but all of the ones I find only refer to sinking power. Is it possible to use these drivers to source current, and if so is there a way of understanding how to convert the sinking specifications to sourcing? The Vcc for my system is 3.3V and LEDs are 3.4V and 20mA
Was looking at this TI TLC5917 driver.
The LEDs on keypad are Lite-On LTST-C150TBKT.
The circuit is setup like

simulate this circuit – Schematic created using CircuitLab

A: Firstly, these drivers do not sink or source power. The stuff they source or sink is current. Power is the rate of energy use or conversion. Current is the flow of electric charge. Very different things.
The arrangement of LEDs you have is called common cathode, because the cathodes of all the LEDs are connected to the same thing.
A driver designed to sink current can not be made to source current. It's certainly possible to design a driver to source current, but this would be a different component. I took a quick look on TI's web site and didn't find anything equivalent to the driver you were considering, but which sourced current. I'm sure someone makes one, but it's somewhat less common.
I'm guessing this is a hobby project, so you aren't going to incur any unacceptable cost by using a few more components. So, you might consider skipping the driver IC. Here's one way you might do it:

simulate this circuit – Schematic created using CircuitLab
The transistor bases can run directly to a microcontroller, or an ordinary shift register.

A: At least one of the traditional 74-series families which will source over 10mA.
I typically use a 1K current limiting resistor on 5V (so under 5mA per LED), so 10mA is plenty to light an LED.
(Edit: 74 series families include 74F, 74AC, 74ACT, see for example TI "Non-Inverting Buffer/Driver"
Allegro make octal High-side drivers, for example the A2982, which is what you is asked.
I don't know if it is an obstacle, but that is in SOIC, which may be a bit awkward unless you have SMD facilities.
If SOIC is awkward, you may buy an 'adapter', a PCB which would carry a SOIC and give a DIP pin out. That is still a bit awkward to solder, however it makes things a more convenient, especially if you are using breadbard or stripboard (veroboard) to prototype or build something.
Otherwise you might use small P-MOSFETs. They will connect between each LED and +V. There will be a current limiting resistor.  Again packages are mostly SMD.


text:
Q: Laravel 5 migration error 1045 I am having the following error:

After following this guide:
http://tutsnare.com/access-denied-for-user-homesteadlocalhost-laravel-5/
I changed my .env file in accordance with the guide but I'm still getting that error.  Does anyone else know how to solve this?  Also I am using a mac with MAMP on localhost.  Thanks.

A: In your .env file you need to set the database config values to match your database configuration. With your current settings you are trying to login to the database as the root user without a password.
You say that you're using MAMP and the default MySQL password under MAMP is root, so your .env should have these database values.
DB_HOST=localhost
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=root

Obviously, you'll also need to make sure there is a database named laravel.

NOTE: Don't run this configuration in a production environment or any environment where security is important. It's ok for development, but for a production server I would recommend giving Laravel its own database user, and only granting that user permissions for your laravel database.

A: If you using MAMP you need to add some things.
In your .env add this..
DB_UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_PORT=8889

If you changed your MAMP MySQL port change it here too.
Then in your database.php config add unix_socket and port..
'mysql' => [
    'unix_socket'   => env('DB_UNIX_SOCKET', ''),
    'port'          => env('DB_PORT', '3306'),
],


text:
Q: Linear relationships for two (x,y) graphs I have x,y data coming in from a [coordinates1] database (GIS - but this could be any database). I have my application with it's own coordinate system, referencing THE SAME MAP.
I have established that a linear relationship exists between coordinates1 (x,y) and coordinates2(x,y) as I have subtracted two different coordinates1 and coordinates2 (dividing x1 with x2 and y1 with y2) and in all cases I get them both showing 0.724 or 0.141 or 0.825 respectively i.e. coordinates1 + coordinates2.
What I now need to figure out - or you help - is that if coordinates1(100000,200000) and coordinates2(0.125,0.255) how do I calculate coordinates2(x,y) from the data in coordinates1(x,y)?

A: For the sake of clarity, I'm going to call coordinates in your base (xn, yn), and coordinates in your target (un, vn).
Now, if we assume:

*

*The origins of the two coordinate systems are the same.

*The orientation of the two coordinate systems are the same (i.e. one is not rotated with respect to the other).

In this case you only need one set of points {(x1, y1), (u1, v1)} to determine the location of (un, vn):

*

*un = u1/x1 * xn

*vn = v1/y1 * yn
Note: we must have x1 ≠ 0, y1 ≠ 0

On the other hand, if the two coordinate systems have different origins (but they are still not rotated with respect to one another), we will need two sets of points {(x1, y1), (u1, v1)} and {(x2, y2), (u2, v2)}:

*

*un = (u2 - u1)/(x2 - x1) * (xn - x1) + u1

*vn = (v2 - v1)/(y2 - y1) * (yn - y1) + v1
Note: we must have x1 ≠ x2, y1 ≠ y2

Now, if the two coordinate systems are rotated with respect to one another, you need (I believe) one more set of matching coordinates.  But it doesn't sound like you need that (unless one of your maps has north pointing in a direction other than straight up), so I'm not going to work out the math now. :)

A: To do the conversion, you need to know the coordinates of one point O in your two coordinates systems .
Let's suppose O has coordinates x1O,y1O in coordinate system 1, and x2O,y2O in coordinate system 2.
Then a point with coordinates x1,y1 in system 1, and x2,y2 in system 2 will satisfy:
(x1O - x1) = Kx * (x2O - x2)
(y1O - y1) = Ky * (y2O - y2)

where Kx and Ky are the scale factor. If you know the coordinates of an other point M in both systems, than you will have Kx and Ky with
Kx = (x1O - x1M) / (x2O - x2M)
Ky = (y1O - y1M) / (y2O - y2M)

Then, you just need to apply the first relationship to go from one system to another system, with
x1 = x1O - Kx * (x2O - x2)
y1 = y10 - Ky * (y2O - y2)

or
x2 = x2O - (x1O - x1) / Kx
y2 = y2O - (y1O - y1) / Ky

Do you also need the code ?


text:
Q: If statement then click event in JavaScript I am trying to only allow a click event to fire if a function return is true. I am not sure if this is the correct syntax or not. Any help would be awesome.
onclick="if(AveryValidateAddress())Shipping.save()"

A: Why would you not include the check Inside the function ?
HTML
onclick="myFunction()"

JS
myFunction = function(){
  if (!AveryValidateAddress()){
     //Dont do anything if it's false
     return
  }
  else{
      Shipping.save()
  }
}

A: Try:
onclick="AveryValidateAddress() && Shipping.save()"

A: The way you have it written, you could accomplish this by taking advantage of the && operator's lazy evaluation. If the first part of your and statement evaluates to false, it won't attempt to evaluate the second part.
onclick="AveryValidateAddress() && Shipping.save()"

However, since you're using jQuery, a better approach would be to take advantage of jQuery's event binding:
Click to save


text:
Q: CAPL - When Button is clicked - program is executed twice The code which need to be executed when Button is clicked. It is being executed twice.
when I use "if(this == 1)" I am having an error "Operand types are incompatible"
on sysvar_update sysvar::NexteerData::WriteRead
{
      seclevel = 1;
      ExtendedSession.SendRequest();
      toggle2 = 1;
      Write("Write CALIBRATION VALUES");
}

A: When using the value of the system variable in an if statement, use as follows:
if(@this == 1)

This will solve your error and also the double execution issue.


text:
Q: Десериализация JSON в KryoNet Пытаюсь написать сервер для онлайн-игры. На данном этапе сервер принимает от клиента координаты игрока и рассылает эти координаты остальным игрокам. В тестовом формате использовал сериализацию Kryo и всё работало отлично, но мне необходимо, чтобы информация в моих пакетах находилась в JSON, поскольку клиентская часть написана на C#. С этим возникают проблемы, а именно сервер выкидывает ошибки
09:24 ERROR: [kryonet] Error reading TCP from connection: Connection 1
com.esotericsoftware.kryonet.KryoNetException: Error during deserialization.
    at com.esotericsoftware.kryonet.TcpConnection.readObject(TcpConnection.java:141)
    at com.esotericsoftware.kryonet.Server.update(Server.java:205)
    at com.esotericsoftware.kryonet.Server.run(Server.java:372)
    at java.base/java.lang.Thread.run(Thread.java:830)
Caused by: com.esotericsoftware.jsonbeans.JsonException:
    at com.esotericsoftware.jsonbeans.Json.readValue(Json.java:800)
    at com.esotericsoftware.jsonbeans.Json.fromJson(Json.java:620)
    at com.esotericsoftware.kryonet.JsonSerialization.read(JsonSerialization.java:68)
    at com.esotericsoftware.kryonet.TcpConnection.readObject(TcpConnection.java:139)
    ... 3 more
Caused by: java.lang.ClassNotFoundException: Position
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:602)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    at java.base/java.lang.Class.forName0(Native Method)
    at java.base/java.lang.Class.forName(Class.java:333)
    at com.esotericsoftware.jsonbeans.Json.readValue(Json.java:797)
    ... 6 more
09:24  INFO: [kryonet] Connection 1 disconnected.

после получения со стороны клиента JSON вида
{
class: Position,
x: 315,
y: 330,
z: 0
}

Класс Position как со стороны клиента, так и со стороны сервера одинаковый(поля публичные, поскольку было подозрение, что десериализация в приватные поля может приводить к ошибкам):
@Data
public class Position {
    public int x, y, z;
    public Position(){}
}

Код сервера:
import DTOs.Position;
import DTOs.UnitPosition;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.JsonSerialization;
import com.esotericsoftware.kryonet.Listener;
import com.esotericsoftware.kryonet.Server;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class Servers extends Listener {

    private final Map<Integer, Position> messages = new HashMap<>();
    private static Server server;

    public static void main(String[] args) throws IOException {
        int port = 27960;
        server = new Server(port, port, new JsonSerialization());
        server.bind(port);

        server.start();

        server.addListener(new Servers());
    }

    @Override
    public void connected(Connection c) {
        messages.forEach((id, data) -> server.sendToTCP(c.getID(), new UnitPosition(c.getID(), data)));
    }

    @Override
    public void received(Connection c, Object object) {
        if (object instanceof Position) {
            Position message = ((Position) object);
            messages.put(c.getID(), message);
            server.sendToAllExceptTCP(c.getID(), new UnitPosition(c.getID(), message));
        }
    }

    @Override
    public void disconnected(Connection c) {
        messages.remove(c.getID());
        server.sendToAllExceptTCP(c.getID(), c.getID());
    }

}

Код клиента:
import com.esotericsoftware.kryonet.Client;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.JsonSerialization;
import com.esotericsoftware.kryonet.Listener;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class MyClient extends Listener {
    private final static int tcpPort = 27960;
    private final static Client client = new Client(tcpPort, tcpPort, new JsonSerialization());
    private final static String ip = "localhost";
    private final Map<Integer, UnitPosition> positionMap = new HashMap<>();
    private final Random random = new Random();
    private Position my;
    private static MyFrame frame;

    public static void main(String[] args) throws IOException {
        client.start();
        client.connect(10000, ip, tcpPort);

        MyClient myClient = new MyClient();
        client.addListener(myClient);
        frame = new MyFrame(myClient);
        myClient.my = new Position(Math.abs(myClient.random.nextInt() % 400),
                Math.abs(myClient.random.nextInt() % 400));
        client.sendTCP(myClient.my);
    }

    @Override
    public void received(Connection connection, Object object) {
        if (object instanceof UnitPosition) {
            UnitPosition now = (UnitPosition) object;
            if(now.getId() != connection.getID()) {
                positionMap.put(now.getId(), now);
                try {
                    frame.repaint();
                } catch (NullPointerException exception) {
                    System.out.println("Repaint throw nullPointer!");
                }
            }
        } else if(object instanceof Integer){
            positionMap.remove(object);
            try {
                frame.repaint();
            } catch (NullPointerException exception) {
                System.out.println("Repaint throw nullPointer!");
            }
        }
    }

    public Position getMy() {
        return my;
    }

    public Map<Integer, UnitPosition> getPositionMap() {
        return positionMap;
    }

    public void send() {
        client.sendTCP(my);
    }
}

A: Проблема состояла в том, что класс Position находился в разных пакетах на клиенте и на сервере. При передаче json пакета в переменную class заносится полное имя класса с учётом пакета, поэтому местонахождение передаваемых классов на клиенте и на сервере должно совпадать.


text:
Q: How can I get ........ of extra characteres of edittext in android? I am new to android and my task is to display ...... when entered more characters in EditText?
Thanks in advance

A: It's a bit hard to understand. Is that what you're looking for - the following appends dots when the text does not fit:
android:ellipsize="end"
android:maxLines="1"
android:scrollHorizontally="true"
android:lines="1"

A: Is this what you're looking for?
<EditText
    android:inputType="password"
    />


text: Q: ArcGIS Layer to KML scale I am trying to create a KML from a layer composed of a large number of polygons.  Because of the large size, it is quite slow to load the KML in Google Earth.  Is there any way to create the KML so that it is only the polygons that are in the display area are visible?


text:
Q: how to get link file from google cloud storage use nodejs I'm try to create a video streaming site using react (client), nodejs (server), mongodb (database) and google cloud storage (for video).
My questions are:

*

*how do I import files into GCS from nodejs and get the link, so i can save the link into the DB

*how stream the videos to client

A: Rather than saving the url of the file to Mongodb, it's better to generate a signed url. This will give users a temporal access to the file. This way you can control who can access your videos easily. On the other hand, if you don't use this method then you will be forced to make your files public and anyone can access them and I guess that's not what you want.
To generate a signed url check the example bellow
// Imports the Google Cloud client library
const { Storage } = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();
async function generateSignedUrl() {
  // These options will allow temporary read access to the file
  const options = {
    version: 'v2', // defaults to 'v2' if missing.
    action: 'read',
    expires: Date.now() + 1000 * 60 * 60, // one hour
  };

  // Get a v2 signed URL for the file
  const [url] = await storage.bucket(bucketName).file(filename).getSignedUrl(options);

  console.log(`The signed url for ${filename} is ${url}.`);
}


text:
Q: systemctl start service in Dockerfile script I am trying to build the docker image using CentOS 7.7 as my base docker image which is systemd image.
Now, my requirement is like this: install the first RPM which starts the systemctl start my-process and this process required to be started in order to install my second RPM. But since Dockerfile not able to start the process using systemctl, i am not able to install any RPM correctly. I am getting following error:
Failed to get D-Bus connection: Operation not permitted

A: The "systemctl" client tool does not do much. It looks for the socket to contact the systemd daemon running on PID 1, i.e. the program you have been running from ENTRYPOINT.  If you have removed the systemd service then you will get an error like that.
If you want to use a container like a virtual machine then it may be better run a different service-manager on PID-1. An example would be the docker-systemctl-replacement service.
It has served me well to bring applications into containers which were not really meant for that.


text:
Q: BLE - i am not able to read 2 characteristic one of temperature service and another of Battery service at same time This is my code where i am discovering services and then get characteristic and setting descriptor for both temperature and battery characteristic.
In starting i am discovering services for Temperature and Battery.
then,I discover characterstic for each Temperature and Battery service
and write descriptor for both.
When i run the code,the call is going to onCharactersticChanged and i got the temperature result.
But,call is not going on OnCharactersticRead for battery
    for (BluetoothGattService service : services) {
                Log.e("asd service discoverd", service.getUuid().toString());

//                check for service should be temperature service or Battery service
                if (service.getUuid().equals(BT_THERMO_SERVICE) || service.getUuid().equals(BT_BATTERY_SERVICE)) {
                    Log.e("asd service discoverd", service.getUuid().toString());

                    List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();

                    //
                    // Create a compartor
                    // sort list with cpmparor

                    // addd in queue

                    // read same

                    for (BluetoothGattCharacteristic characteristic : characteristics) {
                        Log.e("asd charac discoverd:", characteristic.getUuid().toString());
                        if (characteristic.getUuid().equals(BT_REAL_TIME_TEMPERATURE_CHARTERISTICS) || characteristic.getUuid().equals(BT_BATERY_LEVEL_CHARACTERISTICS)) {
                            Log.e("asd charac discoverd:", characteristic.getUuid().toString());

                            arrayList.add(characteristic);

                            // check if characterstic is RealTime Temperature Measurement characterstic  or Battery Level characterstic
                            if (characteristic.getUuid().equals(BT_REAL_TIME_TEMPERATURE_CHARTERISTICS)) {
                                //indicate ble to send temperature data each time when new data value found

                                //notify ble device to send data
                                gatt.setCharacteristicNotification(characteristic, true);

                                for (BluetoothGattDescriptor descriptor : characteristic.getDescriptors()) {
                                    descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
                                    gatt.writeDescriptor(descriptor);

                                }
                            } else
                            if (characteristic.getUuid().equals(BT_BATERY_LEVEL_CHARACTERISTICS)) {

                                //notify ble device to send data
                                gatt.readCharacteristic(characteristic);

                                for (BluetoothGattDescriptor descriptor : characteristic.getDescriptors()) {
                                    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                                    gatt.writeDescriptor(descriptor);

                                }

                            }
                        }
                    }

                }

These are my gattcallback methods.
 @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicRead(gatt, characteristic, status);
            Log.e("charvalu", "" + characteristic);
            if (characteristic.getUuid().equals(BT_BATERY_LEVEL_CHARACTERISTICS)) {
                byte b[] = characteristic.getValue();
                if (b.length != 0) {
                    Log.e("battery", Integer.toString(b.length));
//                    ByteBuffer batterybuffer = ByteBuffer.wrap(b);
//                    Long batteryStatus = batterybuffer.getLong();
//                    Log.e("battery","" + batteryStatus);

                }
            }
        }

@Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            super.onCharacteristicChanged(gatt, characteristic);
            Log.e("inside char", "" + characteristic);
            if (characteristic != null) {
                Log.e("on change char", characteristic.getUuid().toString());

                if (characteristic.getUuid().equals(BT_REAL_TIME_TEMPERATURE_CHARTERISTICS)) {
                    Log.e("on change inside", characteristic.getUuid().toString());

                    //temperature data comes in byte array of size 12
                    byte b[] = characteristic.getValue();

                    if (b.length != 0) {
                        //check header and tail of data packet
                        if (b[0] == 0x7C && b[11] == 0x7D) {
                            //Temp reading is stored in 7 and 8 byte
                            ByteBuffer tempBuffer = ByteBuffer.wrap(b, 7, 2);
                            tempBuffer.order(ByteOrder.LITTLE_ENDIAN);
                            Short temp = tempBuffer.getShort();
                            final Float fTemp = (float) (temp / 100.0);
                            Log.e("sunittemp", Float.toString(fTemp));
                            runOnUiThread(new Thread() {
                                @Override
                                public void run() {
                                    super.run();
                                    workingListener.unstableReading(new IvyThermoReading(fTemp));

                                }
                            });
                        }
                    }
                }
            }
        }

A: Unfortunately sending all read and write requests at once synchronously does not work since android only allows one pending GATT operation at a time. You must somehow enqueue the work and continue sending another request once the callback of the previous request arrives.


text:
Q: Xpath same type child node concatanation with line break in xpath 1.0 I have an XML in the following format
<books>
      <book>ABC</book>
      <book>CDE</book>
      <book>FGH</book>
</books>

Is it possible for me to get the values inside <book> tag concatenated into a single field with a line break between each value using an XPath function? I mean the return field is something like
this as single field.
ABC
CDE
FGH

Can I achieve this using an XPath function because the 3 tags have same name? I can split and get the individual elements separately using {split(xpath('//books'),' ',0)} (returns ABC)
I checked the split function it seems to be for one tag but here are 3 tags.


text:
Q: Is $|xy|^{2/3} = (xy)^{2/3}$?
Can we say $$|xy|^{2/3} = (xy)^{2/3}$$

Can we take the absolute value out consider $ x, y $ are real numbers?

A: How would you explain your way out of this?
$(-1)^{\frac 26} = (-1)^{\frac 13} = -1$
$(-1)^{\frac 26} = ((-1)^2)^{\frac 16}=1^{\frac 16}=1$
addendum
You could just ask if $|x|^{\frac 23} = x^{\frac 23}$
This is obviously true when $x \ge 0$
If it works for one negative number, it should work for all of them. So we compute
$|-1|^{\frac 23} = 1$
$(-1)^{\frac 23} = \left((-1)^2 \right)^{\frac 13} =1^{\frac 13} = 1$
$(-1)^{\frac 23} = \left((-1)^{\frac 13} \right)^1 = (-1)^2 = 1$
So, yes, it seems to be true.

A: I think if we write $x^{\frac{2}{3}}$ then we need $x>0$ by definition.
Thus, in my opinion, the answer is "no":
$$|xy|^{\frac{2}{3}}\neq(xy)^{\frac{2}{3}}$$
For example, $$(-8)^{\frac{1}{3}}=-2$$ is wrong by definition.
By the way, $\sqrt[3]{-8}=-2$.
Let $f(x)=x^{\frac{2}{3}}$.
Thus, the domain of $f$ is $(0,+\infty)$.
This definition come from the following things.
Let $f(x)=x^{r}$, where $r\in\mathbb Q$.
$(-2)^2=4$, but $(-2)^{\frac{1}{2}}$ is undefined.
$0^2=0$, but $0^{-1}$ is undefined and $0^0$ is undefined.
Id est, if we wish to work with the function $f$ then we must assume $x>0$.
By the way, the domain of $g(x)=\sqrt[3]{x^2}$ is $\mathbb R$.


text:
Q: Nilpotent matrix and basis for $F^n$
Let $A \in Mat_{n \times n}(F)$ a matrix which satisfies $A^n=0$ and $A^{n-1} \ne 0$ for some positive integer $n$. Let $v \in F^n$ be such that $A^{n-1}v \ne 0$.  Prove that $\{v, Av, A^2v,...,A^{n-1}v\}$ is a basis for $F^n$.

So, from definition of $A$, I know that $A^iv \ne 0$ for all $0\le i \le n-1$.
I know I need to prove the set is linearly independent and span $F^n$ to prove it's a basis, but I just don't know how.

A: Layout: Suppose the set is linearly dependent.Then there exist scalars $\alpha _0, \ldots, \alpha _{n-1}$ not all null, such that $\alpha _0v+\ldots +\alpha _{n-1}A^{n-1}v=0_{n\times 1}$.
Since not all of them are null, you can take the smallest $j\in \{0,\ldots ,n-1\}$ such that $\alpha_j \neq 0$. (See spoiler below).
This transforms the equality above in something with less terms. Multiply it by an appropriate power of $A$ and find a contradiction.
Spoiler:

Since $\alpha _0= \ldots = \alpha _{j-1}=0$ the equality can be rewritten as $\alpha _jA^jv+\ldots +\alpha _{n-1}A^{n-1}v=0_{n\times 1}$. Now multiply this by $A^{n-j-1}$, (note that $n-j-1\ge 0$). Can you conclude?


text:
Q: unable to merge pr to master after a successful build via jenkins pipeline sh 'git config --global user.name "$ghprbTriggerAuthor"'
    sh 'git config --global user.email "$ghprbTriggerAuthorEmail"'
    checkout changelog: true, poll: true, scm:
      [$class                           : 'GitSCM',
       branches                         : [[name: sha1]],
       doGenerateSubmoduleConfigurations: false,
       extensions                       : [[$class : 'PreBuildMerge',
                                            options: [mergeStrategy: 'DEFAULT', fastForwardMode: 'NO_FF', mergeRemote: 'origin', mergeTarget: 'master']]],
       submoduleCfg                     : [],
       userRemoteConfigs                : [[credentialsId: '<id>', url: 'git@git.xx.com:<repo-name>/<project-name>',name: 'origin',
        refspec: '+refs/pull/*:refs/remotes/origin/pr/*',]]]
        sshagent (credentials: ['<credentialId>']) {
           sh "git status"
           sh "git push origin master"

        }
        sh 'git log -n 10'

jenkin shows  logs as below:

git checkout -f cf1dbfbd9e1f52bf41738884a5c48ab1a59e5104
      [Pipeline] sshagent

[ssh-agent] Looking for ssh-agent implementation...
[ssh-agent]   Exec ssh-agent (binary ssh-agent on a remote machine)
$ ssh-agent
SSH_AUTH_SOCK=/tmp/ssh-eAaXoe8YpGdR/agent.28743
SSH_AGENT_PID=28746

[ssh-agent] Started.
[Pipeline] {
[Pipeline] sh
[Search-UI] Running shell script
+ git status
HEAD detached at origin/master
nothing to commit, working tree clean
[Pipeline] sh
$ ssh-agent -k
unset SSH_AUTH_SOCK;
unset SSH_AGENT_PID;
echo Agent pid 28746 killed;
[ssh-agent] Stopped.
[Search-UI] Running shell script
+ git push origin master
Everything up-to-date

but unable see any changes on git. Is there anything else I need to configure

A:   options: [mergeStrategy: 'DEFAULT', fastForwardMode: 'NO_FF', mergeRemote: 'origin', mergeTarget: ghprbTargetBranch]]]

You have mentioned mergeTarget as "ghprbTargetBranch"

mergeTarget is the branch you wish to merge with.

and
 sh "git push origin $ghprbTargetBranch"

The above two commands aren't matching... you might have mistakenly added the $ in the above command.
If not, then you have mentioned $ghprbTargetBranch i.e. it can/could have a value assigned to it like so
ghprbTargetBranch = master
Based on the logs I'm guessing you are trying to merge to master. If that's the case then you need to change mergeTarget to master.
If not, i.e. mergeTarget= ghprbTargetBranch is the branch that you wish to merge to, then
the sh command i.e. $ghprbTargetBranch (value assigned to it is not ghprbTargetBranch)is probably different.
Hope it helps :)

A: Found the answer as below:
sshagent(credentials: ['<credentialId>']) {
              sh 'git checkout master'
              sh 'git merge --no-ff $sha1'
              sh 'git push origin master'
            }


text:
Q: Turning multiple vector layers into one raster in ArcGIS Desktop? I want to make a raster out of the multitier view I have in ArcMap 9.3.1 .
The layers in my ArcMap come from several datasets.
I know there is a 'Feature to Raster'  tool, but it converts one layer at a time.
Is there a way to convert all of the layers to a raster ( asides from export as jpg, and georeferencing the jpg) ?

A: On the file menu go to export.
There you will select the jpg format and down below on the options tab you select the write world file.


text:
Q: Cannot assign to property 'frame' is a 'let' constant I am stuck with this error in this line:

frame.size = unwrappedController.view.frame.size

This is my first app, please help me if possible.

A: Your frame variable is probably declared using let, which means it cannot be modified once set. Try using var instead of let.


text:
Q: JSTL EL invalid expression(s): javax.el.ELException: in Tomcat 7 I'm trying to get this old JSP project running in Tomcat 7, JRE7 but getting this error in most of the pages in the project. Can any  one please shed some light whats happening?
The code looks like:
<c:set var="structClass">
    <c:if test="${empty param.class}">template</c:if>
    <c:if test="${not empty param.class}">${param.class}</c:if>
</c:set>

The error looks like:

org.apache.jasper.JasperException: javax.servlet.ServletException: javax.servlet.jsp.JspException: org.apache.jasper.JasperException: /WEB-INF/templates/template.jsp (line: 77, column: 4) "${empty param.class}" contains invalid expression(s): javax.el.ELException: Failed to parse the expression [${empty param.class}]
  org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:585)
  org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:455)

A: it is because of 'class' keyword in the expression try to use
<c:if test="${empty param['class']}">template</c:if>
<c:if test="${not empty param['class']}">${param['class']}</c:if>

refer http://geekomatic.ch/2011/03/22/1300804080000.html


text:
Q: DataTables sort by number by default I am pulling some data from my back end, and showing them in a DataTables table. The problem is that it doesn't sort its rows based on the appending number at the end, which is what I'm trying to do. I am pasting a screenshot of the problem. Any help appreciated.

EDIT: This way I am providing the JSON to DataTables
$finalTableSQL = "select * from players_data where store = $store";
$finalTableResult = $mysqli->query($finalTableSQL);
$rows = array();
while ($row = $finalTableResult->fetch_array(MYSQLI_ASSOC)) {
    $rows[] = $row;
}

$returnToCashier = [];
$returnToCashier["data"] = [];
foreach ($rows as $finalTableRows) {
    $playerID = (int) $finalTableRows["user_id"];
    $playerEmail = $userRow["email"];
    $lastintype = (int) $finalTableRows["last_in_type"];
    $lastIN = (float) $finalTableRows["last_in"] / 100;

    if ($lastintype == 0) {
        $intype = "Cash";
    } else if ($lastintype == 1) {
        $intype = "Privilege";
    } else {
        $intype = "Bonus";
    }

    $canCashOut = (int) $finalTableRows["can_cash_out"];

    if ($canCashOut == 0) {
        $credits = "" . ((float) $finalTableRows["credits"] / 100) . " €";
    } else {
        $credits = ((float) $finalTableRows["credits"] / 100) . " €";
    }

    $playeruserSQL = "select * from directus_users where id = $playerID";
    $playeruserResult = $mysqli->query($playeruserSQL);
    $playeruserRow = $playeruserResult->fetch_array(MYSQLI_ASSOC);

    array_push($returnToCashier["data"], [
        "username" => str_replace("@mail.com", "", $playeruserRow["email"]),
        "credits" => $credits,
        "lastintype" => $lastIN . " € " . $intype,
        "lastplayed" => $finalTableRows["last_played"],
        "playerid" => $playerID,
    ]);
}

echo json_encode($returnToCashier);

And this way I'm showing the JSON to the front end:
var table = $('#playerstable').DataTable({
    "fnDrawCallback": function(data) {
        $(".paginate_button > a").on("focus", function() {
            $(this).blur();
        });
    },
    "ajax": "/frontend/cashierusers.php?token=" + sessionStorage.getItem('JWT'),
    "columns": [{
            "data": "username"
        },
        {
            "data": "credits"
        },
        {
            "data": "lastintype"
        },
        {
            "data": "lastplayed"
        },
        {
            "data": "playerid"
        },
    ],
    "autoWidth": false,
    rowReorder: false,
    responsive: true,
    language: {
        search: "_INPUT_",
        searchPlaceholder: "Search..."
    }
});

A: You can combine the following techniques:
1 - Create a hidden column containing only the numeric portion of each value.
2 - Use the orderData option to allow your visible column to be sorted by the data in the hidden column.
In my test case, I am loading my data from a JavaScript variable, not from an ajax URL - but otherwise the approach would work the same way for you:
My test table:

            ID
            hidden column

The DataTable:
  var dataSet = [
    {"playerid": "rodplayer25"},
    {"playerid": "rodplayer10"},
    {"playerid": "rodplayer2"},
    {"playerid": "rodplayer1"}
  ];

  $(document).ready(function() {

    var table = $('#example').DataTable( {
      "data": dataSet,
      "columnDefs": [
        {
          "targets": [ 0 ],
          // use the data in the 2nd (hidden) column for ordering this column:
          "orderData": [ 1 ],
          "data": "playerid"
        },
        {
          "targets": [ 1 ],
          "visible": false,
          "data": function ( row, type, val, meta ) {
            // populate this column with only the trailing number:
            return parseInt(row.playerid.split(/([0-9]+)/)[1]);
          }
        }
      ]
    } );

  } );

This will display your original "rodplayer" data values. But when you sort on that column, it will use the numeric data extracted from the end of each string.
The regular expression I use (/([0-9]+)/) assumes the numeric data always occurs at the end of each value. So, as long as your data never deviates from this format, the regex will work as expected.


text:
Q: dialogflow context vs. intent - Design Choice I started working with Dialogflow a couple of weeks ago. It's nice to learn the concept of intent and (input/output) context through which Google models and defines the daily conversation flow in natural language. I understand how intent and context work at the current setting. But to me the function of context can be achieved by only using intent. You may argue whether the word 'intent' is proper for this usage but it's another discussion. So instead of input and output context just do input and output intents. In the implementation make sure the parameters and information of current conversation is carried to the following intent. And the following intent has again its output intent and the talk continues.
Can anyone correct me if I'm wrong?

A: Intents represent a user action, typically what a user says, including the parameters from that specific utterance.
Contexts serves two purposes:

*

*Hold the parameters from an Intent or that have been set through Fulfillment for some period of time.

*When used as an Input Context, limit what Intents can be triggered.

While you can certainly "send the parameters forward" from one Intent to another, this is a very linear way of thinking, and rapidly falls apart in complicated conversations. Using Contexts to store parameters and other info, as the first bullet suggests, makes this a lot easier, so your user can wander around in the conversation, and yet you are still maintaining the overall state.
As for the second bullet, this is used to change how we understand what the user has said based on other parts of our conversation. (This matches how humans handle conversations.)
So my response saying "Yes" means different things depending if I'm asking to delete a message or send a message - Contexts help us manage that.


text:
Q: Is this real google bot or attack? How do I deal with it? So basically my site was unaccessible and I went to logs folder to see what's wrong and noticed a lot of weird requests from various IPs:
155.4.117.13 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
185.220.100.252 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
155.4.117.13 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
185.220.100.252 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
155.4.117.13 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
155.4.117.13 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
155.4.117.13 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
155.4.117.13 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
155.4.117.13 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
162.247.74.206 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
162.247.74.206 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
162.247.74.206 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
162.247.74.206 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
185.220.100.252 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
155.4.117.13 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
162.247.74.206 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
209.141.45.189 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
155.4.117.13 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
155.4.117.13 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
185.220.100.252 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
185.220.100.252 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
185.220.100.252 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
162.247.74.206 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
162.247.74.206 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
185.220.100.252 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
209.141.45.189 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
185.220.100.252 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
185.220.100.252 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
155.4.117.13 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
185.220.100.252 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
185.220.100.252 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
155.4.117.13 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
185.220.100.252 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
185.220.100.252 - - [30/Mar/2020:20:23:45 +0300] "GET / HTTP/1.0" 200 6189 "-" "Google Bot"
185.220.100.252 - - [30/Mar/2020:20:23:56 +0300] "GET / HTTP/1.0" 200 6344 "-" "Google Bot"
209.141.45.189 - - [30/Mar/2020:20:23:56 +0300] "GET / HTTP/1.0" 200 6344 "-" "Google Bot"
162.247.74.206 - - [30/Mar/2020:20:23:56 +0300] "GET / HTTP/1.0" 200 6344 "-" "Google Bot"
155.4.117.13 - - [30/Mar/2020:20:23:56 +0300] "GET / HTTP/1.0" 200 6344 "-" "Google Bot"

I wonder if it's some kind of attack.
Did some whois lookup, for example this ip 185.220.100.252 is from Germany, "tor-exit-1.zbau.f3netze.de"
How can I protect server from such attacks?
They do like thousand of requests per minute and I can't access my own site.
Error.log says:
AH00161: server reached MaxRequestWorkers setting, consider raising the MaxRequestWorkers setting
(I'm not a webmaster, I host a small site for my needs and have no idea how to react.)

A: This is exactly the scenario that fail2ban was invented to cover. I suggest you look into that here: https://www.fail2ban.org/wiki/index.php/Main_Page
Likely the "badbots" jail would take care of this immediately, and if not it wouldn't be difficult to code a custom jail/filter set to take care of it.
For now, seeing how they IP's seem to be limited, I suggest banning those IP's via iptables:
iptables -I INPUT -s 185.220.100.252 -j DROP

This is what fail2ban does of course (adds IP's to iptables), but fail2ban does it automatically. It would have protected you from this attack without your even noticing.


text:
Q: How would I solve for the bases of an isosceles without the height? In the image below if you were to take 36 degrees and set it between 0-180 degrees how would you solve for the bases between points AC. There are special cases for the bases length such as (60 degrees where the length is 5) and (180 degrees where the length is 10). However a problem arises when (90 degrees where the length is 7.07) that when doubled is (180 degrees where the length is 14.14). Why is that?
Isosceles triangle with no base or height
I have also looked online but have found no articles or solutions to this specific problem. I want to have a better understanding so what do you suggest?

A: You can use trigonometry to determine the base. Denote the midpoint created by the altitude of the triangle point $D$.
Since triangle $ABD$ is right, we may apply our trigonometric formulae. Specifically, we know that $\sin 18^{\circ}=\frac{AD}{5}$. I found $18^{\circ}$ because the altitude bisects the top angle of the triangle.
From this relationship, can you solve for $AD$? Then, can you solve for the total length of the base, knowing that $AD$ is one half of $AC$?
EDIT: If you want to express $\sin 18^{\circ}$ as radicals, it can be shown that $\sin 18^{\circ}=\frac{1}{4}(\sqrt{5}-1).$

A: A $36-72-72$ triangle is a special case involving the golden ratio.
That is, the ratio of base to height is $1:\frac{1+\sqrt5}{2}$.
Therefore, the base length is the following:
$$\frac{10}{1+\sqrt 5}$$

A: Without trig:

You know $|AB|=|BC|=5$ and seek $x=|AC|$. (From there, the height is easy to find using the Pythagorean theorem.)
Extend $AC$ and place $D$ and $E$ on it, so that $\measuredangle BDA = \measuredangle CEB = 36^\circ$. Notice, now, that the triangles $\triangle BAD$ and $\triangle DBE$ are similar, as they both have angles $36^\circ,36^\circ,108^\circ$.
This means that the ratios $\frac{|BD|}{|DE|}$ and $\frac{|AB|}{|BD|}$ are equal.
Notice, also, that $\triangle BCD$ is isosceles, so $|BD|=|CD|=|AC|+|AB|=x+5$.
The triangles $\triangle BAD$ and $\triangle BEC$ are isosceles, so $|DA|=|AB|=5$ and $|CE|=|BC|=5$. Thus, $|DE|=|DA|+|AC|+|CE|=x+10$.
So we have: $\frac{x+5}{x+10} = \frac{5}{x+5}$ or $x^2+5x-25=0$.
The only positive root of this quadratic equation is $x=\frac{5 \sqrt 5 - 5}2$.


text:
Q: mingw32-g++: 'std::tr1' has not been declared I'm facing this issue using Code::Blocks 16.01, everything works perfectly in Visual Studio 2015. The compiler option "Have g++ follow the C++11 ISO C++ language standard [-std=c++11]" is enabled, and the build log is:
mingw32-g++.exe -Weffc++ -std=c++11 -g  -c "<path>\heuristic.cpp" -o .objs\heuristic.o
In file included from <path>\METSlib\metslib-0.5.3\metslib\mets.hh:129:0,
                 from <path>\Model.h:2,
                 from <path>\<file>,
                 from <path>\<file>:
<path>\METSlib\metslib-0.5.3\metslib\model.hh: In function 'void mets::random_shuffle(mets::permutation_problem&, random_generator&)':
<path>\METSlib\metslib-0.5.3\metslib\model.hh:252:10: error: 'std::tr1' has not been declared
     std::tr1::uniform_int<size_t> unigen;

followed by lots of other errors, all related to the missing std::tr1 library. (I've replaced some paths and files with placeholders for privacy)
What am I missing in the compiler configuration?


text:
Q: Calculating Aggregated Weighted Sum in a Step function I have a dataframe that looks like this:
I have appended an aggregated row at the end, that calculates the mean of the column, while ignoring null values. See my code here:
repayments_amt_pivot.loc['Aggregated'] = repayments_amt_pivot.iloc[:, 3:].mean(skipna=True)

However, instead of a simple mean for the aggregated row, I actually need to calculate a weighted sum of the percentages multipled by the proportion in principal_due_per_month.
In this case, for Month 4, row 0 would be multipled by (27,845 / 27,845 + 310,506 + 659,705 + 1,433,121).
For Month 3, row 4 would be multiplied by (1,941,036 / 27,845 + 310,506 + 659,705 + 1,433,121 + 1,941,036)
etc.
Any help would be greatly appreciated as I cannot figure this one out!
See the following for screenshots of how to calculate in excel.
Data:
    pd.DataFrame([{'$ Amount Due': 27845.312793586978,
  'Month 0': 56.479872661140476,
  'Month 1': 92.94027983726657,
  'Month 2': 100.00000000000003,
  'Month 3': 100.00000000000003,
  'Month 4': 100.00000000000003},
 {'$ Amount Due': 310505.5597382864,
  'Month 0': 78.34839385064039,
  'Month 1': 79.58303224427453,
  'Month 2': 79.58303224427453,
  'Month 3': 81.43498983472573,
  'Month 4': 92.54673537743292},
 {'$ Amount Due': 659705.2173778547,
  'Month 0': 90.79718901057414,
  'Month 1': 97.8418387417451,
  'Month 2': 97.85768670717538,
  'Month 3': 97.85768670717538,
  'Month 4': 97.85768670717538},
 {'$ Amount Due': 1433121.318250646,
  'Month 0': 91.7207168764003,
  'Month 1': 94.34283888419282,
  'Month 2': 94.51326381568556,
  'Month 3': 94.8581612152927,
  'Month 4': 94.91544740629973},
 {'$ Amount Due': 1941036.1276433321,
  'Month 0': 79.75029644420579,
  'Month 1': 85.62252846197367,
  'Month 2': 86.59251760542142,
  'Month 3': 86.70920561577343,
  'Month 4': np.nan},
 {'$ Amount Due': 3448302.2801859295,
  'Month 0': 75.83697471065258,
  'Month 1': 83.6700011095642,
  'Month 2': 86.16217213969533,
  'Month 3': np.nan,
  'Month 4': np.nan},
 {'$ Amount Due': 3190042.0279137697,
  'Month 0': 76.69574360823212,
  'Month 1': 85.4625418697537,
  'Month 2': np.nan,
  'Month 3': np.nan,
  'Month 4': np.nan},
 {'$ Amount Due': 2614440.2956102462,
  'Month 0': 74.87175589142862,
  'Month 1': np.nan,
  'Month 2': np.nan,
  'Month 3': np.nan,
  'Month 4': np.nan}])


text:
Q: What are the differerences between the new Ada sub-pool features and pools of pools? I recently read the 2012 rationale portion on iterators and pools. One of the things overviewed is the new abilities concerning subpools, one question that was unanswered is what's the difference between subpools and pools of pools - I mean it seems the same [as pg.25] could rather be achieved like this:
-- Minnesota: Land of 10,000 Lakes
type Minnesota(Size: Storage_Count) is new Root_Storage_Pool with private;
type Lake(Size: Storage_Count) is new Root_Storage_Pool with private
     with Storage_Pool => Minnasota;
-- ...
type Pooled is [...] with Storage_Pool => Lake;

Though I admit I might be horribly wrong, as I haven't used sub-pools, much less pools (yet).

A: From Randy Brukardt of Comp.Lang.Ada.

Aspect Storage_Pool only applies to access types (13.11(15) and
  others), and type Lake is not an access type, so this is illegal (and
  makes no sense as well).
You could implement one pool by putting other pools within its
  implementation (say Minnesota here including a an array of 10000 Lakes
  :-). But you'd then have to have a way to select which item belongs to
  each, ahem, subpool. And you'd be reinventing the wheel.
There is also the issue of finalization. The subpool mechanism ensures
  that objects don't outlive their subpool (pointers to the objects
  might outlive the subpool, but not the object themselves), even when
  the subpool is explicitly destroyed early (just as
  Unchecked_Deallocation does). There's no good way to do that without
  language support (every hand-written subpool implementation that we
  talked about insisted that no controlled, protected, or task objects
  be allocated from it, which is obviously limiting).
Let me assure you, getting this right was hard and contentious. It was
  nearly dropped a couple of times. Doing it yourself wouldn't be
  contentious (I hope!), but it would still be hard. Since the ARG has
  already done the dirty work, it's best to use it.
                                            Randy.


text:
Q: Definition of Derivative of Matrix Let's assume A is $n\times 1$ constants, $X$ is $n\times 1$ vector. Does derivative of transpose(A)* X on X should be transpose(A) instead of A?
I saw both transpose(A) and A from different resources and would like to confirm the right answer.

A: For simplicity, let me write by $A^t$ the transpose of $A$.
I'm assuming that you're asking about the derivative of the function: $\mathbb{R}^n \to \mathbb{R} : X \mapsto A^t X$ ?
Short answer: the derivative is the same map: $(\mathbb{R}^n \to \mathbb{R} : X \mapsto A^t X)$, in other words, $A^t$
Slightly longer answer: for any linear map $B : \mathbb{R}^n \to \mathbb{R}^m$, its derivative is itself (ie, it's the same map $\mathbb{R}^n \to \mathbb{R}^m$). The reason for that is because the derivative $Df_x$ of a map $f$ at $x \in \mathbb{R}^n$ is defined as the (unique) linear map  which gives a first-order Taylor approximation, ie, such that:
$f(x + \varepsilon) = f(x) + Df_x(\varepsilon) + O(\varepsilon^2)$ for any small $\varepsilon \in \mathbb{R}^n$.
When $f = B$ is linear, then we can choose $Df$ to be $B$ itself, and unicity guarantees that it's the only choice, so that the derivative of any linear map is itself.


text:
Q: Accessing Google Calendar using a public/private calendar link in GData (no hardcoding the passwords) I'm currently creating an app that will access a company's google calendar and display the event information in a table. I would like to be able to access this calendar without hardcoding the credentials using statements such as:
[googleCalendarService setUserCredentialsWithUsername:username password:password];

I was reading up on Google's API console and how you can create an OAuth 2.0 client ID to access information. Would this be the most secure way to access it and does GData for iOS support this? How would I go about integrating it? Besides that I was also looking into just reading the calendar from a public/private address. This seems to be giving me more than a hassle though as I'm just receiving errors when attempting to use the provided public/private addresses from the calendar with the method: [googleCalendarService fetchPublicFeedWithURL:calendarURL feedClass:[GDataFeedCalendar class] delegate:self didFinishSelector:@selector(calendarsTicket:finishedWithFeed:error:)];


text:
Q: Prym varieties as Jacobian varieties A generic abelian variety of dimension 2 or 3 is a jacobian of a curve.
Is there a canonical way to determine a curve whose jacobian is a prym variety of a unramified double cover of a curve of genus 3 or 4?

A: Yes, assuming you mean a way to go from the double cover to the curve, (rather than how to go from the Prym variety to the curve, which is just a constructive Torelli argument).  This is based on the fact that curves of genus 3 and 4 are "trigonal", i.e. admit a degree 3 map to the projective line.  The corresponding "trigonal construction" is attributed to S. Recillas who apparently generalized work of Roth, and it may have antecedents in the work of Wirtinger.  An excellent reference is Beauville's paper:
http://math.unice.fr/~beauvill/pubs/specprym.pdf
Basically, a double cover C-->D, where D is trigonal of genus g+1, induces a map of degree 8 on the corresponding third symmetric products of these curves.  By definition, that of D contains a projective line, whose preimage in the 3rd symmetric product of C, and modulo the induced involution, is a tetragonal curve E of genus g.  The Jacobian of E is isomorphic to the Prym variety of C-->D.
In fact the preimage curve in the symmetric cube of C, is a disjoint union of two copies of E, and both embed via the Abel map into copies of the Prym variety of C-->D, realized as the inverse image in Pic^3(C), of the g(1,3) on D. Then Beauville calculates the homology classes of those embedded curves and applies the criterion of Matsusaka.  Recillas himself gave an argument based on Hurwitz schemes.
The link with classical projective geometry is via the "complete quadrangle" or "complete quadrilateral".  (These objects had apparently been studied by Wirtinger and Roth.)  Note that 4 general points determine 3 pairs of distinct diagonals, hence three points of intersection of such pairs, together with a "double cover" of the triple consisting of the 6 diagonals.  On the canonical model of a tetragonal curve E there is a pencil of coplanar 4-tuples of points, hence also another trigonal curve D swept out by the associated pencil of coplanar triples of intersection points.  This curve D is presumably the Prym canonical model of the curve D associated to the double cover C-->D by the curve C of diagonals.
Here is a relevant classical reference:
 Roth P., U ̈ber Beziehungen zwischen algebraischen Gebilden vom Geschlecht drei und vier, Monatsh. fu ̈r Math. und Phys., 22, (1911), 64–88.
And some more recent ones:
http://www.math.lsa.umich.edu/~idolga/rat3.pdf
http://link.springer.com/article/10.1007/BF01766014#page-1


text:
Q: How to Track State Change of Newly Added Values Let's say I have a grocery list where the title of the item, and the quantity is listed. Let's say I found 1 carton of milk, and need 2. So I update the list so that I only need to find one more carton of milk. If I know the contents of the list, I can use state to track each item and re render the list. The issue is, what if I need to add new items. How can I use state to track an unlimited number of newly added values. I've found examples of how to do this but I was wondering what's the most efficient way to do so.
Ex:
Eggs 2

Milk 2

Carrots 5

Found a milk carton so I update the milk quantity to 1. List is re rendered.
Eggs 2

Milk 1

Carrots 5

But now I add a new value as apples. How do I track apples now? How do I re render it when the value is changed if the state isn't being tracked from the beginning.
Eggs 2

Milk 1

Carrots 5

Apples 2 <-- How do I track this items state / re render the list when it changes

A: if data is coming from API then you have to refresh or re-call your method after certain time interval. Only you have to make sure that the user is not making any change on in Flat-list(not performing any action on it). here is the sample code to set intervals
componentDidMount()
  {
   this._interval = setInterval( () => {this.DataReload()}, 180*1000);

  } ;

componentWillUnmount()
  {
   clearInterval(this._interval);
  };

 DataReload =()=>{
 //here your code and call you API. update your state data, when the state is changed then your flat-list automatically re-render.
}


text:
Q: ffmpeg default audio codec instead of specifying it with acodec option In raspberry pi I've following i2s microphone breakout board and use it like the guide suggested. When I try record audio from it using ffmpeg to the file with ffmpeg -f alsa -i dmic_sv out.wav command. I'll receive following error
[alsa @ 0x22e21c0] cannot set sample format 0x10000 2 (Invalid argument)
dmic_sv: Input/output error

When I specify the used codec explicitly with -acodec it works fine:
ffmpeg -f alsa -acodec pcm_s32le -i dmic_sv out.wav

And from the output ffmpeg will reencode to pcm_s16le
Input #0, alsa, from 'dmic_sv':
  Duration: N/A, start: 1597597938.887969, bitrate: 3072 kb/s
    Stream #0:0: Audio: pcm_s32le, 48000 Hz, stereo, s32, 3072 kb/s
Stream mapping:
  Stream #0:0 -> #0:0 (pcm_s32le (native) -> pcm_s16le (native))

How I can tell ffmpeg to use signed 32-bit little endian by default without specifying it explicitly? And where ffmpeg gets this default and can I configure it somehow?

A: I figured this one out myself by reading ffmpeg source code. It seems when codec is not specified and alsa device is used. FFmpeg will default to pcm 16-bit samples instead. Code to set the default here and the default macro here.


text:
Q: Difference between refresh_token and access_token
I can't find any reason why to use refresh_token. when we can make
  access_token longed lived...
Why do we have both?

A: As you have JWT as a tag on your question I will assume you are referring to Json Web Tokens
The following was referenced from
Refresh Tokens: When to Use Them and How They Interact with JWTs

*

*Access tokens carry the necessary information to access a resource directly. In other words, when a client passes an access
  token to a server managing a resource, that server can use the
  information contained in the token to decide whether the client is
  authorized or not. Access tokens usually have an expiration date and
  are short-lived.

*Refresh tokens carry the information necessary to get a new access token. In other words, whenever an access token is required to
  access a specific resource, a client may use a refresh token to get a
  new access token issued by the authentication server. Common use cases
  include getting new access tokens after old ones have expired, or
  getting access to a new resource for the first time. Refresh tokens
  can also expire but are rather long-lived. Refresh tokens are usually
  subject to strict storage requirements to ensure they are not leaked.
  They can also be blacklisted by the authorization server.

This second reference is also an interesting read re the short-lived access token and  long-lived refresh token.
Why Does OAuth v2 Have Both Access and Refresh Tokens?

revocation: if the access token is self contained, authorization can be revoked by not issuing new access tokens. A resource does not
  need to query the authorization server to see if the access token is
  valid.This simplifies access token validation and makes it easier to
  scale and support multiple authorization servers. There is a window of
  time when an access token is valid, but authorization is revoked.

Hope this helps.


text:
Q: Handle the request param dynamically with Jackson library I have a rest controller which has a GET request and the request param could be of any type which is more dynamic i would say. I would like to map the request param to an appropriate child class based on the data we get from user.
BaseRequest Class is `
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
        @JsonSubTypes.Type(value = RequestA.class, name = "RequestA"),
        @JsonSubTypes.Type(value = RequestB.class, name = "RequestB")
})
@Data
@NoArgsConstructor
public class BaseRequest {
    private String error;
}

RequestA class is
@Data
@JsonTypeName("RequestA")
@NoArgsConstructor
public class RequestA extends BaseRequest {
    private String token;
}

`
RequestB is `
@Data
@JsonTypeName("RequestB")
@NoArgsConstructor
public class RequestB extends BaseRequest {
    private String id;
}

`
My controller is `
@GetMapping(value = "/request", produces = MediaType.APPLICATION_JSON_VALUE)
    public String request(BaseRequest request)

`
The request would look like
1)http://localhost:8080/request?token=abc&error=test
2)http://localhost:8080/request?id=abc
It doesnt seem working. I only get info for Base class at controller.

A: If you're using GET it won't use JSON, you could write
@GetMapping(value = "/request", produces = MediaType.APPLICATION_JSON_VALUE)
 public String request(@RequestParam(required = false) String token,
 @RequestParam(required = false) String id, @RequestParam(required = false) String error) {
  //Initialize request A if token is not null else request B or add your custom control
}

if you need more params with different purposes you could create a custom object to be passed in a POST body and then, based on your needs, make the correct call.


text:
Q: Get all inputs from a submitted form I have a form that has no id, no class whatsoever. I need to get all the inputs that are inside it, I have a script but it will get all inputs no matter if they are inside my form or not.
Of course I could add classes, id's to my forms but is there any way of doing what I want without adding identifiers to my form?
It is only logical that in my case it will iterate trough every input on my page, but how can I make sure it will only iterate trough every input on current form?
$('form').submit(function(e){
    e.preventDefault();

    $('input, textarea').each(function(){
        alert('a'); // Alerts on every input, not just inside this form...
    });
});

Fiddle: http://jsfiddle.net/dsN43/

A: You can pass this as context (second parameter) to jQuery function to search only inside current element.
$('form').submit(function(e){
    e.preventDefault();

    $('input, textarea', this).each(function(){
        alert('a'); // Alerts on every input inside this form.
    });
});

A: $('form').submit(function(e){
    e.preventDefault();

    $(this).find('input, textarea').each(function(){
        alert('a'); // Alerts on every input, just inside this form
    });
});

A: You can use the jQuery find() method like this: (it's better for debugging to print the tagName / name attributes of your elements, to make sure you find the right ones)
$(document).ready(function(){
    $('form').submit(function(e){
        e.preventDefault();

        $(this).find('input, textarea').each(function(){
            alert(this.nodeName + ' ' + $(this).attr('name'));
        });
    });
});

jsFiddle example


text:
Q: Filter json data by boolean value in PostgreSQL I'm trying to filter json-data in cell by boolean values
Everything just fine when I filtering just by numeric values:
select id,
       jsonb_path_query(terminals->'terminal',
                        '$ ? (@.maxLength >= $length)',
                        '{"length": 1.0}') as terminals
FROM public.table;

And when I'm trying to filter by boolean value:
select id,
       jsonb_path_query(terminals->'terminal',
                        '$ ? (@.boolValue == TRUE && @.maxLength >= $length)',
                        '{"length": 1.0}') as terminals
FROM public.table;

I get it:
ERROR:  syntax error, unexpected IDENT_P at or near " " of jsonpath input
LINE 1:  jsonb_path_query(terminals->'terminal', '$ ? (@.boolValue...
                                                 ^
SQL state: 42601


text:
Q: How to parse facebook api XML online to retrieve 'like' count? I've located a method of retrieving an XML file online via api.facebook.com which contains the number of likes a given page has received. For example:
https://api.facebook.com/method/fql.query?query=select%20like_count%20from%20link_stat%20where%20url=%27http://mashable.com/2011/03/21/google-chrome-icon/%27&format=xml
However, I'm not sure how I can parse that XML in my PHP application to then extract the 'like' number and place it into a variable to use myself.

A: You can use the built-in simplexml_load_file() but since it doesn't work with HTTPS you can use CURL and simplexml_load_string() function.
<?php
$url = "https://api.facebook.com/method/fql.query?query=select%20like_count%20from%20link_stat%20where%20url=%27http://mashable.com/2011/03/21/google-chrome-icon/%27&format=xml";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
$xml = simplexml_load_string($data);
print_r($xml);
?>


text:
Q: Updating a form's select element's selectedIndex property, updates the value, but doesn't change the selected option in the page Here is the code:
const formClubSelect: HTMLSelectElement | null = document.getElementsByTagName('select',)[1] as HTMLSelectElement;
if (formClubSelect) {
    for (var i = 0; i < formClubSelect.options.length; i++) {
        const option = formClubSelect.options[i];

        if (option.value === clubId && option.text === clubName) {
            formClubSelect.selectedIndex = option.index;
            formClubSelect.options[option.index].selected = true;
        }
    }
}

The option's can sometimes have the same value, so I'm looping through them and checking the value/text based on some previous values. If the values match the option ones, I try to set the index on the select element, as well as set the selected property on the option to true. I've tried setting just the option selected property, but it doesn't seem to change anything.
I've also checked the index before and after the change and it does update, but the option doesn't appear on the select:

HTML:
<select name="__field_349914" id="45eafcb7-97d1-4889-bd09-2ceceb954508" required="" aria-required="true" data-f-datainput="" aria-describedby="__field_349914_desc" aria-invalid="false">
      <option disabled="disabled" selected="selected" value="">-- Select an option --</option>
      <option value="02847" data-f-datainput="">1</option>
      <option value="02771" data-f-datainput="">2</option>
      <option value="03181" data-f-datainput="">3</option>
      <option value="02810" data-f-datainput="">4</option>
      <option value="02832" data-f-datainput="">5</option>
 </select>


text:
Q: Удаление пустых строк в конце текстового файла Java Нужно было реализовать логику для замены строки в текстовом файле.Применял разные схемы, но остановился на самом лаконичном, как мне кажется:
try {
        Files.write(Paths.get(fileName), Collections.singleton(new String(Files.readAllBytes
                                (Paths.get(fileName))).replace(searchString, replaceString)));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

Все получается хорошо. Но, - после изменения заданной строки, - в конце файла добавляется пустая строка. При добавлении в файл, эта пустая строка мешает,  - не соблюдаются отступы от предыдущего текста, приложение "ругается". Помогите побороть эти пустые строки. По всей видимости, они содержат какой-то tab...

A: Ответ найден. Просто мне нужно внимательнее читать stackoverflow... Нужно использовать
RandomAccessFile f = new RandomAccessFile(fileName, "rw");


text:
Q: Ignore push notifications when iOS app is in the foreground I have a fairly large iOS project. When the app receives a notifications while in the foreground, the notification is displayed in something that looks like an AlertView. I want to get rid of it. I have no idea if this is something I programmed myself a long time ago, or if one of the frameworks in the project (Parse, Onesignal, FBSDK) is doing this. My question is, how can I find out where that alert view is coming from, so I can remove that code. I have not implemented the willPresentNotification method anywhere (I have searched through the entire project). I do have a didReceiveRemoteNotification method, and even though that should only be called when a notification is tapped, I have tried commenting it out. I have also searched through the entire project for UIAlertView and UIAlertController, to no avail.

A: OneSignal SDK automatically uses the new UserNotifications Framework, when iOS10 is detected on device.
In this case, the AppDelegate method didReceiveRemoteNotification method not get called, instead methods in UNUserNotificationCenterDelegate get invoked, which is captured by SDK to record clicks/views.
OneSignal use callback to handle received Notification.

*

*OSHandleNotificationReceivedBlock: Called when the app receives a notification while in focus only

*OSHandleNotificationActionBlock: Called when the user opens or taps an action on a notification.

*OSNotificationOpenedResult: The information returned from a notification the user received.
You can directly implement UNUserNotificationCenterDelegate methods to handling notification-related interactions in your app.


text:
Q: How to compute the limit of $\lim_{n\to \infty}\left(1-e^{-nk}\right)^n$ for $k>0$ a constant? I am wondering how I can  compute the limit of $\lim_{n\to \infty}\left(1-e^{-nk}\right)^n$ for $k>0$ a constant. I want to think L'Hospital's rule would work here but am unable to get it. Is there an easy trick here?

A: Hint: Using Bernoulli's inequality
$$1 \geqslant \left(1-e^{-nk}\right)^n \geqslant 1 - n (e^{-k})^n$$

A:
METHODOLOGY $1$:  Apply L'Hospital's Rule

If one wishes to use L'Hospital's Rule, then one can proceed by writing
$$\begin{align}
\lim_{n\to \infty}\left(1-e^{-kn}\right)^n&=\lim_{n\to \infty}e^{n\log\left(1-e^{-kn}\right)}\tag 1\\\\
&=e^{\lim_{n\to \infty}n\log\left(1-e^{-kn}\right)}\\\\
&=e^{\lim_{n\to \infty}\frac{\log\left(1-e^{-kn}\right)}{1/n}}\\\\
&=e^{\lim_{n\to \infty}\frac{-kn^2}{e^{kn}-1}}\\\\
&=e^{0}\\\\
&=1
\end{align}$$

METHODOLOGY $2$:  Apply Elementary Inequalities and the Squeeze Theorem

Alternatively, we can use the fact that the logarithm function satisfies the inequalities SEE THIS ANSWER

$$\bbox[5px,border:2px solid #C0A000]{\frac{x-1}{x}\le\log(x)\le x-1 }\tag 2$$

Using $(2)$ in $(1)$ we have
$$e^{\frac{-ne^{-kn}}{1-e^{-kn}}}\le e^{n\log\left(1-e^{-kn}\right)}\le e^{-ne^{-kn}}$$
whence application of the squeeze theorem yields the coveted limit.


text:
Q: Can't access bios on Sumsung np 900 x3c Can't access UEFI setup after installing linux.
My steps were.

*

*Go to the EFI setup program (firmware) turn off fast boot and secure boot.

*Choose CSM only.
Then I was able to boot from USB flashdrive.

*I remove all windows partitions and install elementary os.

Right now I can access firmware or choose boot device. On startup I have Samsung logo and a title at the bottom "F2-Setup F4-Recovery".
But any of F buttons doesn't doo anything. I just see grub page with elementary os.

A: Try one of these:

*

*Before the power comes on. Press and hold the F2 button. Do not let up, then press on.

*Download the last bios update from Samsung Official Site.

*Remove the battery and hold the ON button for 1-2 min.

*The last option to remove the CMOS battery, wait for 1 min then replace it again.


text:
Q: CodeIgniter - How to hide index.php from the URL This is what my .htaccess looks like. The .htaccess is sitting in /www/scripts directory which is the parent of codeigniter's system directory and which also contains index.php. I have enabled mod_rewrite in my Apache 2.2.x. This is on Ubuntu 9.10 server.
I followed this link, but it does not work. Is there anything I need to do in apache2, any specific configuration so that this works?
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [QSA,L]

A: use this:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /folder/index.php/$1 [L]

A: Just toss the following code into your .htaccess file
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]

Source: http://codeigniter.com/user_guide/general/urls.html

A: here is the solution simply drop in root.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]

A: CodeIgniter User Guide on URLs


text:
Q: How to get a list of child nodes and iterate over them My question is how do I obtain the children nodes for a parent node. My reason for doing this is I have two elements that have the same tag
and I want to display all the elements for the children nodes. I am new to XML Parsing so I don't know that much, I have been using a DOM Parser.
I have the following xml file
<Employees>
    <Employee id=12121>
        <Name> John </Name>
        <Profession> Programmer </Profession>
        <Age> 26 </Age>
    </Employee>
    <Employee id=121212>
        <Name> Jack </Name>
        <Profession> Analyst </Profession>
        <Profession> Team Lead </Profession>
        <Age/>
    </Employee>
    <Employee id=121241>
        <Name> Emma </Name>
        <Profession> Risk Analyst </Profession>
        <Age> 29 </Age>
    </Employee>
</Employees>

I want to get a list of the children  nodes for each Employee node
I have tried the following code in java
/*The code above simple creates a DOM Builder I havent included it in*/
NodeList nList = dc.getElementsByTagName("Employee");
for (int i=0; i<nList.getLength(); i++){
    Node nNode = nList.item(i);
    NodeList childNodeList = nNode.getChildNodes();

}

The Sample output looks this
John profession is Programmer and is aged 26
Jack profession is Analyst and  team lead
Emma profession is Risk Analyst and is aged 29

A: Your code looks good.Whats your doubt?
try this, n1 is the NodeList
    for(int i=0;i<nl.getLength();i++){
        Node n=nl.item(i);
        if(n.getNodeType()==Node.ELEMENT_NODE){
           System.out.println(n.getNodeName()+"\t"+n.getTextContent());
        }
    }


text:
Q: sp::proj4string(obj) : CRS object has comment, which is lost in output in R I am trying to plot a map using tmap library:
library("rgdal")
library("tmap")
area_dnipro <- readOGR("dnipro.shp", encoding = "UTF-8", use_iconv=TRUE)
tm_shape(area_dnipro) + tm_polygons()

But during plotting I am getting this message:
Warning message:
In sp::proj4string(obj) : CRS object has comment, which is lost in output

Can anybody clearly explain the meaning of this message? Why does library (I guess sp) outputs this for me? Something wrong with my shp-file? Can I do something in order not to get this warning? - May be transform my shape-file somehow? Because I am plotting this map from RStudio to HTML and don't want this text in the resulting HTML:

Here are my shape-files: download
P.S. I am aware about this topic but it doesn't shed light on this problem (at least for me). I don't understand what is the problem and what to do.

A: Use the sf package to read the shapefile:
R> area_dnipro <- sf::read_sf("dnipro.shp")
R> tm_shape(area_dnipro) + tm_polygons()

this does not show the warning.
See also ?tm_shape:
shp: shape object, which is an object from a class defined by the 'sf' or 'stars' package. Objects from the packages 'sp' and 'raster' are also supported, but discouraged.