text:
Q: How can I alter data type and datas in it, numbers separated with comma I have table , that has field named AMOUNT , amount takes number, table has 1.4m records, i need to upgrade them all . I would like the change NUMBER to varchar and make look like amount datas comma separated , eg: 76543-> 76,543. How can I able to do it?

A: 1 - Create the new column at the end of the table.
2 - Run an update to populate the new table column
(in this step for thousand seperataor look Thousand Seperator function in oracle? )
3 - Drop the old table column
4 - Re-name the new column to the original column name

A: You can use to_char():
select to_char(col, 'FM999,990;')

A:
i need to upgrade them all

Don't; if you have a numeric value then store it as a NUMBER.

I would like the change NUMBER to varchar and make look like amount datas comma separated , eg: 76543-> 76,543. How can I able to do it?

Just change how you are displaying the value rather than changing how you are storing the value.
If you have the table and data:
CREATE TABLE table_name ( amount NUMBER(12,0) );
INSERT INTO table_name ( amount ) VALUES ( 76543 );

If you want to do it in a SELECT statement then use TO_CHAR and include sufficient digits to format the largest number you can hold:
SELECT amount,
       TO_CHAR(amount, 'FM999G999G999G990') AS formatted_amount
FROM   table_name;

Outputs:

AMOUNT
FORMATTED_AMOUNT

76543
76,543

If you want to do that in the table then add a virtual column:
ALTER TABLE table_name
  ADD formatted_amount VARCHAR2(16)
                       GENERATED ALWAYS AS ( TO_CHAR(amount, 'FM999G999G999G990') );

Then, after adding the virtual column:
SELECT * FROM table_name;

Outputs:

AMOUNT
FORMATTED_AMOUNT

76543
76,543

db<>fiddle here


text:
Q: Overriding highlighted selection in UIPickerView I have a custom UIPickerView where I use:
-(UIView *)pickerView:(UIPickerView *)pickerView
       viewForRow:(NSInteger)row
     forComponent:(NSInteger)component
      reusingView:(UIView *)view

to populate the picker with UILabels.  Is there a way to disable the behavior of highlighting the selected row when touched?
I think this is a property of the underlying UITableViewCell inherent in the UIPickerView and I can't find a way to change it.

A: You need to make sure your custom view has the following properties:

*

*It needs to be sized to the same dimensions that the UIPickerView expects based on your delegate methods -- pickerView:rowHeightForComponent: and pickerView:widthForComponent:. The default height is 44 if you're not specifying a custom height.

*The background color must be [UIColor clearColor].

*The view must capture all touches.

The one gotcha when using UILabel instances as the custom view is that UILabel defaults userInteractionEnabled to NO (UIView, on the other hand, defaults this property to YES).
Based on these requirements, the example code from Halle can be rewritten as follows. This example also correctly reuses previously created views, which is needed for fast scrolling performance.
- (UIView *)pickerView:(UIPickerView *)pickerView
            viewForRow:(NSInteger)row
          forComponent:(NSInteger)component
           reusingView:(UIView *)view {

  UILabel *pickerRowLabel = (UILabel *)view;
  if (pickerRowLabel == nil) {
    // Rule 1: width and height match what the picker view expects.
    //         Change as needed.
    CGRect frame = CGRectMake(0.0, 0.0, 320, 44);
    pickerRowLabel = [[[UILabel alloc] initWithFrame:frame] autorelease];
    // Rule 2: background color is clear. The view is positioned over
    //         the UIPickerView chrome.
    pickerRowLabel.backgroundColor = [UIColor clearColor];
    // Rule 3: view must capture all touches otherwise the cell will highlight,
    //         because the picker view uses a UITableView in its implementation.
    pickerRowLabel.userInteractionEnabled = YES;
  }
  pickerRowLabel.text = [pickerDataArray objectAtIndex:row];

  return pickerRowLabel;
}

A: Setting the userInteractionEnabled property of UILabel to YES fixes the highlighting issue, but it also disables the UIPickerView from autoscrolling to select the row that has been touched.
If you want to disable the highlighting behavior, but maintain the UIPickerView's default autoscrolling functionality, call the setShowSelection function in the UITableCell instances contained in the UIPickerView. A way of doing this is to subclass the UILabel class similar to the following:
PickerViewLabel.h -
#import <UIKit/UIKit.h>

@interface PickerViewLabel:UILabel
{
}

@end

PickerViewLabel.m -
#import "PickerViewLabel.h"

@implementation PickerViewLabel

- (void)didMoveToSuperview
{
 if ([[self superview] respondsToSelector:@selector(setShowSelection:)])
 {
  [[self superview] performSelector:@selector(setShowSelection:) withObject:NO];
 }
}

@end

Then, where you had previously been returning an instance of UILabel in pickerView:viewForRow:forComponent:reusingView:, return an instance of PickerViewLabel. As an example, using the code from Doug, you would replace all the cases of 'UILabel' with 'PickerViewLabel'. Just remember to remove the pickerRowLabel.userInteractionEnabled = YES; line.

A: I guess you may want to look at "showsSelectionIndicator" property of UIPickerView

A: I'm not sure if there is an easy way to remove the selection feedback, but you can cover it up if you make the background of the label white and size it to the same dimensions as the blue selection rectangle:
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {

    UILabel *pickerRowLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 316, 40)];
    pickerRowLabel.backgroundColor = [UIColor whiteColor];
    pickerRowLabel.text = [pickerDataArray objectAtIndex:row];
    [self.view addSubview:pickerRowLabel];

    return pickerRowLabel;

}

With a width of 316 the label covers all but a sliver of blue on each side, and at 320 it completely covers the selection feedback but it also starts to cover a bit of the outer wheel gradients, which may or may not bother you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Testing Proxy auto-config FindProxyForURL() via Javascript Console Is it possible to test a Proxy auto-config (PAC) script by manually executing the FindProxyForURL(url, host) function from the browser JavaScript console?
Can the internal implementation of the PAC functions (such as dnsDomainIs, shExpMatch, isInNet) be accessed from the console?
Alternatively can these functions be implemented within standard JavaScript to allow the FindProxyForURL function to be executed manually?
The only way I can find to debug the proxy.pac script within the browser is to add alert() statements and let the browser execute it internally.  Being able to add  breakpoints and manually step through the FindProxyForURL function would make debugging it easier.
There are many external tools for testing PAC scripts, such as pacparser (which uses Spidermonkey) and autoprox (which uses Microsofts implementation)
Similar questions have been asked:
How to discover de proxy used in a pac
How to get access log of PAC(proxy auto config)
Debugging autoproxy (PAC) javascript with alert()?
Where in Windows is the Javascript file which contains functions for executing PAC files?

A: Some of the PAC functions have been implemented by pactester and available in pac_utils.js: https://github.com/manugarg/pactester/blob/master/pac_utils.js
However it is missing the functions dnsResolve and myIpAddress as noted in the pactester readme:

PAC files use certain JavaScript functions. These functions have been defined in pac_utils.js file included with this tool (This file was generated using another file from Mozilla source code). Also, since JavaScript has no DNS resolving capability which is required by the "dnsResolve" and "myIpAddress" functions in the PAC files, these functions have been defined in perl and then exported to a JavaScript context.

There are implementations of these functions using web services but they won't work with local addresses without running your own server:
dnsResolve:
Can I perform a DNS lookup (hostname to IP address) using client-side Javascript?
Perform a DNS lookup to resolve a hostname to an IP address using JavaScript
myIpAddress:
How to get client's IP address using javascript only?
I don't know if it's possible to make any browsers grant access to manually execute scripts within the PAC sandbox environment which hosts the native implementation of these functions.

PAC files run in a browser sandbox thus don't have access to the entire JavaScript programming language. Instead, PAC file functionality is implemented in a browser with a custom sanboxed function set.


text:
Q: How do I get the UTC time of "midnight" for a given timezone? The best I can come up with for now is this monstrosity:
>>> datetime.utcnow() \
...   .replace(tzinfo=pytz.UTC) \
...   .astimezone(pytz.timezone("Australia/Melbourne")) \
...   .replace(hour=0,minute=0,second=0,microsecond=0) \
...   .astimezone(pytz.UTC) \
...   .replace(tzinfo=None)
datetime.datetime(2008, 12, 16, 13, 0)

I.e., in English, get the current time (in UTC), convert it to some other timezone, set the time to midnight, then convert back to UTC.
I'm not just using now() or localtime() as that would use the server's timezone, not the user's timezone.
I can't help feeling I'm missing something, any ideas?

A: @hop's answer is wrong on the day of transition from Daylight Saving Time (DST) e.g., Apr 1, 2012. To fix it tz.localize() could be used:
tz = pytz.timezone("Australia/Melbourne")
today = datetime.now(tz).date()
midnight = tz.localize(datetime.combine(today, time(0, 0)), is_dst=None)
utc_dt = midnight.astimezone(pytz.utc)

The same with comments:
#!/usr/bin/env python
from datetime import datetime, time
import pytz # pip instal pytz

tz = pytz.timezone("Australia/Melbourne") # choose timezone

# 1. get correct date for the midnight using given timezone.
today = datetime.now(tz).date()

# 2. get midnight in the correct timezone (taking into account DST)
#NOTE: tzinfo=None and tz.localize()
# assert that there is no dst transition at midnight (`is_dst=None`)
midnight = tz.localize(datetime.combine(today, time(0, 0)), is_dst=None)

# 3. convert to UTC (no need to call `utc.normalize()` due to UTC has no
#    DST transitions)
fmt = '%Y-%m-%d %H:%M:%S %Z%z'
print midnight.astimezone(pytz.utc).strftime(fmt)

A: This is more straightforward with dateutil.tz than pytz:
>>>import datetime
>>>import dateutil.tz
>>>midnight=(datetime.datetime
             .now(dateutil.tz.gettz('Australia/Melbourne'))
             .replace(hour=0, minute=0, second=0, microsecond=0)
             .astimezone(dateutil.tz.tzutc()))
>>>print(midnight)
2019-04-26 14:00:00+00:00

The tzinfo documentation recommends dateutil.tz since Python 3.6. The tzinfo objects from dateutil.tz have no problems with anomalies like DST without requiring the localize functionality of pytz. Using the example from user3850:
>>> now = (datetime.datetime(2012, 4, 1, 5,
...         tzinfo = dateutil.tz.gettz('Australia/Melbourne')))
>>> print(now.replace(hour = 0).astimezone(dateutil.tz.tzutc()))
2012-03-31 13:00:00+00:00

A: I think you can shave off a few method calls if you do it like this:
>>> from datetime import datetime
>>> datetime.now(pytz.timezone("Australia/Melbourne")) \
            .replace(hour=0, minute=0, second=0, microsecond=0) \
            .astimezone(pytz.utc)

BUT… there is a bigger problem than aesthetics in your code: it will give the wrong result on the day of the switch to or from Daylight Saving Time.
The reason for this is that neither the datetime constructors nor replace() take DST changes into account.
For example:
>>> now = datetime(2012, 4, 1, 5, 0, 0, 0, tzinfo=pytz.timezone("Australia/Melbourne"))
>>> print now
2012-04-01 05:00:00+10:00
>>> print now.replace(hour=0)
2012-04-01 00:00:00+10:00 # wrong! midnight was at 2012-04-01 00:00:00+11:00
>>> print datetime(2012, 3, 1, 0, 0, 0, 0, tzinfo=tz)
2012-03-01 00:00:00+10:00 # wrong again!

However, the documentation for tz.localize() states:

This method should be used to construct localtimes, rather
  than passing a tzinfo argument to a datetime constructor.

Thus, your problem is solved like so:
>>> import pytz
>>> from datetime import datetime, date, time

>>> tz = pytz.timezone("Australia/Melbourne")
>>> the_date = date(2012, 4, 1) # use date.today() here

>>> midnight_without_tzinfo = datetime.combine(the_date, time())
>>> print midnight_without_tzinfo
2012-04-01 00:00:00

>>> midnight_with_tzinfo = tz.localize(midnight_without_tzinfo)
>>> print midnight_with_tzinfo
2012-04-01 00:00:00+11:00

>>> print midnight_with_tzinfo.astimezone(pytz.utc)
2012-03-31 13:00:00+00:00

No guarantees for dates before 1582, though.

A: Setting the TZ environment variable modifies what timezone Python's date and time functions work with.
>>> time.gmtime()
(2008, 12, 17, 1, 16, 46, 2, 352, 0)
>>> time.localtime()
(2008, 12, 16, 20, 16, 47, 1, 351, 0)
>>> os.environ['TZ']='Australia/Melbourne'
>>> time.localtime()
(2008, 12, 17, 12, 16, 53, 2, 352, 1)

A: Each time zone has a number, eg US/Central = -6. This is defined as the offset in hours from UTC. Since 0000 is midnight, you can simply use this offset to find the time in any time zone when it is midnight UTC. To access that, I believe you can use  time.timezone
According to The Python Docs, time.timezone actually gives the negative value of this number:

time.timezone

The offset of the local (non-DST) timezone, in seconds west of UTC (negative in most of Western Europe, positive in the US, zero in the UK).

So you would simply use that number for the time in hours if it's positive (i.e., if it's midnight in Chicago (which has a +6 timezone value), then it's 6000 = 6am UTC).
If the number is negative, subtract from 24. For example, Berlin would give -1, so 24 - 1 => 2300 = 11pm.

A: It's worth remarking that we can adapt the answer given by @jfs to find tomorrow's midnight or yesterday's midnight, etc. The trick is to add a certain number of days to the aware timezone. This works because although this usually adds 24 hours, sometimes it might add 23 or 25 based on DST issues.
from datetime import datetime, time, timedelta
import pytz

def midnight_UTC(offset):

    # Construct a timezone object
    tz = pytz.timezone('Australia/Melbourne')

    # Work out today/now as a timezone-aware datetime
    today = datetime.now(tz)

    # Adjust by the offset. Note that that adding 1 day might actually move us 23 or 25
    # hours into the future, depending on daylight savings. This works because the {today}
    # variable is timezone aware
    target_day = today + timedelta(days=1) * offset

    # Discard hours, minutes, seconds and microseconds
    midnight_aware = tz.localize(
        datetime.combine(target_day, time(0, 0, 0, 0)), is_dst=None)

    # Convert to UTC
    midnight_UTC = midnight_aware.astimezone(pytz.utc)

    return midnight_UTC

print("The UTC time of the previous midnight is:", midnight_UTC(0))
print("The UTC time of the upcoming midnight is:", midnight_UTC(1))


text:
Q: SpriteKit: Making a character move in a world i am trying to understand how you can make a huge world, and have a character move inside the world, and then it moves the visible part of the world with the moving character. Like the Mario game.
I read apples guide here: https://developer.apple.com/library/IOs/documentation/GraphicsAnimation/Conceptual/SpriteKit_PG/Actions/Actions.html#//apple_ref/doc/uid/TP40013043-CH4-SW32
on "centering the scene on a node" but i really couldn't understand it at all. I tried implementing it, but it did not work at all.
So, anyone able to help me here? A full example with some good comments on would be great.
Hope my question makes sense, thanks on advance everyone!

A: They try to talk with you "Your game world is a node and what you need to do only move the world node with your character".
Game "Adventure" - the example game for Sprite Kit will help you a lot to create a huge world like that.
https://developer.apple.com/LIBRARY/IOS/documentation/GraphicsAnimation/Conceptual/CodeExplainedAdventure/AdventureArchitecture/AdventureArchitecture.html
=> There are example Code of this game in documentary.
Besides, you can create "Tile map" to do the same.

A: I use a simple class AGMovingNode, inherited from SKNode as a background layer.
It's not perfect, but at least you can start from where.
Here is a code of the class:
AGMovingNode.h:
#import <SpriteKit/SpriteKit.h>

@interface AGMovingNode : SKNode

@property float pointsPerSecondSpeed;

- (instancetype)initWithPointsPerSecondSpeed:(float)pointsPerSecondSpeed;
- (void)update:(NSTimeInterval)currentTime paused:(BOOL)paused;

@end

AGMovingNode.m:
#import "AGMovingNode.h"

@implementation AGMovingNode
{

    NSTimeInterval _lastUpdateTime;
    NSTimeInterval _deltaTime;

}

- (instancetype)initWithPointsPerSecondSpeed:(float)pointsPerSecondSpeed {
    if (self = [super init]) {
        self.pointsPerSecondSpeed = pointsPerSecondSpeed;
    }
    return self;
}

- (void)update:(NSTimeInterval)currentTime paused:(BOOL)paused {
    if (paused) {
        _lastUpdateTime = 0;
        return;
    }
    //To compute velocity we need delta time to multiply by points per second
    if (_lastUpdateTime) {
        _deltaTime = currentTime - _lastUpdateTime;
    } else {
        _deltaTime = 0;
    }
    _lastUpdateTime = currentTime;

    CGPoint bgVelocity = CGPointMake(-self.pointsPerSecondSpeed, 0.0);
    CGPoint amtToMove = CGPointMake(bgVelocity.x * _deltaTime, bgVelocity.y * _deltaTime);
    self.position = CGPointMake(self.position.x+amtToMove.x, self.position.y+amtToMove.y);
}
@end

I found it in one of tutorials (can't remember which one right now) and slightly modified it.

A: I found it best if you use SKActions to move objects around.
What i do is have a method to reposition my character also with sprite animations (when he is standing and when he is walking):
- (void)moveUser:(CGPoint)position {
  SKSpriteNode *user = (SKSpriteNode*)[self childNodeWithName:@"userSprite"];

  // ... some logic to load correct atlas
  NSArray *animationFrames = ...

  SKAction *animation = [SKAction animateWithTextures:animationFrames timePerFrame:0.05f numberOfFrames:animationFrames.size];
  SKAction *moveToPositionAction = [SKAction moveTo:position duration:0.4f];

  [userNode runAction:[SKAction group:@[animation,moveToPositionAction]]];
}


text:
Q: Trying to install a package from bullseye-backports I am running Debian Bullseye and I want to install ffmpeg 4.4.1, which looks to be available in sid:

So I have added the backports repo:
# apt-cache policy
Package files:
...
 500 http://mirrors.ocf.berkeley.edu/debian bullseye/main amd64 Packages
     release v=11.2,o=Debian,a=stable,n=bullseye,l=Debian,c=main,b=amd64
     origin mirrors.ocf.berkeley.edu
 100 http://deb.debian.org/debian bullseye-backports/main amd64 Packages
     release o=Debian Backports,a=bullseye-backports,n=bullseye-backports,l=Debian Backports,c=main,b=amd64
     origin deb.debian.org
...

# apt-get install -t bullseye-backports ffmpeg
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
ffmpeg is already the newest version (7:4.3.3-0+deb11u1).
0 upgraded, 0 newly installed, 0 to remove and 33 not upgraded.

apt-cache show ffmpeg only shows one entry, which is for ffmpeg 4.3 in the main stable repository.  Any advice?

A: Seems ffmpeg-4.4.1 is not in bullseye backports. If you really want to use 4.4.1, you'd have to add debian testing repos, but don't do this lightheartedly!


text:
Q: Serve local video files for vlc-plugin with python I have a web application focused around playing videos.  It uses a flask api to serve the metadata.  I want to be able to pass a local filepath for a video to the client and allow the client to play that video.  Since you can't just load a local file, how can I serve the file to the browser?  I know there is simplehttpserver but I have files all over the place.
How can I set it up so that I can use the vlc plugin like in this post Open video stream on VLC Player through the browser?
UPDATE
This is not a duplicate.  I am asking how can I serve a file from a client-supplied filepath.  This can be any location, not just one directory of static css/html/js files I want served.  Since the client is getting the filepath from the server, I can validate that file is allowed to be served.
UPDATE 2
Still do not believe this is a duplicate as it is for consumption by a specific plugin, vlc web plugin.  I tried to use send_from_directory but it did not work.  Hopefully this makes it clearer.  If send_from_directory` is the right thing to use though, what is my error here?
On python my endpoint is as follows (using flask-restful):
from flask import Blueprint, send_from_directory
from flask_restful import Api, Resource

class VideoServer(Resource):

    def get(self, filepath):
        path, file = os.path.split(filepath)
        return send_from_directory(path, file)

base_blueprint.add_resource(VideoServer, '/video_server/<string:filepath')

On the js side:
let videourl = config.api_server + '/video_server/' + filepath
let $video = $("<object>", {type: "application/x-vlc-plugin", data: videourl});
let $param = $("<param>", {name: "movie", value: videourl});
let $embed = $("<embed>", {type: "application/x-vlc-plugin", autoplay: "yes", loop: "no", target: videourl});
$video.append($param);
$video.append($embed);
$("#mydiv").append($video);
$("#mydiv").load();

A: For this kind of task I'd recommend a real server (as opposite to python simplehttpserver or flask embedded dev server).
So, maybe nginx ?


text:
Q: Chose to fight Blue at Battle Tree, how do I get Kanto Starter Mega Stones? In Pokemon Sun and Moon, once you enter the Battle Tree for the first time, you get challenged by Red and Blue, the "Champions" of Kanto. The Mega Stones for the Kanto starters are given by Red, but I chose to fight Blue at the Battle tree, who did not give me the Venusaurite, Charizardite X/Y, and Blastoisinite.
After choosing the trainer to fight, both trainers left and I did not receive the Mega Stones for Venusaur, Charizard, and Blastoise. Is there another chance for me to obtain the stones?

A: In regular singles you have to fight Red on the last battle (20) and then he will appear outside of the Battle Tree and give you the stones. He doesn't give out stones on Super Singles.

A: According to Serebii, you are able to fight Red (and Blue, for that matter) in the Battle Tree randomly. They are listed as Special Trainers and you will fight one of them every 10 battles in Super Battles.

In the Super Battles, these trainers will come every 10 wins in a streak and offer a bit of a challenge.

Since defeating Red is what nets you the Venusaurite, Charizardite X/Y, and Blastoisite, it appears that regardless of whether or not you choose to defeat Red at the entrance of the Battle Tree, you will just have to beat him when he appears during your Battle Tree challenge as the last battle in Regular Singles, as mentioned in Alexander's answer.
Besides Red and Blue, you can also end up fighting Anabel, Colress, Cynthia, Dexio, Grimsley, Guzma, Kiawe, Mallow, Plumeria, Sina, or Wally.

A: I beat Red outside of Battle Tree and still didn't get the stones. I think you have to beat him in the official Battle Tree challenge to get the stones


text:
Q: KnpSnappyBundle PDF generation exceeds maximum execution time I'm trying to generate a PDF with KnpSnappyBundle in Symfony, but whenever I attempt to run the action to do so, it exceeds the maximum 60 second execution time in PHP.
Here is the action:
/**
* @Route("/download-agreement", name="download_agreement")
*/
public function downloadAgreementAction()
{
    $session = new Session();
    $html = $this->renderView('client-representation.html.twig', array(
        'clientAgreementData'  => $session->get("sessionClientAgreementData"),
        "pdfStatus" => true
        ));

    return new Response(
        $this->get('knp_snappy.pdf')->getOutputFromHtml($html),
        200,
        array(
            'Content-Type'          => 'application/pdf',
            'Content-Disposition'   => 'attachment; filename="error.pdf"'
            )
        );
}

It also only seems to exceed the execution time when I use absolute urls for assets in the twig template, like absolute_url(asset('css/agreement.css')). If I use relative urls, then the css will just get ignored and the PDF will generate, but of course I need the styling.
Any ideas?
EDIT: For anyone who has this problem, using absolute urls SHOULD work on a production server; on localhost however, you may get the problem I had. Thank you to chalasr.

A:
Ok, the solution is really simple actually, the problem is that it wont work on dev(local) environment because for some reason the wkhtmltopdf doesn't like localhost:8000... whatever.

From this issue (and many other) opened for this problem in the laravel package.
Another on the bundle https://github.com/KnpLabs/KnpSnappyBundle/issues/66
The first time I worked with KnpSnappyBundle, I used a lot of alternatives, unsuccessfully.
The 'timeout exceeded' occurs when trying to generate pdf using a view (same for all related methods of the Pdf class) which contains one or more absolute url(s).
To deal with this bug, I use a specific template used only for Pdf generation,  where I put the css directly in a <style></style> block.
Like this, the style is correctly applied.


text:
Q: Last record in database is being used rather than the record desired I have an approval/denial user system that I created and I am running into an issue with it.
I first have to approve or deny the user. If that user is approved, their name is placed into a different section of the page called 'Approved Users'. Within this area I change the user's permission/group level. However, if I have more than one user in the approved user section, if I try to update a user, it updates the last record displayed no matter which user I try to change.
For example, if I had this and tried to update Rick's record, Bob's would be updated. Bob's record would be the last one in my database.
-Bob
-Tony
-Rick

Whenever I approve the record, the correct user's record gets changed. It is only when I try to change the group/permission part, it does not work right.
Starting here it works..
    $con = mysqli_connect("localhost", "", "", "");
$run = mysqli_query($con,"SELECT * FROM user_requests ORDER BY id DESC");
$numrows = mysqli_num_rows($run);

    if( $numrows ) {
        while($row = mysqli_fetch_assoc($run)){
            if($row['status'] == "Pending"){

                $pending_id        = $row['id'];
                $pending_user_id   = $row['user_id'];
                $pending_firstname = $row['firstname'];
                $pending_lastname  = $row['lastname'];
                $pending_username  = $row['username'];
                $pending_email  = $row['email'];
?>
        <form action="" method="POST" id="status">
             <input type='hidden' name='id' value='<?php echo $pending_id; ?>' id='pending_id'/>
<?php
        if ($pending_firstname == true) {
            echo "Name - ". $pending_firstname . " " . $pending_lastname . "
" .
                "Username - ". $pending_username . "

"
                //echo print_r($_POST);
?>

                        <button class="approve" type="submit" form="status" name="approve" value="<?=$pending_id;?>">Approve</button>
                        <button class="deny" type="submit" form="status" name="deny" value="<?=$pending_id;?>">Deny</button>
                        </form>

<?php
                    ;} else {
                        echo "There are no Pending Requests at this time.";
                    }
                }
            }
        }
?>

End of Pending users and up to this point it works and uses the correct user that was clicked. Now at this point when I try to update the user's info it updated the first user displayed...

Approved User Requests

<?php
    $con2 = mysqli_connect("localhost", "", "", "");
    $run2 = mysqli_query($con2,"SELECT * FROM user_requests ORDER BY id DESC");
    $runUsers2 = mysqli_query($con2,"SELECT * FROM users ORDER BY id DESC");
    $numrows2 = mysqli_num_rows($run2);

        if( $numrows2 ) {
            while($row2 = mysqli_fetch_assoc($run2)){
                if($row2['status'] == "Approved"){
                //var_dump ($row2);

                    $approved_id        = $row2['user_id'];
                    $approved_firstname = $row2['firstname'];
                    $approved_lastname  = $row2['lastname'];
                    $approved_username  = $row2['username'];
                    $approved_email  = $row2['email'];

        if ($approved_firstname == true) {
            echo "Name - ". $approved_firstname . " " . $approved_lastname . "
" .
                "Username - ". $approved_username . "

"
?>

     Change User Permission

    Close

    <form id="update_group" action="" method="POST" accept-charset="utf-8">

        Group
        <input type="hidden" value="<?php echo $approved_id; ?>" id="approved_id" name="id" />
        <input type="hidden" value="<?php echo $approved_firstname; ?>" id="approved_firstname" name="firstname" />
        <input type="hidden" value="<?php echo $approved_lastname; ?>" id="approved_lastname" name="lastname" />
        <input type="hidden" value="<?php echo $approved_username; ?>" id="approved_username" name="username" />
        <input type="hidden" value="<?php echo $approved_email; ?>" id="approved_email" name="email" />
        <select id='group_id' name='group' required>
            <option value=''><?php echo htmlentities($group); ?></option>
            <option value="1">Bench</option>
            <option value="2">Spectator</option>
            <option value="3">Team Member</option>
            <option value="4">Commissioner</option>
        </select>

    <input type="submit" value="submit" name="group">
    </form>

AJAX that I use to update the info..
//AJAX call for Approving the status
$(document).ready(function () {

    $('.approve').click(function () {
        $.ajax({
            url: 'userRequest_approve.php',
            type: 'POST',
            data: {
                id: $(this).val(), //id
                status: 'Approved' //status
            },
            success: function (data) {
                //do something with the data that got returned
                $("#success").fadeIn();
                $("#success").show();
                $('#success').html('User Status Changed!');
                $('#success').delay(5000).fadeOut(400);
            },
            //type: 'POST'
        });
        return false;
    });
});

//AJAX call for updating the group
$(document).ready(function () {

    $('#update_group').on('submit', function (event) {
    event.preventDefault();
        $.ajax({
            url: 'user_group_update.php',
            type: 'POST',
            data: {
            id: $("#approved_id").val(), //id
            firstname: $("#approved_firstname").val(), //firstname
            lastname: $("#approved_lastname").val(), //lastname
            username: $("#approved_username").val(), //username
            email: $("#approved_email").val(), //email
           // update_group: $("#group_id").val() //group level
          update_group: $(this).find( "#group_id option:selected" ).val()
        },
            success: function (data) {
                //do something with the data that got returned
                $(".group_success").fadeIn();
                $(".group_success").show();
                $('.group_success').html('User Permission Level Changed!');
                $('.group_success').delay(5000).fadeOut(400);
                alert(data);
            },
             error: function(jqXHR, textStatus,errorThrown )
            {
              // alert on an http error
              alert( textStatus +  errorThrown );
            }
        });
        return false;
    });
});

I believe the entire issue has to do with the id, but I don't get what is wrong with the id I am getting. Does anyone see anything I am doing incorrectly that is causing this?

A: In the first part of your code, I found a few syntax errors. Corrected to:
<?php
$con = mysqli_connect("localhost", "", "", "");
$run = mysqli_query($con,"SELECT * FROM user_requests ORDER BY id DESC");
$numrows = mysqli_num_rows($run);
if( $numrows ) {
    while($row = mysqli_fetch_assoc($run)){
        if($row['status'] == "Pending"){
            $pending_id        = $row['id'];
            $pending_user_id   = $row['user_id'];
            $pending_firstname = $row['firstname'];
            $pending_lastname  = $row['lastname'];
            $pending_username  = $row['username'];
            $pending_email     = $row['email'];
            echo "<form action='' method='POST' id='status'>\r\n";
            echo "<input type='hidden' name='id' value='$pending_id' id='pending_id' />\r\n";
            if ($pending_firstname == true) {
                echo "Name - $pending_firstname $pending_lastname
\r\n";
                echo "Username - $pending_username

\r\n";
                echo "<button class='approve' type='submit' form='status' name='approve' value='$pending_id'>Approve</button>\r\n";
                echo "<button class='deny' type='submit' form='status' name='deny' value='$pending_id'>Deny</button>\r\n";
                echo "</form>

\r\n";
            } else {
                echo "There are no Pending Requests at this time.";
            }
        }
    }
}
?>

Second, am concerned about your double query. I would advise running the query, iterate over the result, and then run the second query. Should also free the results after each query just to be safe. If this is in the same page, I would also not create a new connection.
If you could post any error or results form your Console, could expand upon my answer.


text:
Q: How to slice python dictionary, based on existence of specific element I have dictionary like this:
mydictionary = {0: header,
1: thumbnail,
2: paragraph,
3: header,
4: thumbnail,
5: thumbnail,
6: paragraph,
7: paragraph}

im looping through the dictionary and if I find a paragraph , I want to find all the previous thumbnails but only up to previous paragraph.
for x in mydictionary:
   if paragraph in mydictionary:
      find all the previous thumbnails up to previous paragraph

in other words at paragraph 2, it would return item 1
in paragraph 6, it would return item 4 and 5
in paragraph 7, nothing will be returned

A: You can do something like this:
mydictionary = {0: "header",
                1: "thumbnail",
                2: "paragraph",
                3: "header",
                4: "thumbnail",
                5: "thumbnail",
                6: "paragraph",
                7: "paragraph"}

prev_thumbnails = []
for key, value in mydictionary.items():
    if value == "thumbnail":
        prev_thumbnails.append(key)
    elif value == "paragraph":
        print(prev_thumbnails)
        prev_thumbnails = []
#returns
#[1]
#[4, 5]
#[]


text:
Q: Can bzr specify the major and minor version number? At least by default, and committed version number is a single number with 1 increment. Can I specify the version number as major.minor when committing? Or there is another mechanism I overlooked?

A: Revision numbers are automatically incremented by every commit in the branch, and thus they are integer numbers.
When you merge another branch into the current branch, the revisions of that branch will be renamed using a dotted notation, in the format BASE.BRANCH.REV, as you can observe for example in the Bazaar project itself:
bzr log --line -n0 -r6572..6573 lp:bzr

This dotted notation has nothing to with major-minor version numbers. You can read more about this in the documentation: http://doc.bazaar.canonical.com/beta/en/user-guide/zen.html
On the other hand, you can assign tags to revision numbers, and these are designed exactly for this kind of purpose, to mark release numbers. For example in one of my projects I have the following tags:
$ bzr tags
1.1              159
1.3              188

This means that I assigned (in the past) the tag "1.1" to revision 159 and "1.3" to revision 188. The "1.1" and "1.3" are indeed intended as major-minor release numbers.
Tags work like aliases to revisions. These commands are equivalent:
bzr log -r revno:159
bzr log -r tag:1.1

(As a matter of fact Bazaar is smart enough to figure out the right even if I drop the revno: and tag: prefixes)
You can create tags using bzr tag, you can assign tags to the latest revision or any past revision. See bzr tag --help for details.

A: It's not a version number, not in the sense of a product's version number. It's a revision number -- you can consider it the number of changes made to your project.


text:
Q: Developer Edition with Namespace: duplicate triggers? In my namespaced Developer Edition org, I started using Cloud 9 IDE, which, despite being a beta, is pretty amazing. However, in one of my orgs, Cloud 9 refused to work without any explanation. I plan on filing a bug with them, but I traced the problem to something I thought was impossible: I had two triggers by the same name, with different content, one with the namespace and one without. Of course, since the API was stripping the namespace from my files (because it's the managed package org), the file system got confused and couldn't save the files.
The trigger in question is: chatter_answers_question_escalation_to_case_trigger, which I presume was made by the system, because I certainly don't call making it, nor would I use such an unusual naming convention. However, it's now in my system twice, and I'm confused how a non-namespaced file could have made its way into my org, since this thing has had a namespace that predates any of the current code in the org. No other classes, pages, triggers, etc exhibit this behavior, and I cannot make another non-namespaced code object manually through any technique I know.
Is there a known bug around this? Under what circumstances could this have occurred? I presume it's safe to delete one, but I was really curious what led to this phenomenon to begin with. I'll accept any answer which either shows documentation of the bug, or a way to reproduce this bug so I can file a report with salesforce.
Edit:
The system allows me to edit both triggers independently. In fact, I just renamed both of them to a new conflicting name, and they both saved. The non-namespaced trigger still has no namespace after the edit.
Edit 2:
The files appear as follows:
 CreatedBy.Name | NamespacePrefix | Name                                                | CreatedDate
----------------+-----------------+-----------------------------------------------------+------------------------------
 Brian Fear     | (null)          | chatter_answers_question_escalation_to_case_trigger | 2015-08-07T19:57:52.000+0000
 Brian Fear     | <<redacted>>    | chatter_answers_question_escalation_to_case_trigger | 2015-08-07T19:58:42.000+0000
 (2 records)

A: Steps to reproduce: Enable "Chatter Answers". This generates the trigger chatter_answers_question_escalation_to_case_trigger without namespace. Download the trigger via the Metadata API to your local box. Then upload it via Metadata API, e.g. via the migration tool with sf:deploy - outch! Two triggers with the same name, just distinguished by an empty or non-empty namespace prefix.


text:
Q: How to Auto-Trigger Jenkins based on GIT changes through web-hooks? GitHub is deprecating the integration services. Whats the easiest way to trigger the Jenkins through git web-hooks?

A: Configure your build job with below steps:
1. Job URL:
   Get the Jenkins job URL (ex: https://buildtools.com/job/job-name)
2. API TOKEN:
    Get your API token from Jenkins account. (ex:fsdjlfs76dfsf6fsdfsf)
3. Create Job hook URL:
   Generate the build hook URL with this pattern:http://jenkins_username:jenkins_API-TOKEN@job_url/build
NOTE: if your job having build parameters use buildWithParameters instead of build.

Now, your job URL is ready to call. wherever u want to trigger you can just call.
Example use cases:
some sample use cases are listed below:
Integrating with Github :

*

*Login to your GitHub account.

*Click on your Project repository

*Click on your repository settings

*Click on Add Webhook paste your Job hook URL in payload URL input box select the event to call the job URL.

*click on Add Webhook check your Jenkins job by making some event in
GitHub.

if any queries feel free comment below

A: Git Hooks
Command documentation
Once you configure/install the git-hooks into your environment, then the hook can be used to call your commands to do a build.


text:
Q: How to make ajax auto-complete compulsory? I want to force the user to select from the auto-complete options.
NB: I do not want to use a drop down menu.

A: Try using this
var isItemSelected = false;

 //Handler for AutoCompleter OnClientItemSelected event
  function onItemSelected() {
      isItemSelected = true;
  }

  //Handler for textbox blur event
  function checkItemSelected(myTextBox) {
      if (!isItemSelected) {
          alert("Please select item from the list only!");
          myTextBox.focus();
      }
      else {
          //reset isItemSelected
          isItemSelected = false;
      }
  }

And then throw this in the Textbox:
onblur="checkItemSelected(this)"

A: Well i have this forum for the references .
Forum,
You'll need to use the select and focus options to support this.
  Fiddle  example
focus: function( event, ui ) {
            $( "#tags" ).val( ui.item.label );
            return false;
        },


text:
Q: Conda installation python shortcut I have installed Anaconda using the CLI.
It has modified my ~/.bash_profile as follow:
# >>> conda init >>>
# !! Contents within this block are managed by 'conda init' !!
__conda_setup="$(CONDA_REPORT_ERRORS=false '/opt/anaconda3/bin/conda' shell.bash hook 2> /dev/null)"
if [ $? -eq 0 ]; then
    \eval "$__conda_setup"
else
    if [ -f "/opt/anaconda3/etc/profile.d/conda.sh" ]; then
# . "/opt/anaconda3/etc/profile.d/conda.sh"  # commented out by conda initialize
        CONDA_CHANGEPS1=false conda activate base
    else
        \export PATH="/opt/anaconda3/bin:$PATH"
    fi
fi
unset __conda_setup
# <<< conda init <<<

# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
__conda_setup="$('/Users/Solal/anaconda3/bin/conda' 'shell.bash' 'hook' 2> /dev/null)"
if [ $? -eq 0 ]; then
    eval "$__conda_setup"
else
    if [ -f "/Users/Solal/anaconda3/etc/profile.d/conda.sh" ]; then
        . "/Users/Solal/anaconda3/etc/profile.d/conda.sh"
    else
        export PATH="/Users/Solal/anaconda3/bin:$PATH"
    fi
fi
unset __conda_setup
# <<< conda initialize <<<

And the installation created a file .bash_profile-anaconda3.bak as follow:
export PATH=/usr/local/bin:/usr/local/sbin:${PATH}
I don't understand when I try to run python command it sills use MacOS default python version
which python returns:
/usr/bin/python
How can I make my anaconda python the default one?
Thank you for your help

A: Source your ./bash_profile after you have done the necessary modifications. Doing so executes the content of the file passed as the argument.
At the terminal:
source ~/.bash_profile


text:
Q: Can an RCD detect a fault on an isolated circuit? I was installing a new plug socket today in an outbuilding of my house, which is wired up to a small circuit breaker box which houses breakers for the lights and plug sockets in this outbuilding. This smaller circuit breaker box is then presumably wired up to the houses main circuit breaker box, which houses an RCD along with all the breakers for the rest of the house.
Before working on the sockets in the outbuilding, I turned off the plug sockets and light circuit breakers to the outbuilding on this smaller circuit breaker box, yet, when I began to work on the socket and stripped the wires, it caused the RCD in the main circuit breaker box to trip, cutting power to the whole house.
How is this possible? I thought that by cutting power to the outbuilding, the RCD wouldn't be able to "see" that part of the circuit?

A: A single-phase circuit-breaker will only disconnect the live. It can't fully isolate if the neutral is still connected.
Neutral is bonded to earth / ground at the distribution transformer or at the service entrance to the property. If there is any electrical load running in the property there will be current flowing in the neutral. Since the neutral has resistance we can predict that there will be a voltage (V = IR) on the neutral wire. (This might only be a couple of volts.) Generally, the further you go from the earth bonding point, the higher this neutral-earth voltage will be.
Now if you ground the neutral some current will flow. The RCD will sense that there is an imbalance between what's going out on the live and what's returning on the neutral (they don't cancel out anymore) and will disconnect the supply to ensure your safety.

Ah I see, thank you - how come electrical loads cause current to flow in the neutral? My knowledge is basic but I always presumed earth meant any current that went into it is immediately dissipated into wherever the earth terminates.

simulate this circuit – Schematic created using CircuitLab
Figure 1. LAMP2 has been removed and the neutral accidentally connected to earth.
It's a circuit. Current that comes in on the live must return to the source via the neutral. If it didn't then why would we need neutral wiring or why couldn't we use a much lighter wire for the neutral? Earth fault currents do dissipate through the ground but must "un-dissipate" back at the transformer's earth-neutral connection. What goes out on L must come back on neutral and/or earth.


text:
Q: With R changing row names of a dataframe i have a Dataframe like this.
My column names are F02283_L1_S49_L006, F02284_L1_S50_L006 etc. which is totally fine.
But my row names are 1,2,3,4 etc. and i dont want that. Instead of that i want ENSG00000182199, ENSG00000157870 etc.
Im new in R and i have to process this dataframe. I will my dataframe as a matrix, so they muss contain just numeric values. How can i do that with R?


text:
Q: Automapper un-flatten output I'm trying to get automapper to nest some data instead of flatten data.  I have these two structures:
public class PlatformDTO {
    public string Name { get; set; }
    public string OperatingSystem { get; set; }
}

public class ExistingDTO {
    public string Stepping { get; set; }
    public PlatformDTO Platform { get; set; }
}

and then I setup Automapper:
var config = new MapperConfiguration(x => {
    x.CreateMap<ChecklistIntegratedPlatform, PlatformDTO>()
        .ForMember(x => x.Name, x => x.MapFrom(x => x.PlatformName));

    x.CreateMap<ChecklistIntegratedPlatform, ExistingDTO>();
});

If I .ProjectTo<PlatformDTO> in my linq query I get the expected output.  If I project to ExistingDTO I get the stepping, but the Platform is null.  How do I configure things so that I get the platform populated when projecting to ExistingDTO?


text:
Q: Errors with UIPickerView I am getting these errors and i dont even know why
1: Type view controller does not conform with UIViewPickerDataSource
2: method pickerview(pickerView:numberOfRowsInComponent:) has different argument names from those required
Here is my code!
Any help will be appreciated. Thanks
import UIKit

class ViewController: UIViewController,UIPickerViewDataSource,UIPickerViewDelegate {

@IBOutlet weak var timePicker: UIPickerView!

var timePickerData:[[Int]] = [[Int]]()

override func viewDidLoad()
{
    super.viewDidLoad()

    self.timePicker.delegate = self
    self.timePicker.dataSource = self

    timePickerData = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,52,  53, 54, 55, 56, 57, 58, 59], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,52,  53, 54, 55, 56, 57, 58, 59]]
}

override func didReceiveMemoryWarning()
{
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int
{
    return timePickerData.count
}

// The number of rows of data
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
{
    return timePickerData[component].count
}

// The data to return for the row and component (column) that's being passed in
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> Int?
{
    return timePickerData[component][row]
}

}

A: It seems like you are using XCode 8, but your code uses old Swift 2.2 UIPickerView API. My suggestion for correction:
class ViewController: UIViewController,UIPickerViewDataSource,UIPickerViewDelegate {

@IBOutlet weak var timePicker: UIPickerView!

var timePickerData:[[Int]] = [[Int]]()

override func viewDidLoad()
{
    super.viewDidLoad()

    self.timePicker.delegate = self
    self.timePicker.dataSource = self

    timePickerData = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,52,  53, 54, 55, 56, 57, 58, 59], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,52,  53, 54, 55, 56, 57, 58, 59]]
}

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return timePickerData.count
}

// The number of rows of data
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
{
    return timePickerData[component].count
}

// The data to return for the row and component (column) that's being passed in
private func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> Int?
{
    return timePickerData[component][row]
}

}


text:
Q: How to make a frama-c WP warning into an error? This warning is a fairly serious one that I would like to turn into an error. I spent a lot of time puzzling over why a proof was not working before realising that this warning really could not be ignored.
[wp] <my source code>.c:16: Warning:
  Cast with incompatible pointers types (source: uint8*) (target: sint8*)

I believe that the answer should be something like
-wp-warn-key <category>=error

but I don't know how to find the category of "Cast with incompatible pointers types".
Can anyone help?

A: Unfortunately you can't do that for this particular type of warning. Warning categories are a relatively new addition to Frama-C (appearing in 17.0 Chlorine according to the Changelog, i.e. in 2018), and not all warnings that predate this feature have been given a proper category. Since you can only set the behavior of a warning category, category-less warnings can only be warnings.
Warnings with a category will start with [plugin-category], so that you can easily identify which category they belong to


text:
Q: Object Oriented Modeling Issue I have two tables

1= cities(cityId, CITY(string), CountryId)
2= countries(Id, CountryName(string))

I have two classes
public class CitiesList
{
    public int cityId{ get; set; }
    public int CountryId{ get; set; }
    public string CITY { get; set; }

    public List<CitiesList> GetCity()
    {

        //get city list
        //
        //

        var query = from o in dsResult.Tables[0].AsEnumerable()

        select new CitiesList
        {
            CITYID = o.Field<int>("CITYID"),
            CITY = o.Field<string>("CITY")
        };

        List<CitiesList> lstDisplay = new List<CitiesList>();
        lstDisplay.AddRange(query);

        return lstDisplay;
    }
}

public class CountriesList
{
    public int CountryId { get; set; }
    public string CountryName { get; set; }

    public List<CountriesList> GetDisplayCountryList()
    {
        //code
        //
        //

        var query = from o in dsResult.Tables[0].AsEnumerable()
        select new CountriesList
        {
            CountryName = o.Field<string>("CountryName"),
            CountryId = o.Field<int>("CountryId")
        }
    }
}

All this code is working well....Now what if i want a join query to display data from both tables?because i can assign data only to one list at a tyme?

A: I'd say you need a new data structure.  I'm envisioning something like a multi-map, where the key is the country and the value is a list of cities.
Data structures are good abstract data types, but I don't think the abstraction is complete.  Do you need another object somewhere besides lists or maps?


text:
Q: How do I get a floating button like uber I want to create a floating button like Uber. Uber shows a floating button when online and hides it when offline. Also "DU recorder" app has the floating button.
I want the floating button remain on top of all apps and be movable on any place on screen.
I have Samsung Galaxy S7 Edge with Android 8 (Oreo)

A: use this code

import android.content.Context;
import android.support.design.widget.FloatingActionButton;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class MovableFloatingActionButton extends FloatingActionButton implements View.OnTouchListener {

    private final static float CLICK_DRAG_TOLERANCE = 10; // Often, there will be a slight, unintentional, drag when the user taps the FAB, so we need to account for this.

    private float downRawX, downRawY;
    private float dX, dY;

    public MovableFloatingActionButton(Context context) {
        super(context);
        init();
    }

    public MovableFloatingActionButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MovableFloatingActionButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        setOnTouchListener(this);
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent){

        int action = motionEvent.getAction();
        if (action == MotionEvent.ACTION_DOWN) {

            downRawX = motionEvent.getRawX();
            downRawY = motionEvent.getRawY();
            dX = view.getX() - downRawX;
            dY = view.getY() - downRawY;

            return true; // Consumed

        }
        else if (action == MotionEvent.ACTION_MOVE) {

            int viewWidth = view.getWidth();
            int viewHeight = view.getHeight();

            View viewParent = (View)view.getParent();
            int parentWidth = viewParent.getWidth();
            int parentHeight = viewParent.getHeight();

            float newX = motionEvent.getRawX() + dX;
            newX = Math.max(0, newX); // Don't allow the FAB past the left hand side of the parent
            newX = Math.min(parentWidth - viewWidth, newX); // Don't allow the FAB past the right hand side of the parent

            float newY = motionEvent.getRawY() + dY;
            newY = Math.max(0, newY); // Don't allow the FAB past the top of the parent
            newY = Math.min(parentHeight - viewHeight, newY); // Don't allow the FAB past the bottom of the parent

            view.animate()
                    .x(newX)
                    .y(newY)
                    .setDuration(0)
                    .start();

            return true; // Consumed

        }
        else if (action == MotionEvent.ACTION_UP) {

            float upRawX = motionEvent.getRawX();
            float upRawY = motionEvent.getRawY();

            float upDX = upRawX - downRawX;
            float upDY = upRawY - downRawY;

            if (Math.abs(upDX) < CLICK_DRAG_TOLERANCE && Math.abs(upDY) < CLICK_DRAG_TOLERANCE) { // A click
                return performClick();
            }
            else { // A drag
                return true; // Consumed
            }

        }
        else {
            return super.onTouchEvent(motionEvent);
        }

    }

}

//-------------------this code inside the xml file -----------
<com.example.MovableFloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@drawable/ic_navigate_next_white_24dp"/>

A: Your question contains multiple questions so let us break it down and take it to step by step.
For Creating Floating Button:
I would say use @Vishal Sharma answer about this question in this page
And about showing and hiding it when the user is online or offline:
public class NetworkStateReceiver extends BroadcastReceiver {

    protected Set<NetworkStateReceiverListener> listeners;
    protected Boolean connected;

    public NetworkStateReceiver() {
        listeners = new HashSet<NetworkStateReceiverListener>();
        connected = null;
    }

    public void onReceive(Context context, Intent intent) {
        if(intent == null || intent.getExtras() == null)
            return;

        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = manager.getActiveNetworkInfo();

        if(ni != null && ni.getState() == NetworkInfo.State.CONNECTED) {
            connected = true;
        } else if(intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
            connected = false;
        }

        notifyStateToAll();
    }

    private void notifyStateToAll() {
        for(NetworkStateReceiverListener listener : listeners)
            notifyState(listener);
    }

    private void notifyState(NetworkStateReceiverListener listener) {
        if(connected == null || listener == null)
            return;

        if(connected == true)
            listener.networkAvailable();
        else
            listener.networkUnavailable();
    }

    public void addListener(NetworkStateReceiverListener l) {
        listeners.add(l);
        notifyState(l);
    }

    public void removeListener(NetworkStateReceiverListener l) {
        listeners.remove(l);
    }

    public interface NetworkStateReceiverListener {
        public void networkAvailable();
        public void networkUnavailable();
    }
}

YOUR ACTIVITY:
public class MyActivity implements NetworkStateReceiverListener {
    private NetworkStateReceiver networkStateReceiver;
}

IN YOUR ACTIVITY: INSTANTIATE THE RECEIVER
public void onCreate(Bundle savedInstanceState) {
    networkStateReceiver = new NetworkStateReceiver();
    networkStateReceiver.addListener(this);
    this.registerReceiver(networkStateReceiver, new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION));
}

public void onDestroy() {
    super.onDestroy();
    networkStateReceiver.removeListener(this);
    this.unregisterReceiver(networkStateReceiver);
}

IN YOUR ACTIVITY: IMPLEMENTS THE REQUIRED METHODS
@Override
public void networkAvailable() {
    /* TODO: show your button here */
}

@Override
public void networkUnavailable() {
    /* TODO: hide your button here */
}


text:
Q: jQuery UI tabs: Do not redirect to target selector I use jQuery tabs on my two tab form, everything is working and almost identical to the demo structure.

Tab 1

Tab 2

If I wanted to have the Tab 2 to open instead of the first (default), I will have just this URL: http://localhost/path/#tabs-two
However, I noticed something, right after the onload it is going to section of Tab 2 which I do not want because it is somewhere in the middle of the page. Is there something I can do to prevent this?

A: try something like this
Initialize the tabs with the active option specified:
$( "#tabs" ).tabs({ active: 1 });

REFERENCE
http://api.jqueryui.com/tabs/#option-active

A: You should use jquery to load the tab on page load depending on the hash.
In the links provide a different id than the tab ids. ie, stabs-two for the tabs-two
Tab 2

eg.
var hash = document.URL.substr(document.URL.indexOf('#')+1) ;
if(hash != ""){
   var tabId = hash.substring(1);
   var index = $('#tabs ul').index($('#'+tabId));
   $('#tabs ul').tabs('select', index);
}

This will solve the auto scroll to the element with id same as hash in URL.


text:
Q: Want to create UTF-8 with BOM csv file in c#  static void Main(string args[])
    {
        using (var streamWriter = new StreamWriter("D:\\path\\outputcsv"))
        {
          using (var csvWriter = new CsvWriter(streamWriter, CultureInfo.InvariantCulture))
            `

This is my code to create a file named output file which is giving me a utf-8 file
But my company need the output as utf-8 with bom file which I don't know how to create.
This is my file

This is what to get

I tried this
static void Main(string args[])
    {
        using (var streamWriter =new
 StreamWriter("D:\\path\\outputcsv",false,UTF8Encoding(false))
        {
          using (var csvWriter = new CsvWriter(streamWriter, CultureInfo.InvariantCulture))

but not working...
Thanks in advance:)
I've edited the code like this
using (var streamWriter = new StreamWriter("D:\path\Output.csv", true,UTF8Encoding(true)))
{
But still, it gives me the errors
1)cannot convert string to system.io.stream (on the file path)
2)cannot convert from bool to system.Text.Encoding
3)The name utf-8 encoding does not exist in the current context.
The solution provided to a similar question is not working for me.
I could solve these errors by changing the code to
   using (var streamWriter = new StreamWriter("D:\\path\\Output.csv", true, System.Text.Encoding.UTF8))

but it doesn't show "UTF-8 with bom" in my csv file notepad


text:
Q: performance.timeOrigin returning a date in the past After updating to Chrome 105, I noticed while debugging that I was seeing some really incorrect values when attempting to calculate TTFB on our website, and realized that in certain browser tabs I'm getting incorrect values for performance.timeOrigin.
Some sample output from the devtools console:
new Date()
> Mon Sep 19 2022 13:56:37 GMT-0500 (Central Daylight Time)
new Date(performance.timing.responseStart)
> Mon Sep 19 2022 13:56:14 GMT-0500 (Central Daylight Time)
new Date(performance.timeOrigin)
> Fri Sep 16 2022 21:39:16 GMT-0500 (Central Daylight Time)

You'll notice that the first two values are correct, while the last is almost 3 days in the past. This incorrect behavior survives reloading the tab, and even opening a new tab, and going to the same domain.
Reloading the tab and checking performance.timeOrigin will show that it continues to move forward in time like normal... but still almost 3 days in the past.
Interesting experimental results:

*

*Initial tab opened is example.com/a and shows bad performance.timeOrigin

*Opening a brand new tab, go to example.com/b and
performance.timeOrigin will still be bad.

*I can then type in a new url like google.com and performance.timeOrigin is correct.

*Then typing in example.com/c and performance.timeOrigin is bad again.

I'm thinking it may have something to do with hibernating/sleeping the computer, and any domains which were opened in Chrome at that time have their timeOrigin screwed up, but not completely sure.
Closing chrome and reopening seems to have fixed the problem, but I'm wondering if anybody know what exactly caused this?

A: I've also experience the same thing on Chrome 105, except that it is isolated to timeOrigin from iframe contents. But it looks like your hypothesis with regards to hibernation seems about right - see the following bug opened 5 days ago on Chromium bug tracker:
https://bugs.chromium.org/p/chromium/issues/detail?id=1365808&q=timeOrigin&can=2


text:
Q: I can't connect my nodejs server to my mariadb raspberry pi I'm trying to make a forum with a mariadb database on my raspberry pi (the nodejs server is on my computer and the database is on my raspberry)
I can't connect to my raspberry pi with a user...
i get this error :

SqlError: (conn=-1, no: 45028, SQLState: HY000) retrieve connection from pool timeout after 10015ms
    at Object.module.exports.createError (C:\Users\Josselin Arnaud\Desktop\forum\node_modules\mariadb\lib\misc\errors.js:56:10)
    at Pool._requestTimeoutHandler (C:\Users\Josselin Arnaud\Desktop\forum\node_modules\mariadb\lib\pool.js:332:18)
    at listOnTimeout (node:internal/timers:557:17)
    at processTimers (node:internal/timers:500:7) {
  text: 'retrieve connection from pool timeout after 10015ms',
  sql: null,
  fatal: false,
  errno: 45028,
  sqlState: 'HY000',
  code: 'ER_GET_CONNECTION_TIMEOUT'
}

and here is my code :

const pool = mariadb.createPool({
     host: '192.168.0.45',
     user:'root',
     password: '*hello*',
     connectionLimit: 5
});
pool.getConnection()
    .then(conn => {

      conn.query("SELECT * FROM forum.utilisateur")
        .then((rows) => {
          console.log(rows); //[ {val: 1}, meta: ... ]
          //Table must have been created before
          // " CREATE TABLE myTable (id int, val varchar(255)) "
          return conn.query("INSERT INTO forum.utilisateur value (?, ?)", [1, "mariadb", "mariadb", "mariadb", "mariadb"]);
        })
        .then((res) => {
          console.log(res); // { affectedRows: 1, insertId: 1, warningStatus: 0 }
          conn.end();
        })
        .catch(err => {
          //handle error
          console.log(err);
          conn.end();
        })

    }).catch(err => {
      //not connected
      console.log(err);
});


text:
Q: SQL database value to variable So, I am kinda new to php and mysql, but I have found a login form and adapted it to my needs as I dont have the knowledge to make one my self yet. I added a firstname and surname column into the database and the register form adds the values into the database fine.
Now I want to be able to display the firstname and surname onto a restricted page, the reason why I need this is because I want it to say: Welcome Jo Blogs. Below is the register form.
<?php

session_start();

if( isset($_SESSION['user_id']) ){
    header("Location: /");
}

require 'database.php';

$message = '';

if(!empty($_POST['email']) && !empty($_POST['password']) && !empty($_POST['firstname']) && !empty($_POST['surname'])):

    // Enter the new user in the database
    $sql = "INSERT INTO users (email, password, firstname, surname) VALUES (:email, :password, :firstname, :surname)";
    $stmt = $conn->prepare($sql);

    $stmt->bindParam(':email', $_POST['email']);
    $stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
    $stmt->bindParam(':firstname', $_POST['firstname']);
    $stmt->bindParam(':surname', $_POST['surname']);

    if( $stmt->execute() ):
        $message = 'Successfully created new user';
    else:
        $message = 'Sorry there must have been an issue creating your account';
    endif;

endif;

?>

<!DOCTYPE html>

    <title>Register</title>
    <?php include '../header.php'; ?>

    <?php if(!empty($message)): ?>

<?= $message ?>

    <?php endif; ?>

Register

    or login here

    <form action="register.php" method="POST">

        <input type="text" placeholder="Enter your email" name="email">
        <input type="password" placeholder="and password" name="password">
        <input type="password" placeholder="confirm password" name="confirm_password">
        <input type="text" placeholder="Enter your first name" name="firstname">
        <input type="text" placeholder="Enter your surname" name="surname">
        <input type="submit">

    </form>

And below here is the login form as im not really sure what you guys need to help me :)
<?php

session_start();

if( isset($_SESSION['user_id']) ){
    header("Location: /");
}

require 'database.php';

if(!empty($_POST['email']) && !empty($_POST['password'])):

    $records = $conn->prepare('SELECT id,email,password FROM users WHERE email = :email');
    $records->bindParam(':email', $_POST['email']);
    $records->execute();
    $results = $records->fetch(PDO::FETCH_ASSOC);

    $message = '';

    if(count($results) > 0 && password_verify($_POST['password'], $results['password']) ){

        $_SESSION['user_id'] = $results['id'];
        header("Location: /");

    } else {
        $message = 'Sorry, those credentials do not match';
    }

endif;

?>

<!DOCTYPE html>

    <title>Login</title>
    <?php include '../header.php'; ?>

    <?php if(!empty($message)): ?>

<?= $message ?>

    <?php endif; ?>

Login

    or register here

    <form action="login.php" method="POST">

        <input type="text" placeholder="Enter your email" name="email">
        <input type="password" placeholder="and password" name="password">
        <input type="submit">

    </form>

Also while I am here, I am currently using javascript to redirect to the homepage once you log out as i couldn't find any information on how to do it with php
Restricted.php:
<!DOCTYPE html>

    <title>Restricted Area</title>
    <link rel="stylesheet" type="text/css" href="../assets/css/style.css">
    <link href='http://fonts.googleapis.com/css?family=Comfortaa' rel='stylesheet' type='text/css'>
    <?php
    include '../header.php';
    ?>

    <?php
    session_start();

    if(isset($_SESSION['user_id'])) { ?>

Restriced Area

You have sucessfully logged in with your credentials

    <?php
    } else { ?>

    <?php
    exit;
    }

    ?>

Just let me know if you guys need any more information/code.
Thanks.

A: As Qirel suggested...
Restricted.php should resemble this:
<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header("Location: /login.php");  // no need to query
}
require('database.php');  // assumed to declare $conn=new PDO(...);
$loggedin = $conn->prepare('SELECT firstname,surname FROM users WHERE id=?');
$loggedin->execute([$_SESSION['user_id']]);
$results = $loggedin->fetch(PDO::FETCH_ASSOC);
if (!$results) {
    header("Location: /login.php");  // unsuccessful query
}
?>
<!DOCTYPE html>

    <title>Restricted Area</title>
    <link rel="stylesheet" type="text/css" href="../assets/css/style.css">
    <link href='http://fonts.googleapis.com/css?family=Comfortaa' rel='stylesheet' type='text/css'>
    <?php include '../header.php'; ?>

Restriced Area

You have successfully logged in with your credentials

    <?php echo "Welcome {$results['firstname']} {$results['surname']}"; ?>

Edit:
This statement borders on too serious but I would like to mention, especially to inexperienced php coders, that SESSION data can be hijacked (this is outlined in Pro PHP Security: From Application Security Principles to the Implementation of XSS Defense - Chapter 7: Preventing Session Hijacking) and so it can be suggested to never store any personal information in $_SESSION.  This would most critically include credit card numbers, government issued ids, and passwords; but would also extend into less assuming data like usernames, emails, phone numbers, etc which would allow a hacker to impersonate/compromise a legitimate user.
The internet is still very much in its "Wild West" era, and nothing is 100% safe.  ...and Internet Security is a rabbit hole / money pit.  Every coder should devote some time to understanding known threats and preventing them, but just how far to go with this will differ from person to person.

A: Maybe this??
In the first snippet after successfully adding a new user..
if( $stmt->execute() ):
    $message = 'Successfully created new user';
    $_SESSION['firstname'] = $_POST['firstname'];
    $_SESSION['surname'] = $_POST['surname'];
    # redirect to login or you could just
    # have the logged in at this point and..
    # redirect to restricted.php..
    header("Location: /login.php");
else:
    $message = 'Sorry there must have been an issue creating your account';
endif;

Then set up restricted.php like so:
<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header("Location: /login.php");
}
?>
<!DOCTYPE html>

    <title>Restricted Area</title>
    <link rel="stylesheet" type="text/css" href="../assets/css/style.css">
    <link href='http://fonts.googleapis.com/css?family=Comfortaa' rel='stylesheet' type='text/css'>
    <?php include '../header.php'; ?>

Welcome <?php echo $_SESSION['firstname']; ?> <?php echo $_SESSION['surname']; ?>

You have sucessfully logged in with your credentials


text:
Q: Viewing GCC Optimization Intermediates in GDB? I have a C++ program that I am trying to debug with GDB. I am building it with optimization, and I often run into the case where I want to debug something like:
int newVar = someArray[thing1 + thing2];

However, GCC is smart and optimizes code heavily. Perhaps at that point only intermediate thing1 + thing2 is stored, with the individual thing1 and thing2 having been overwritten. When I ask GDB to print thing1, I get <value optimized out>. Same for thing2.
So I have two questions:

*

*If I ask gdb to p thing1 + thing2, is it smart enough to realize that that intermediate is currently stored in a register? Or is it just going to try to naively evaluate the expression, realize that both the variables it uses are optimized out, and fail?

*How can I get a listing of what expression-evaluation intermediates are actually available at any given point in an execution? If it's storing &someArray + sizeof(int) * thing2 as the intermediate instead, I would like to know that. Does GCC not include sufficiently detailed information about its optimizations for GDB to figure out what intermediates are actually stored/how the compiler has decided to use each register? Is there some super-detailed multi-megabyte debugging info format that I could instruct GCC to produce? Is there another compiler/debugger pair that handles this better?
If I were to spend 20 minutes tracing through the assembly for the function, noting where thing1 and thing2 come in and when whatever is derived from them meets up with the address of someArray, I would be able to work this out manually. But I want the debugger to do it for me, since the compiler had to track all this stuff to do the optimization in the first place.

A:
If I ask gdb to p thing1 + thing2, is it smart enough to realize that that intermediate is currently stored in a register?

No, it will try the naive thing and fail.

How can I get a listing of what expression-evaluation intermediates are actually available at any given point in an execution?

You can't.

But I want the debugger to do it for me, since the compiler had to track all this stuff to do the optimization in the first place.

The compiler did track all this stuff, but then discarded the info after it generated the assembly. Without that info, the debugger can't possibly reconstruct it. (Well, in theory it's possible to do, but in practice it's very hard for any sufficiently aggressively optimized code.)
Having the compiler not discard the info is possible in theory, but is not practical: the resulting binary would be way too big, and I don't believe that current debugging formats support "the value of this complicated expression is stored in that register" descriptions well (if at all).


text:
Q: Is it possible to remove specific tool from bokeh toolbar specially bokeh logo and help icon? I have been doing a small project on plotting graph for my school on bokeh but bokeh toolbar is coming with unnecessary logos.is it possible to remove specific tools?
I have tried this but it's removing the entire toolbar
p.toolbar.logo = None
p.toolbar_location = None

A: If I understand you right you want to configure the toolbar to have only certain tools. So i rather add the tools that i want instead of removing them. And remove the logo:
from bokeh.plotting import show
from bokeh.models.tools import PanTool, SaveTool

p = figure()
p.line([1, 2, 3, 4],[1, 4, 3, 0])
p.toolbar.logo = None
p.tools = [SaveTool(), PanTool()]
show(p)

A: p.toolbar_location = None is specifically telling Bokeh not to display a toolbar anywhere. You only need the first line above.


text:
Q: Error "Vuex do not mutate vuex store state outside mutation handlers" when no mutation outside vuex occurs I have a mutation defined inside Vuex that looks like this:
setError(state, error) {
    state.error = error
    setTimeout(() => {
      state.error = null
    }, 5000)
  },

And I call it like this:
...
catch (error) {
          this.$store.commit('setError', error.response.data.error.message)
        }
...

When the timeout period expires, I get an error: [vuex] do not mutate vuex store state outside mutation handlers. I don't get it, because I'm not mutating anything outside of Vuex.
Can anyone suggest how to fix this?
I could fix this by simplifying setError to just assigning the error and dropping the setTimeout part, but I had to do this elsewhere like this:
flashError(message) {
      this.$store.commit('setError', message)
      setTimeout(() => {
        this.$store.commit('setError', null)
      }, 5000)
    },

This solution seems suboptimal because I want to be able to set this error temporarily everywhere
Many thanks

A: Based on our comment exchange, I created a sample component that demonstrates how to auto close a flash error without involving Vuex.
<template>

Flash Error with Auto Close

        <button class="btn btn-secondary" @click="triggerTimedErrorDisplay">Show Flash Error</button>

          {{ errorMessage }}

</template>


text:
Q: Failed to load resource: the server responded with a status of 404 (Not Found) http://eluxer.net/code?sesscheck=1&id=105&subid=51824_5848_ I use live-server to live reload folder with HTML, javascript and CSS files using Visual Studio Code.
When I open the console in Google Chrome I see this
:

"Failed to load resource: the server responded with a status of 404
  (Not Found)
  http://eluxer.net/code?sesscheck=1&id=105&subid=51824_5848_"

I tried this with many different folders and every time there is the same message with live-server. Аt the same time, there is no error message when I open the HTML file direct in the browser (without live-server).
Please, Can anyone tell me how to fix this?

A: I fixed the problem making this steps:

*

*Clear cache and cookies. Here You can see how.

*Reset Chrome this way: Click on "Customize and control Google Chrome" in the upper right corner => Click on "Settings" => then "Advanced" => "Reset and clean up" => "Reset" => Restart Chrome.

*Uninstall Chrome. For Windows 10 is this way: Close all Chrome windows and tabs => Right click on the "Start menu" => Click "Apps and Features" => Click on Google Chrome => Click "Uninstall" => (The current step will delete your user profile information, like your browser preferences, bookmarks and history, so if You want to save it, do it in advance! Mine profile information was save in my Google account.) Check this box "Also delete your browsing data" and click "Uninstall". Here is a video tutorial "How to uninstall Google Chrome web browser and remove all Google Chrome files from Your computer".

*Install fresh copy of Google Chrome
After all this, The Error was gone but I had a new one:

I removed this error this way.
Finally all is clear:

A: I faced this issue.
If you are just testing / developing. You can use Incognito, ctrl+shift+n
mode this quickly  clears the issue and you can proceed with testing/dev.
But please follow the other steps for a permanent fix.

A: In my case, I got the error because I was having issues trying to load a picture that the server could not find.
I solved by moving the picture from the root location to
\wwwroot\images\picture.jpg

A: The reason for the error may be;
You may not have defined the js file in the body with the script tag.


text:
Q: Simple pandas / numpy 'indexing' in vectorized calcs Sorry for a basic question. I'm sure the answer is quite simple, but I've banged my head against a wall for a while trying to figure it out. I'm new to python, but I understand the concept of vectorized computations. For instance, in the following (pretty trivial) piece of code:
import pandas as pd

ndx = ['a', 'b', 'c', 'd', 'e', 'f']
first = [3, 7, 2, 5, 9, 4]
second = [8, 9, 7, 3, 3, 7]

first = pd.DataFrame(first, index = ndx)
second = pd.DataFrame(second, index = ndx)

I know that first > second will return a boolean array, True where each element in a is greater than the corresponding element in b, matching the indexes. I understand that this rigid index matching is one of the benefits of using pandas, but...
Question: how can I efficiently reference "offset" indexes in a vectorized operation? For instance, what if I want to compare the next value in b with the current value in a (first['a'] > second['b'], first['b'] > second['c'], ...)? Along the same lines, what if I want to return True only if first['a'] is greater than both second['a] and second['b']?
I've written some code that does things like this iterating through the array by index. Here's an example:
        if next.at[curr.index[i], 'OI'] > curr.OI[i] and \
        next.at[curr.index[i+1], 'OI'] > curr.OI[i+1] and \
        next.at[curr.index[i], 'Vol'] > curr.Vol[i] and \
        next.at[curr.index[i+1], 'Vol'] > curr.Vol[i+1]:

(next and curr are DataFrames. OI and Vol are columns in those dataframes and i is my counter.) I know this is not pythonic and it's also super slow (which... hmmm... might be why it's not pythonic? lol)
Thank you in advance.
Summary: general question is how to reference offset elements in pandas (and numpy).
EDIT:
Thank you to Jaime and TomAugspurger for the answers for np and pd below. Got it... makes sense.
Followup question: How can I implement the pandas shift with dataframes that are different lengths? Imagine I have two time series that overlap but one extends before and the other extends after the other. So there are non-matching values in each index, and the indexes are (almost certainly) different lengths. pandas will not allow shift() with this error:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-15-35914edbe0ff> in <module>()
----> 1 aa = q['OI'] > r['OI']

C:\Python27\lib\site-packages\pandas\core\ops.pyc in wrapper(self, other)
    540             name = _maybe_match_name(self, other)
    541             if len(self) != len(other):
--> 542                 raise ValueError('Series lengths must match to compare')
    543             return self._constructor(na_op(self.values, other.values),
    544                                      index=self.index, name=name)

ValueError: Series lengths must match to compare

I suppose I could do a step and take the set defined by the union of the indexes, but that seems like an inefficient extra step. (I'm trying to learn correct coding practice as much (or more) than simply getting my project to work.) Any ideas on this? Thank you in advance.

A: Not sure about pandas, but in numpy you do this type of things by comparing offset slices. With your example of "comparing the next value with the current one" you could do something like:
>>> first = np.array([3, 7, 2, 5, 9, 4])
>>> second = np.array([8, 9, 7, 3, 3, 7])
>>> first[:-1] > second[1:]
array([False, False, False,  True,  True], dtype=bool)

The slicing obviously does not compare the last element of first, or the first of second, to anything.


text:
Q: No visible @interface for 'UIImageView' declares the selector 'setImageWithURL Hi I have a problem with new Xcode and AFNetworking.
On xcode5 I don't have that problems but I start to make some changes and updates.
Problem is:

No visible @interface for 'UIImageView' declares the selector
  'setImageWithURL

And code part:
  NSString *showThumb = [[[[SettingDataClass instance] getSetting] objectForKey:@"appearance_option"] objectForKey:@"category_browse_show_thumb"];
if([showThumb isEqualToString:@"show"])
{
UIImageView *img = [[UIImageView alloc] init];
img = cell.imageView;
[cell.imageView setImageWithURL:[NSURL URLWithString:[[ToolClass instance] decodeHTMLCharacterEntities:[[aryDic objectAtIndex:indexPath.row] objectForKey:@"thumb"]]]
        placeholderImage:[UIImage imageNamed:NSLocalizedString(@"image_loading_placeholder", nil)]
               completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {

                   img.image = [[ToolClass instance] imageByScalingAndCroppingForSize:CGSizeMake(57, 57) source:image];

               }];

Where could be a problem and why this code doesn't work with Xcode6?
I will be very grateful for help

A: Try including "UIImageView+AFNetworking.h" in the file that uses the method.

A: UIImageView does not work like that. You will need to add AFNetworking's UIImageView category to get the setImageWithURL method.

A: Here is the apples documentation about UIImageView. As You can see there is no method like setImageWithURL.
AFNetworking has subclass of UIImageView. It has a method named setImageWithURL. If you want to use this method you need to import that class. Hope this helps.. :)
You should be writing this:
img = cell.imageView;
[cell.imageView setImageWithURL:[NSURL URLWithString:[[ToolClass instance] decodeHTMLCharacterEntities:[[aryDic objectAtIndex:indexPath.row] objectForKey:@"thumb"]]]
        placeholderImage:[UIImage imageNamed:NSLocalizedString(@"image_loading_placeholder", nil)]
               completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {

                   img.image = [[ToolClass instance] imageByScalingAndCroppingForSize:CGSizeMake(57, 57) source:image];

               }];

And your cell should have a UIImageView+AFNetworking type of imageView.


text:
Q: Custom object deserializes fine in Jax-RS but if it is used in another object it doesn't work Deserializing works fine if I just pass my custom object through
@POST
public Response saveCustomObject(CustomObject data)
{
    // Prints correct value
    System.out.println(data);
}

However, if it is a property on another object, it just gets the default value of my custom object
@POST
public Response saveCustomObjectWrapper(CustomObjectWrapper data)
{
    // Prints incorrect value
    System.out.println(data.getCustomObject());
}

My provider is registered and looks like this:
public CustomObject readFrom(Class<CustomObject> type, Type type1, Annotation[] antns, MediaType mt, MultivaluedMap<String, String> mm, InputStream in) throws IOException, WebApplicationException
{
    try {
        return new CustomObject(IOUtils.toString(in));
    } catch (Exception ex) {
        throw new ProcessingException("Error deserializing a CustomObject.", ex);
    }
}

A: The problem is that the reader for all other objects doesn't do lookup/delegation while unmarshalling. What I mean by that, can be seen in this answer, where one reader looks up another reader based on the type. Assuming the format is JSON, whether you're using MOXy (the default with Glassfish) or Jackson, the result is the same. The reader is smart enough to handle the the JSON by itself, so doesn't need to lookup any other readers.
One solution would be to create another reader for the wrapper class, and do lookup/delegation, as seen in the link above. If you have a lot of these situations, you may can extend the default reader, and override its unmarshalling method, but I would completely advise against this, unless you really know what you're doing.
Another solution, depending on the serializer you're using, is to write JsonDeserializer (for Jackson) or XmlAdapter (for MOXy or Jackson). For Jackson an example would be something like (you can see a better example here)
public class CustomObjectDeserializer extends JsonDeserializer<CustomObject> {

    @Override
    public CustomObject deserialize(JsonParser jp, DeserializationContext dc)
            throws IOException, JsonProcessingException {
        JsonNode node = jp.getCodec().readTree(jp);
        return new CustomObject("Hello World");
    }
}

@JsonDeserialize(using = CustomObjectDeserializer.class)
public class CustomObject {
    public String message;
    public String getMessage() { return message; }
    public void setMessage(String message) { this.message = message; }
    public CustomObject(String message) { this.message = message; }
    public CustomObject(){}
}

In which case, there is no need for a custom reader at all. This will handle CustomObjects and objects that have CustomObject as a member. One problem with this is I'm not sure how or if you can get the InputStream. You just need to use the Jackson APIs to parse the JSON.
If you want to use Jackson instead of the default MOXy for glassfish, you can just add the Jackson dependency
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>2.13</version>
</dependency>

Then register the JacksonFeature, or simply disable MOXy, as mentioned here. If you want to continue using MOXy, I don't know if there is such thing as a class level adapter, so you will still need the reader as well as create a XmlAdapter for class members. It's a bit of a hassle, but that's why I recommend Jackson, for many other reasons, besides this particular use case. You can see an example of an adapter here
Now a lot of this answer is based on the assumption you are using JSON format, as you haven't specified the media type you are using. If it some other format, then I think maybe your only solution is to create another customer reader for the wrapper.


text:
Q: Save Application Wide Boolean in SharedPreference I know that this is a common question asked, and I have spent all afternoon trying different solutions that don't seem to work.
I am trying to store a boolean receiveNotifications in SharedPreferences but when I send a notification it still comes through. When I check whether the boolean is set in the activity I set it in, it says that the value is what it should be, but when I call this in my Firebase MessagingService it still allows the notification to come through.
This is my first time using them so if you see the obvious answer thats why.
Storing the Boolean:
// shared preferences
notificationsPref = mContext.getSharedPreferences("notifications", MODE_PRIVATE);
SharedPreferences.Editor editor = notificationsPref.edit();
                editor.putBoolean("receiveNotifications", false);
                editor.apply();

Checking if Boolean is Set:
// check if they want to receive notifications
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("notifications", MODE_PRIVATE);
Boolean areNotificationsAllowed = sharedPreferences.getBoolean("receiveNotifications", true);
if (areNotificationsAllowed){
        Toast.makeText(this, "Send Notification", Toast.LENGTH_SHORT).show();
        sendNotification(contentTitle, messageBody);
}

A: A push message is a Json object, next example is directly from the docs:
{
  "message":{
    "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "notification":{
      "title":"Portugal vs. Denmark",
      "body":"great match!"
    }
  }
}

There are 3 types of push messages, notification, data, and both;
  //Notification
  "message":{
    "notification":{
    }
  }

  //data
  "message":{
    "data":{
    }
  }

  //both
  "message":{
    "notification":{
    },
    "data":{
    }
  }

Each will trigger a different behavior in the app depending if the app is open or not.

*

*Notification: if the app is open the code on the service will be executed, if not the notification is showed by default

*Data: Always the code on the service will be executed

*Both: f the app is open the code on the service will be executed, if not the notification is showed by default and the data will be available in the launcher activity as extra obtainable from the intent
The Firebase web console will always send "notification" type and if you add data as custom params it will send both.
Your boolean will never be taken in consideration if the app is closed and the notification comes from the web console.

A:  private SharedPreferences prefs;
 private SharedPreferences.Editor editor;

 prefs = getApplicationContext().getSharedPreferences("notifiactions",
 MODE_PRIVATE);

 editor = prefs.edit();

 /////Assigning a Boolean///////////

editor.putBoolean("receiveNotifications", false);
editor.commit();

//Retrieving Boolean
 prefs = getApplicationContext().getSharedPreferences("notifications",
 MODE_PRIVATE);
 bool = prefs.getBoolean("receiveNotifications", true);

   //Try replacing this with your code also
     if(bool){

     }

A: Turns out that no matter what you do Firebase must override whatever you have set in the application. I found this out by instead of sending from the Firebase console, I sent notification from my web server. The notification was stopped perfectly and the Shared Preference worked.


text:
Q: Try to open file using Click Counter with PHP I want to prevent user from predicting the target script (test.php) AND do the whole "counter" logic on the server side.
I don't know how to achieve it with PHP.
I would like to open the file from the server side with PHP so the client will not have the possibility to see and know what file will open after 15 clicks. Because by typing the URL of the file it is possible to open it even before 15 clicks.
Thanks
HTML

        <button id="clap" class="clap-container" tabindex="-1"></button>

JAVASCRIPT
let accCounter = 0;
let totalCount = 0;

document.getElementById('totalCounter').innerText = totalCount;

document.getElementById('clap').onclick = function() {
    const clap = document.getElementById('clap');
    const clickCounter = document.getElementById("clicker");
    upClickCounter();
    loadDoc();
}

function upClickCounter() {
    const clickCounter = document.getElementById("clicker");
    const totalClickCounter = document.getElementById('totalCounter');

    accCounter ++;
    clickCounter.children[0].innerText = '+' + accCounter;
    totalClickCounter.innerText = totalCount + accCounter;
}

 function loadDoc() {
     var xhttp = new XMLHttpRequest();
     xhttp.onreadystatechange = function() {
         if (this.readyState == 4 && this.status == 200) {
             document.getElementById("view").innerHTML = this.responseText;
         }
     };
     xhttp.open("GET", "clickcheck.php", true);
     xhttp.send();

     document.getElementById("view").style.visibility="visible";
     if (totalCount + accCounter%15) {
     document.getElementById('view').style.visibility="hidden";
     }
     document.getElementById('overlay').style.display  = 'block';
     if (totalCount + accCounter%15) {
         document.getElementById('overlay').style.display  = 'none';
     }
    }

clickcheck.php:
<?php
session_start();
if (!array_key_exists('clickcount', $_SESSION)) {
    $_SESSION['clickcount'] = 1;
}
if ($_SESSION['clickcount'] < 15) {
    header('HTTP/1.1 404 Not found');
    exit();
} else {
    include("test.php");
}
?>


text:
Q: JQuery .clone() isn't working when an html5 form tag is present I'm trying to build a cloning plugin and started with the simple example they used on W3C.  At first when I tried it I would see the data blink on the page and disappear.  I saw nothing wrong in the console, I played with it in JS fiddle and got an error telling me to use "post", so I added the a post method to the form tag and still got the same result.
However when I took away the form tag, the clone worked.  Does anybody understand why this would happen?
Here's the HTML
<body>
    <fieldset id="question01">
        <input type="text" id="ques_01_text" placeholder="text01" name="ques_01" />
        <input type="text" id="ques_02_text" placeholder="text02" name="ques_02" />
        <input type="text" id="ques_03_text" placeholder="text03" name="ques_03" />
    </fieldset>

    <button>add</button>
</body>

Here's the Jquery
$(document).ready(function () {
    $("button").click(function () {
        $("#question01").clone().appendTo("body");
    });
});

A: when you have a button in a form, it acts as a submit button by default. That is to say, when you have this:
<button>add</button>

It actually gets interpreted as this:
<button type='submit'>add</button>

See here for more info: what's the standard behavior when < button > tag click? will it submit the form?
So when you click it, regardless of your click event, it still submits the form, which you don't want. That explains why it works when you don't have a form; there is nothing to submit, so it's submit action is inert. To make the button not submit, you can just change its type to button
<button type='button'>add</button>

And then when it is inside a form, it won't automatically submit when you click it.

A: Your form was submitting. If you don't want you form to submit specify that the button is just a "button" and not a "submit button"... like so:
<button type="button">Add</button>

Rather than
<button type="submit">Add</button>

A: Try this:
$($('#question01').get(0).cloneNode(true)).appendTo('body')