text:
Q: Front facing camera in UIImagePickerController I am developing the front facing camera app in iPad2 by using the UIImagePickerController.
When I capture the image it's shows as flipped from left to right.
How do I correct this?
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *imgPkr = [[UIImagePickerController alloc] init];
        imgPkr.delegate = self;
        imgPkr.sourceType = UIImagePickerControllerSourceTypeCamera;
        imgPkr.cameraDevice=UIImagePickerControllerCameraDeviceFront;

        UIImageView *anImageView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@"select%d.png",val]]];
        anImageView.frame = CGRectMake(0, 0, anImageView.image.size.width, anImageView.image.size.height);
        imgPkr.cameraOverlayView = anImageView;
        [theApp.TabViewControllerObject presentModalViewController:imgPkr animated:YES];
        [imgPkr release];
    }

A: You can flip the image from the source image use this
UIImage *flippedImage = [UIImage imageWithCGImage:picture.CGImage scale:picture.scale orientation:UIImageOrientationLeftMirrored];

Edit: Added swift code
let flippedImage = UIImage(CGImage: picture.CGImage, scale: picture.scale, orientation:.LeftMirrored)

A: Just to add how I have just achieved this without subclassing UIImagePickerController and without adding extra buttons to the camera view.
Simply listen for this notification which is fired several times whenever the camera is changed:
[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(cameraChanged:)
                                                 name:@"AVCaptureDeviceDidStartRunningNotification"
                                               object:nil];

Then use this method to flip the camera view:
- (void)cameraChanged:(NSNotification *)notification
{
    if(imagePicker.cameraDevice == UIImagePickerControllerCameraDeviceFront)
    {
        imagePicker.cameraViewTransform = CGAffineTransformIdentity;
        imagePicker.cameraViewTransform = CGAffineTransformScale(imagePicker.cameraViewTransform, -1,     1);
    } else {
        imagePicker.cameraViewTransform = CGAffineTransformIdentity;
    }
}

A: I know this question is really old but it seems like this is a still a common problem. Just set a CGAffineTransform on the cameraViewTransform property on a UIImagePickerController object.
let picker = UIImagePickerController()
picker.cameraViewTransform = CGAffineTransformScale(picker.cameraViewTransform, -1, 1)

A: Updated "bandog" answer for swift 4
let picker = UIImagePickerController()
picker.cameraViewTransform = picker.cameraViewTransform.scaledBy(x: -1, y: 1)

A: It looks like AVCaptureDeviceDidStartRunningNotification is no longer available as a means of detecting camera device changes. Also, the cameraDevice property on UIImagePickerController doesn't work with KVO. However, it's still possible to detect camera device changes, as shown below (though long-term support for this solution isn't guaranteed as we're using KVO on a property that isn't explicitly marked as KVO-compliant).
import AVFoundation

var context = 0

override func viewDidLoad() {
    super.viewDidLoad()
    // Register for notifications
    let notificationCenter = NSNotificationCenter.defaultCenter()
    notificationCenter.addObserver(self, selector: #selector(handleCaptureSessionDidStartRunning(_:)), name: AVCaptureSessionDidStartRunningNotification, object: nil)
    notificationCenter.addObserver(self, selector: #selector(handleCaptureSessionDidStopRunning(_:)), name: AVCaptureSessionDidStopRunningNotification, object: nil)
}

deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

func handleCaptureSessionDidStartRunning(notification: NSNotification) {
    guard let session = notification.object as? AVCaptureSession else { return }
    session.addObserver(self, forKeyPath: "inputs", options: [ .Old, .New ], context: &context)
}

func handleCaptureSessionDidStopRunning(notification: NSNotification) {
    guard let session = notification.object as? AVCaptureSession else { return }
    session.removeObserver(self, forKeyPath: "inputs")
}

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    if context == &self.context {
        if let inputs = change?[NSKeyValueChangeNewKey] as? [AnyObject], captureDevice = (inputs.first as? AVCaptureDeviceInput)?.device {
            switch captureDevice.position {
            case .Back: print("Switched to back camera")
            case .Front: print("Switched to front camera")
            case .Unspecified: break
            }
        }
    } else {
        super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
    }
}

Swift 4+ version:
import AVFoundation

var context = 0

override func viewDidLoad() {
    super.viewDidLoad()
    // Register for notifications
    let notificationCenter = NSNotificationCenter.defaultCenter()
    notificationCenter.addObserver(forName: NSNotification.Name(rawValue: "AVCaptureSessionDidStartRunningNotification"), object: nil, queue: nil) { [weak self] notification in
        self?.handleCaptureSessionDidStartRunning(notification: notification)
    }
    notificationCenter.addObserver(forName: NSNotification.Name(rawValue: "AVCaptureSessionDidStopRunningNotification"), object: nil, queue: nil) { [weak self] notification in
        self?.handleCaptureSessionDidStopRunning(notification: notification)
    }
}

deinit {
    NotificationCenter.default.removeObserver(self)
}

func handleCaptureSessionDidStartRunning(notification: Notification){
    guard let session = notification.object as? AVCaptureSession else { return }
    session.addObserver(self, forKeyPath: "inputs", options: [ .old, .new ], context: &context)
}

func handleCaptureSessionDidStopRunning(notification: Notification){
    guard let session = notification.object as? AVCaptureSession else { return }
    session.removeObserver(self, forKeyPath: "inputs")
}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if context == &self.context {
        if let inputs = change?[NSKeyValueChangeKey.newKey] as? [AnyObject], let captureDevice = (inputs.first as? AVCaptureDeviceInput)?.device {
            switch captureDevice.position {
            case .back: print("Switched to back camera")
            case .front: print("Switched to front camera")
            case .unspecified: break
            }
        }
    } else {
        super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
    }
}

A: It took me few hours, but I think I got there. Here is a working solution for Swift 5.2 of how to get correct image (both in ImagePicker preview and in output).

     //Registering to get notification when users takes a picture

    override func viewDidLoad() {
        NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "_UIImagePickerControllerUserDidCaptureItem"), object: nil, queue: nil) { (notification) in
            self.changePhotoOrientation()
    }

    //Changing image orientation for ImagePicker preview

    func changePhotoOrientation() {
        var subviews: [UIView] = [imagePicker.view]
        while (!subviews.isEmpty) {
            let subview = subviews.removeFirst()
            subviews += subview.subviews
            if (subview.isKind(of: UIImageView.self)) {
                subview.transform = self.imagePicker.cameraViewTransform.scaledBy(x: -1, y: 1)
            }
        }
    }

    //Changing image orientation for the output image

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let userPickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            image = UIImage(cgImage: userPickedImage.cgImage!, scale: userPickedImage.scale, orientation: .leftMirrored)
        }
    }

}

A: I had the same problem - and the solution above only got me half the answer, because the user had to approve the mirrored image before getting to the next page of my app - where I use the captured image after flipping it.
To solve this I had to flip the camera view whenever I switch to the front facing camera:
- (IBAction)flipCamera:(id)sender {
if(cameraUI.cameraDevice == UIImagePickerControllerCameraDeviceFront)
{
    cameraUI.cameraDevice = UIImagePickerControllerCameraDeviceRear;
}
else {
    cameraUI.cameraDevice = UIImagePickerControllerCameraDeviceFront;
}
cameraUI.cameraViewTransform = CGAffineTransformScale(cameraUI.cameraViewTransform, -1,     1);
}

Just to expand on this great answer, some typical complete code, Dec2013, iOS7 / Xcode5. Does everything. You just need an icon (cameraToggle.PNG in the example).
-(void)showTheDeviceCamera
    {
    if ( ! [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera] )
        return;

    // self.cameraController is a UIImagePickerController
    self.cameraController = [[UIImagePickerController alloc] init];
    self.cameraController.delegate = (id)self;
    self.cameraController.mediaTypes = @[(NSString *)kUTTypeImage];
    self.cameraController.allowsEditing = YES;
    self.cameraController.sourceType = UIImagePickerControllerSourceTypeCamera;
    [self presentViewController:self.cameraController animated:YES completion:NULL];

        // Add front-rear toggle button MANUALLY, IF NECESSARY
        // (You seem to usually get it for free, on iPhone, but
        // need to add manually on an iPad.)

        UIView *buttonView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cameraToggle"]];
        [buttonView sizeToFit];

        buttonView.userInteractionEnabled = YES;
        [self.cameraController.view addSubview:buttonView];

        UITapGestureRecognizer *tap =
            [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_frontRearButtonClicked) ];
        tap.numberOfTapsRequired = 1;
        [buttonView addGestureRecognizer:tap];

        // we'll add it at the top right .. could be anywhere you want
        buttonView.center = CGPointMake(
                self.cameraController.view.frame.size.width-buttonView.frame.size.width,
                3.0 * buttonView.frame.size.height
                );

    }

-(void)_frontRearButtonClicked
    {
    [UIView transitionWithView:self.cameraController.view
        duration:1.0
        options:UIViewAnimationOptionAllowAnimatedContent | UIViewAnimationOptionTransitionFlipFromLeft
        animations:^{
            if ( self.cameraController.cameraDevice == UIImagePickerControllerCameraDeviceRear )
                self.cameraController.cameraDevice = UIImagePickerControllerCameraDeviceFront;
            else
                self.cameraController.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        } completion:NULL];
    }

A: As the other answers, I had the same problem. As Yonatan Betzer mentioned, just flip the final image is only half the answer, because the preview image, displayed by the UIPickerController when you take a picture with the front camera, it's still inverted (mirrored).
Yonatan Betzer's anwser works great, but he did not mentioned how or where to put the action to change the camera device.
Based in some codes from internet, I created a Pod to get this wanted behavior:
https://github.com/lucasecf/LEMirroredImagePicker
After installed, you just have to call this two lines of code together with your UIImagePickerController:
self.mirrorFrontPicker = [[LEMirroredImagePicker alloc] initWithImagePicker:pickerController];
[self.mirrorFrontPicker mirrorFrontCamera];

And thats it, simply as that. You can check for more informations in the README of the github link.

A: Full Working Example in Swift, which answers to the initial question of this post (tested on an iPhone 5c using iOS 8.2):
        import UIKit

        class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIActionSheetDelegate {

         @IBOutlet var myUIImageView: UIImageView!

         var myUIImagePickerController: UIImagePickerController!

         override func viewDidLoad() {
             super.viewDidLoad()
         }

         override func viewWillAppear(animated: Bool) {
             println("viewWillAppear(animated: Bool) method called.")
             super.viewWillAppear(animated)
             NSNotificationCenter.defaultCenter().removeObserver(self)
         }

         override func viewWillDisappear(animated: Bool) {
             println("viewWillDisappear(animated: Bool) method called.")
             super.viewWillDisappear(animated)
             NSNotificationCenter.defaultCenter().addObserver(self, selector: "cameraChanged:", name: "AVCaptureDeviceDidStartRunningNotification", object: nil)
         }

         /* UIImagePickerControllerDelegate Section */
         func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
              if(self.myUIImagePickerController.sourceType == UIImagePickerControllerSourceType.Camera) {
                 self.myUIImageView.image = info[UIImagePickerControllerEditedImage] as? UIImage
              } else {
                 self.myUIImageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
              }
              self.dismissViewControllerAnimated(true, completion: nil)
         }

        func imagePickerControllerDidCancel(picker: UIImagePickerController) {
            self.dismissViewControllerAnimated(true, completion: nil)
        }

        /*
        You can choose to use one of the UIResponder methods:
        touchesBegan, touchesMoved, touchesEnded etc, in order to detect the touch
        on the UIImageView.
        */
        override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
            let touch: UITouch? = touches.anyObject() as? UITouch
            if (touch?.view == myUIImageView) {
                println("myUIImageView has been tapped by the user.")
                self.takingAPictureUsingTheCamera()
            }
        }

        func takingAPictureUsingTheCamera() {
            self.myUIImagePickerController = UIImagePickerController()
            self.myUIImagePickerController.delegate = self // Set the delegate
            self.myUIImagePickerController.sourceType = UIImagePickerControllerSourceType.Camera
            self.myUIImagePickerController.cameraDevice = UIImagePickerControllerCameraDevice.Front
    //        self.myUIImagePickerController.editing = true
            self.myUIImagePickerController.allowsEditing = true
            self.presentViewController(self.myUIImagePickerController, animated: true, completion: nil)
        }

        func cameraChanged(notification: NSNotification) {
             println("cameraChanged(notification: NSNotification) method called.")
             self.myUIImagePickerController.cameraViewTransform = CGAffineTransformIdentity
             if(self.myUIImagePickerController.cameraDevice == UIImagePickerControllerCameraDevice.Front){
                 self.myUIImagePickerController.cameraViewTransform = CGAffineTransformScale(self.myUIImagePickerController.cameraViewTransform, -1, 1)
             }
        }
       }// End class


text:
Q: Asp.NET MVC4 Redirect(url) throwing argument exception This seems impossible, I'm sure there is something very simple I am missing, but I just don't see it.
Inside of an action method I have this code
   var redirectUrl = FormsAuthentication.GetRedirectUrl(model.UserName, false);

   if (redirectUrl.IsBlank())
   {
       return RedirectToRoute(Routes.HomeUrl);
   }
   else
   {
       return Redirect(redirectUrl);
   }

And IsBlank() is implemented
  public static bool IsBlank(this string s)
  {
      return String.IsNullOrWhiteSpace(s);
  }

Somehow though
POST /login?ReturnUrl=
UserName=xxxx&Password=xxxx

manages to product this error
ArgumentException: Value cannot be null or empty.
Parameter name: url]
   System.Web.Mvc.Controller.Redirect(String url) +113
   WebHost.Controllers.SecurityController.Login(LoginModel model) +200
   lambda_method(Closure , ControllerBase , Object[] ) +104
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +182
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
   System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +28
   System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
   System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +58
   System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +225
   System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
   System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +24
   System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +99
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
   System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +39
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +31
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9629296
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

A: I think an action needs to be redirected to an action, rather than a simple URL.
Try something like this:
Response.Redirect(Url.RouteUrl(new{ controller="controller", action="action"}));

A: try this:
var redirectUrl = FormsAuthentication.GetRedirectUrl(model.UserName, false);

if ( Url.IsLocalUrl(redirectUrl) )
{
    return Redirect(redirectUrl);
}
else
{
    return RedirectToRoute(Routes.HomeUrl);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Alternative of Unity & SIO2 I am searching for open source free API just like Unity or SIO2 which I can use for commercial purpose. Kindly tell me if there is any API for iPhone 3D games.

A: AFAIK there are two open source game engines:
irrlicht
oolongengine
I don't know much about irrlicht, but there are some dicussions about it here on stackoverflow.com. I think they support iPhone development for quite a while. oolong seems to have a hard learning curve because there is not much documentation and you have to subscribe to a good old mailing list.
If you are an Indie developer with less than 100k $ / year, Bork 3D engine might be worth to look at - you just have to pay $49. There is one drawback in that you don't have support for blender and you should have to check whether collada files are useful, if you don't use a commercial 3D modelling tool.
Just found this in my bookmarks :-) It's a bit out of date but a good place to start investigations:
iPhone Game Engine Comparison – Open Source

A: UNREAL
also you can use Unreal game engine which will you help al ot in making high graphics games for iphone.

A: Being a paid SIO2 user (Android) - My opinion of SIO2 is that the registration scheme on Android is TERRIBLE.
I've had to move on to another product.
The author of SIO2 seems to feel that answering customer questions is beneath him and gives answers in riddle form, as opposed to d


text:
Q: JWS launch: "To restart Deployment Toolkit, please refresh the web page" I'm using the deployJava.js together with a primefaces commandbutton to launch a java web start app. Now this works perfectly on my own computers and browsers, but some users get the following popup
"To restart Deployment Toolkit, please refresh the web page".
Refreshing and then click button again just renders the same result.

The relevant code in play:
<h:head>
    <script type="text/javascript" src="http://java.com/js/deployJava.js" />
</h:head>
<h:body>
    <h:form>
        <p:commandButton value="Launch" onclick="javascript:
            if (!deployJava.isWebStartInstalled("1.7.0")) {
            if (deployJava.installLatestJRE()) {
            if (deployJava.launch("myjnlp.jnlp")) {}}} else {
            if (deployJava.launch("myjnlp.jnlp")) {}}"
        />
    </h:form>
</h:body>

I realise one solution to this problem likely is to do some setting on the client browser/system and if you know which one an answer is welcome.
But ideally I would want to change the code to also cover this use case without client-side workarounds.


text:
Q: particle models with network interaction - simultaneous estimation I am working on an application in behavioral ecology that combines network and particle interaction models. I have not been able to find any articles that simultaneously estimate these types of models and I was hoping that someone with more math background than myself could suggest any references.
First, we know that animals like wolves and birds, etc., form flocks or groups for hunting, protection, etc. There is a lot of work on flocking and swarming behaviors in the animal kingdom already. Second, many of these animal groups compete with each other for food--or form rivalries. So we can model these rivalries as a network, where each node is an animal group and an edge represents a rivalry. What I would like to do is understand the bi-directional interaction between (a) the network of rivalries producing changes in the flocking behavior of group (phase change), and (b) how phase changes in the flocking behavior of a group(s) can have a corresponding effect on the network or rivalries.
I have consulted the work on flocking and the work on networks, but I have not found anyone that integrates the two. Any references to articles or work would be appreciated.

A: Your question seems rather broad. Here's what a quick search yielded. I hope this is the sort of stuff you're looking for:
http://iotic.com/flock2/AS08_DSayers_Project.pdf
http://iotic.com/flock2/dsayers_evolflock_final.pdf

A: I think I found an answer to this question. There is some work being done on multi-species flocking by Xiaohui Cui. Very interesting work. It seems like a good foundation from which to build. Thanks for the input folks.


text:
Q: Get the data from "pins" on a Leaflet map There's a site with a Leaflet map that has pins on it. When I click on a pin, it makes a tooltip with some text in it. I want to get that text for each pin.
So I open Developer Tools. But where do I look?
What is the name of the JS variable that holds the text for each pin?

A: Leaflet popups generally only appear one at a time inside a .leaflet-popup-content element. It sounds like you need to dig around the underlying code to see where the bindPopup calls are taking place to see the data in its original form. Or rig up some sort of automated process to click every marker, get the content with jQuery's .text(), then move onto the next marker.


text:
Q: Get the View of the fragment, and disable the whole view In my main.xml layout, I have an <FrameLayout> element which is the fragment placeholder:
main.xml:
<FrameLayout
        android:id="@+id/fragment_placeholder"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>

I add Fragment programmatically to the above <FrameLayout> by:
fragmentTransaction.add(R.id.fragment_placeholder, fragment, null);

I can then use the replace() to change to other fragment:
fragmentTransaction.replace(R.id.fragment_placeholder, otherFragment, null);

At some point of my project, I need to get the current showing fragment, and disable everything on the view. I firstly successfully get the current showing fragment by :
Fragment currentFragment = fragmentManager.findFragmentById(R.id.fragment_placeholder);

Then, how can I disable the view of the fragment ? On the view, there could be buttons, is it possible to disable the whole view? If it is not possible, how can I add an overlay on the view?
I tried:
currentFragment.getView().setEnabled(false);

But, it does not work, I can still click on buttons on the view.

A: As per @Georgy's comment, here is a copy of the answer from Disable the touch events for all the views (credit to @peceps).

Here is a function for disabling all child views of some view group:
 /**
   * Enables/Disables all child views in a view group.
   *
   * @param viewGroup the view group
   * @param enabled true to enable, false to disable
   * the views.
   */
  public static void enableDisableViewGroup(ViewGroup viewGroup, boolean enabled) {
    int childCount = viewGroup.getChildCount();
    for (int i = 0; i < childCount; i++) {
      View view = viewGroup.getChildAt(i);
      view.setEnabled(enabled);
      if (view instanceof ViewGroup) {
        enableDisableViewGroup((ViewGroup) view, enabled);
      }
    }
  }

You can call this passing in your Fragment's view as retrieved by Fragment.getView(). Assuming that your fragment's view is a ViewGroup.

A: Here's a Kotlin implementation with @Marcel's suggestion.
fun ViewGroup.enableDisableViewGroup(enabled: Boolean, affectedViews: MutableList<View>) {
    for (i in 0 until childCount) {
        val view = getChildAt(i)
        if (view.isEnabled != enabled) {
            view.isEnabled = enabled
            affectedViews.add(view)
        }

        (view as? ViewGroup)?.enableDisableViewGroup(enabled, affectedViews)
    }
}

fun MutableList<View>.restoreStateAndClear(enabled: Boolean) {
    forEach { view -> view.isEnabled = enabled }
    clear()
}


text:
Q: Polymorphic Association with Comments - Ruby on Rails I am having a bit of trouble getting these polymorphic associations to work completely. I followed this tutorial www.railscasts.com/episodes/154-polymorphic-association, but that seems to only work if I am path /controller/ID#/comments when making a new post. If I try to render a partial comment form right on /controller/ID# I get this error when creating the comment:
undefined method `comments' for #<ActiveSupport::HashWithIndifferentAccess:0x10341b2d0>

I have three models:
class Comment < ActiveRecord::Base
    belongs_to :commentable, :polymorphic => true
end

class Post < ActiveRecord::Base
    belongs_to :user
    has_many :comments, :as => :commentable
end

class Article < ActiveRecord::Base
    belongs_to :user
    has_many :comments, :as => :commentable
end

And this is my view for /articles/#{ID}
<%= @article.title %>
<%= @article.content %>
<%= @article.user.login %>
<%= link_to 'Edit Article', edit_article_path(@article) %>

Comments

<%= render "comments/comments" %>
<%= render "comments/comment" %>

And here is my comment partial:

<%= form_for [@commentable, Comment.new] do |f| %>
    <%= f.text_area :content %>
    <%= f.submit "Post" %>
<% end %>

Here is my create method in the comments controller:
def create
    @commentable = find_commentable
    @comment = @commentable.comments.build(params[:comment])
    @comment.user_id = current_user.id
    if @comment.save
        redirect_to :id => nil
    else
        flash[:notice] = "something went wrong"
        redirect_to @commentable
    end
end

def find_commentable
    params.each do |name, value|
        if name =~ /(.+)_id$/
            return $1.classify.constantize.find(value)
        end
    end
end

I think I understand what the issue is, but not sure how to correct the problem. This form is looking for @commentable, but if the path isn't nested it cannot find @commentable (may be wrong).
Here are my routes:
devise_for :users do
        get "login", :to => "devise/sessions#new"
        get "register", :to => "devise/registrations#new"
    end

    resources :posts do
        resources :comments
        resources :tags
    end

    resources :articles do
        resources :comments
        resources :tags
    end

    resources :users do
        resources :articles
        resources :comments
        resources :tags
        resources :posts
    end

    resources :comments

    root :to => "home#index"

end

A: Your issue is that find_commentable is returning the params hash itself because the return statement never fired.
I deduced this by the error message because params.class == ActiveSupport::HashWithIndiffrentAccess
def find_commentable
    params.each do |name, value|
        if name =~ /(.+)_id$/
            return $1.classify.constantize.find(value)
        end
    end
end

I would add something like
def find_commentable
    params.each do |name, value|
        if name =~ /(.+)_id$/
            return $1.classify.constantize.find(value)
        end
    end
    raise ActiveRecord:NoRecord.new("Couldn\'t find it captain!")
end

The above exception type I think is correct, if not see what Comment.find_by_id(-1) or something like that raises. Should be something along those lines.
Edit
The reason I suggest raising the exception is because ApplicationController should be catching those and handling them gracefully when people start poling around and go to example.com/posts/9001

A: devise_for :users do
        get "login", :to => "devise/sessions#new"
        get "register", :to => "devise/registrations#new"
    end

    resources :posts do
        resources :comments
        resources :tags
    end

    resources :articles do
        resources :comments
        resources :tags
    end

    resources :users do
        resources :articles
        resources :comments
        resources :tags
        resources :posts
    end

    #REMOVE IT resources :comments

    root :to => "home#index"

end

and add
def index
    @commentable = find_commentable #this
    @comments = @commentable.comments

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @comments }
    end
  end


text:
Q: Bind to the reference, not the object Let's say you have an object, with a property, to which you bind a control. Like this:
MyClass MyObject = new MyClass();
MyObject.MyProperty = "Hello StackOverflow!";
MyTextBox.DataBindings.Add("Text", MyObject, nameOf(MyObject.MyProperty);

And you then change MyObject to a new instance of MyClass, like this:
MyObject = new MyClass();
MyObject.MyProperty = "I've made a new instance of my class...";

Then MyTextBox will still be bound to the instance of MyClass where MyProperty is set to "Hello StackOverflow!". Is there anyway to set the data bindings so that it sticks with the new instance of the class? I know that I could simply set the DataBindings again, but sometimes this isn't as simple as in this example.

A: Data bindings support property paths for the source property. So, as long as you put your MyObject variable in another object that can be used for data binding and expose that as a property, you can specify the property name referencing the property holding that value, then a dot, then the property you actually want.
For example, let's assume you have a Model class with a MyClass property value:
class Model : INotifyPropertyChanged
{
    private MyClass _myClass;
    public MyClass MyClass
    {
        get { return _myClass; }
        set { _UpdateField(ref _myClass, value); }
    }
}

(The above assumes a helper method _UpdateField() that handles updating the field and raising the PropertyChanged event as necessary.)
Then you can define your binding like so:
Model model = new Model(); // initialized somewhere you can access this reference later
model.MyClass.MyProperty = "Hello StackOverflow!";
MyTextBox.DataBindings.Add("Text", model,
    nameof(Model.MyClass) + "." +  nameof(MyClass.MyProperty);

Then, when you want to update the MyClass object, you change the model.MyClass property value. The binding will update the target value accordingly.

Here's a complete example (except the *.Designer.cs file…just make sure there's a Label and Button on the form, with their default names and subscribe the Button.Click event to the handler in the code below):
public partial class Form1 : Form
{
    private readonly C2[] _rgc2 =
    {
        new C2 { Text = "First C2" },
        new C2 { Text = "Second C2" },
    };

    private readonly C1 _c1 = new C1();

    private bool _toggle = false;

    public Form1()
    {
        InitializeComponent();
        label1.DataBindings.Add("Text", _c1, nameof(C1.C2) + "." + nameof(C2.Text));
        _UpdateC2();
    }

    private void _UpdateC2()
    {
        _c1.C2 = _rgc2[_toggle ? 1 : 0];
    }

    private void button1_Click(object sender, EventArgs e)
    {
        _toggle = !_toggle;
        _UpdateC2();
    }
}

class C1 : NotifyPropertyChangedBase
{
    private C2 _c2;

    public C2 C2
    {
        get { return _c2; }
        set { _UpdateField(ref _c2, value); }
    }
}

class C2 : NotifyPropertyChangedBase
{
    private string _text;

    public string Text
    {
        get { return _text; }
        set { _UpdateField(ref _text, value); }
    }
}

class NotifyPropertyChangedBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void _UpdateField<T>(ref T field, T newValue,
        Action<T> onChangedCallback = null,
        [CallerMemberName] string propertyName = null)
    {
        if (EqualityComparer<T>.Default.Equals(field, newValue))
        {
            return;
        }

        T oldValue = field;

        field = newValue;
        onChangedCallback?.Invoke(oldValue);
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}


text:
Q: Importing CSV into MySQL and I'm very new to using MySQL but have been tasked with creating a database to hold a considerable amount of client data.
The biggest issues I'm having is around normalization and how to import data to ensure it meets normalization rules. Obviously I could put everything into one big table and hope for the best but from anything I've read it will cause considerable problems down the road.
How should I embark on importing data that takes the following form (not actual data but form will be the same just more rows and more columns)
Unique Reg Num |Promotion  |Advert  |Characteristics
---------------|-----------|--------|----------------
123            |20% Off    |Aug 15  |Green;Blue;Purple
124            |10% Off    |Sep 14  |Purple;Red;Green
125            |20% Off    |Aug 15  |Green;Blue;Purple
126            |10% Off    |Sep 14  |Purple;Red;Green

So Promotion and Advert columns should be normalized and have separate tables (this is a many to one relationship I think) linked back to Unique Reg Num however the main issue is how to sort the Characteristics column. (I'll set up separate threads if needed for other questions)
I have several columns like the Characteristics column with delimited data. How should I upload this to a database so that data can be queried using these columns?
I could expand the rows for each delimited piece of data which would give me 3 rows of data for Unique Reg Num 123 (just using the sample table above). However, if I have another column with multiple characteristics, say 3 countries (Germany;France;Italy) then the number of rows trebles to 9 rows of data for Unique Reg Num 123.
I really have no idea how to begin to tackle this issue other than creating a big table.
I'm using MySQL 6.3, with MySQL Workbench. Currently set up in Win 7 for testing but will set actual database up on Windows Server 2012.
If I've left out any relevant info please let me know and I'll update the question.
Thanks in advance

A: Here is what your data should ideally look like.  I would split your sample table into two tables, one for promotion information and the other for characteristics:
promotions
Unique Reg Num |Promotion  |Advert
---------------|-----------|--------
123            |20% Off    |Aug 15
124            |10% Off    |Sep 14
125            |20% Off    |Aug 15
126            |10% Off    |Sep 14

characteristics
Unique Reg Num |Characteristic
---------------|----------------
123            | Green
123            | Blue
123            | Purple
124            | Purple
124            | Red
124            | Green
125            | Green
125            | Blue
125            | Purple
126            | Purple
126            | Red
126            | Green

These tables are fairly normalized, probably sufficient for your use case.  The challenge you face is in getting rid of that CSV data.


text:
Q: Install kernel-devel of specific version in fedora 19 So I have different "installed" kernel versions from the running kernel version, on my fedora 19 machine.
To give a more clear idea, here is my terminal output:
 [user@home ~]$ uname -r
 3.10.3-300.fc19.x86_64
 [user@home ~]$ rpm -qa | grep kernel-devel
 kernel-devel-3.10.6-200.fc19.x86_64
 kernel-devel-3.10.4-300.fc19.x86_64

When I install Nvidia drivers, it gives me this error that the installed and the running versions are not the same. I want to remove the currently installed 3.10.6-200 and 3.10.4-300 versions, and install the running version ( 3.10.3-300)instead. I don't know how to go about doing it. Any help will be appreciated!!

A: It's just complaining because you have newer versions of Kernels installed yet when you booted your system your Grub installation is still defaulting to an older version of the Kernel.
If you're using the EFI version of Grub then you'll likely find your default kernel to boot under /boot/efi. You'll want to change it to set default="0", so that it selects the latest Kernel.

A: Ideally you should be able to run:
yum install kernel-devel-3.10.3-300.fc19.x86_64
No package kernel-devel-3.10.3-300.fc19.x86_64 available.

But this packages is no longer available. It seems that you have been upgrading your system without actually rebooting it into a new kernel.
On my running system:
 yum info kernel|grep -E "Name|Version|Release"
Name        : kernel
Version     : 3.10.4
Release     : 300.fc19
Name        : kernel
Version     : 3.10.5
Release     : 201.fc19
Name        : kernel
Version     : 3.10.6
Release     : 200.fc19

uname -r
3.10.6-200.fc19.x86_64

yum info kernel-devel
Name        : kernel-devel
Version     : 3.10.4
Release     : 300.fc19
Name        : kernel-devel
Version     : 3.10.5
Release     : 201.fc19
Name        : kernel-devel
Version     : 3.10.6
Release     : 200.fc19

I advise you to do the following:
Check what kernel you have installed. Check the grub configuration and reboot into the new kernel. After that recompile nvidia drivers.
Unless there is a specific reason for you to stay with your current running kernel, then you will need to look for it. In the Fedora updates repo there is not such package anymore. You can check here


text:
Q: How nginx rewrite and proxy? http://sa.com/rabbitmq/api/#/queues/%2F/somequeue I try to use a single domain to proxy several programs like this:
http://sa.com/rabbitmq/ --->  http://localhost:15672/
http://sa.com/zabbix/ ---> http://localhost:10000/

and my conf is blow:
location /rabbitmq {
   rewrite /rabbitmq(.*) $1 break;
   proxy_pass http://localhost:15672;

It works well until I click a queue name to watch the detail,
which url is as the title said:
http://sa.com/rabbitmq/api/#/queues/%2F/somequeue
an 404 error occured, I saw an request in dev-tools of chrome:
http://rabbitmq.testing.gotokeep.com:15672/api/queues/%2F/dailyNewLike?lengths_age=60&lengths_incr=5&msg_rates_age=60&msg_rates_incr=5
this request returned 404.
I guess that when rewrite processed, the uri was decoded (.../%2F/... -> ...///...) and the extra slashes will be removed...
Is my guess right? Is there a solution?

A: Your guess is good, but no, the real problem is that nginx converts %2F into %252F (% -> %25).
%2F is vhost name (/). I don't found the real solution for this problem,  and my workaround was to use other vhost name which do not contains / symbol (e.g. pool1).

A: You can use $request_uri to prevent nginx decode the uri.
use conf like below
location /rabbitmq {
    if ($request_uri ~* "/rabbitmq/(.*)") {
        proxy_pass http://localhost:15672/$1;
    }
}


text:
Q: How to customize CSS of input element in iView? I use Vue's single file components and wanted to try iView UI framework. Consider there is following piece of code:
<template>

</template>

Then I want to change the width of my input. Just for example, to check that changes take effect:

But it has no effect. Tried i-input too.

Works as expected.
Which CSS selector should I use?

A: Vue/iView allows you to use the inline style attribute and pass it a width, or you can change the .ivu-input-wrapper CSS class and give it the with you want.

Vue.use(iview);
new Vue({
  data() {
    return {
      value: ''
    }
  }
}).$mount('#app')
@import url("//unpkg.com/iview/dist/styles/iview.css");
#app {
  padding: 32px;
}

.ivu-input-wrapper {
  width: 400px;
}


text:
Q: v-for not updating input error from store vuex In store i have passengers array. This array will be updating by calling some actions. For example, when I typing secondName in input, I get id and value of this input.
This data uploading in vuex. But when I want to check error this is not working for me and I don't know why. I have problem with v-for, because error is not reactive.

import CancelIcon from "@/components/icons/CancelIcon";
import ArrowDownIcon from "@/components/icons/ArrowDownIcon";
import MyDataButton from "@/components/MyDataButton";
import {mapState, mapActions, mapGetters} from 'vuex';

export default {
  name: "PassengersInfo",
  components: {MyDataButton, ArrowDownIcon, CancelIcon},
  methods: {
    ...mapActions([
        'updateSecondName',
        'validateNameField',
        'getPassengersArrays'
    ])
  },

  computed: {
    ...mapState({
      passengers: state => state.passengers,
    }),
    ...mapGetters([
       'getPassengers',
        'getError'
    ]),
  },
}

          <button
              v-for="passenger in getPassengers"
              :key="passenger.id"
              :class="{active: passenger.id === 1}"
              class="nav-link"
              :id="'passenger-'+passenger.id+'-tab'"
              data-bs-toggle="tab"
              :data-bs-target="'#passenger-'+passenger.id"
              type="button" role="tab"
              :aria-controls="'passenger-'+passenger.id"
              :aria-selected="{true : passenger.id === 1}"
          >Пассажир №{{passenger.id}}</button>

                  <MyDataButton class="d-none"/>

                      <input class="form-check-input" type="radio" v-on:click="oneWay=true" name="inlineRadioOptions" id="inlineRadio1" value="option1" checked>
                      В одну сторону

                      <input class="form-check-input" type="radio" v-on:click="oneWay=false"  name="inlineRadioOptions" id="inlineRadio2" value="option2">
                      Туда-обратно

                    <button type="button" class="remove-button" data-bs-toggle="modal" data-bs-target="#removeModal">
                      Убрать
                      <CancelIcon color="#1399FF"/>
                    </button>

                  Фамилия
                  <input
                      @input="updateSecondName($event);validateNameField($event);"
                      :value="passenger.secondName"
                      type="text"
                      class="form-control" :id="'secondName' + passenger.id"
                      placeholder="Иванов">

                  {{passenger.error}}

{{passenger.error}}

                  Имя
                  <input type="text" class="form-control" id="firstName" placeholder="Иван">

Укажите имя

                  Отчество
                  <input type="text" class="form-control" id="MiddleName" placeholder="Иванович">

Укажите отчество

                  Дата рождения
                  <input type="text" class="form-control" id="birthday" placeholder="дд.мм.гггг">

Некорректная дата, вам больше 125 лет?

                  Пол
                  <select id="gender" class="form-select">
                    <option selected>Мужской</option>
                    <option>Женский</option>
                  </select>

                  Гражданство
                  <select id="citizenship" class="form-select">
                    <option selected>Российская Федерация</option>
                    <option>...</option>
                  </select>

Выберите пол

                  Документ
                  <select id="document" class="form-select">
                    <option selected>Паспорт РФ</option>
                    <option>...</option>
                  </select>

                  Серия и номер документа
                  <input type="text" class="form-control" id="documentInfo" placeholder="01 23 456789">

Некорректные серия и номер документа

export const passengerModule = {
    state: () => ({
        passengers: [],
        tripId: 0,
        flightId: 0,
        placeNumber: [],
        isLogin: false,
        buyerInfo: {
            firstName: '',
            secondName: '',
            email: '',
            number: '',
        },
        promocode: '',
    }),
    mutations: {
        addArraysPassengers(state, arraysPassengers) {
            state.passengers.push(...arraysPassengers)
        },
        updateSecondName(state, {value, id}) {
            // state.passengers[id-1] = {id: Number(id),secondName: value}
            state.passengers[id-1].secondName = value;
        },
        updateError(state, [error, id]) {
            state.passengers[id-1].error = error
        }
    },
    actions: {
        async getPassengersArrays(ctx) {
            const arraysPassengers = [ctx.getters.getPassengersArrays];
            await ctx.commit('addArraysPassengers', arraysPassengers)
        },
        updateSecondName(ctx, event) {
            const value = event.target.value;
            //исключить наименование и оставить только цифры в id при помощи replace
            const id = event.target.id.replace(/[^0-9]/g,"");
            ctx.commit('updateSecondName', {value, id});
        },
        validateNameField(ctx, event) {
            const value = event.target.value;
            //получение названия поля
            const field = event.target.id.replace(/[0-9]/g, '')
            //исключить наименование и оставить только цифры в id при помощи replace
            const id = event.target.id.replace(/[^0-9]/g,"");
            if (field === 'secondName' && value === '') {
                ctx.commit('updateError', ['заполните фамилию', id]);
            }
            if (field === 'secondName' && value !== '') {
                ctx.commit('updateError', ['', id])
            }
        }
    },
    getters: {
        getPassengers(state, getters) {
            return state.passengers;
        },
        getPassengersArrays(state, getters) {
            return {id: getters.adults+getters.childrens}
        }
    },
}


text:
Q: version dependency error while using screenshots package Because every version of screenshots depends on YAML ^2.1.15 and flutter_piano depends on YAML ^3.0.0, screenshots are forbidden.
So, because flutter_piano depends on screenshots 2.1.0, version solving failed.


text:
Q: Why can I assign characters to string objects but not to vectors of string objects? C++ Primer says that character and string literals may be converted to strings.
I tried assigning a character to a string as:
std::string s;
s = 's';

And it gave me no error.
But, when I tried to assign characters to a vector of strings object as:
std::vector<std::string> svec;
svec = {'a', 'b'};

It gave me an error. Why?

A: The key to understanding this is initializer lists.
First, note that this does not work:
  std::string s('a');

but this does:
  std::string s{'a'};

The reason is that the first one would require a ctor that takes a single char, but std::string does not have such a constructor. The second, on the other hand, creates an initializer_list<char>, for which std::string does have a ctor.
The exact same reasoning applies to
  std::vector<std::string>> vs{ 'a', 'b' };

versus
  std::vector<std::string>> vs{ {'a'}, {'b'} };

The first wants to use a non-existent std::string ctor taking a char, and the second uses initializer lists.
As for the original code, the reason that
  std::string s;
  s = 'a';

works is that while std::string lacks a ctor taking a char, it does have an assignment operator which takes a char.

A: Consider the following example:
#include <initializer_list>
#include <vector>
#include <string>
#include <type_traits>

int main() {
    std::vector<std::string> svec;

    // Non-ambigously deduced to std::initializer_list<char>.
    auto a = {'a', 'b'};
    static_assert(std::is_same_v<std::initializer_list<char>, decltype(a)>);

    // (A)
    // error: no match for 'operator=' (... std::vector<std::string> and 'std::initializer_list<char>')
    //svec = a;
    //svec = std::initializer_list<char>{'a', 'b'};

    // error:
    // error: unable to deduce 'std::initializer_list<auto>' from '{{'a', 'b'}}'
    //auto b = {{'a', 'b'}};

    // (B)
    // OK.
    // After all the following copy assingnments, svec.size() is 1 (a single "ab" element).
    svec = {{'a', 'b'}};
    svec = std::initializer_list<std::string>{{'a', 'b'}};
    svec = std::initializer_list<std::string>{std::initializer_list<char>{'a', 'b'}};
    svec = std::initializer_list<std::string>{"ab"};
}

The error message at (A) is self-explanatory: there exist no copy assignment operator for std::vector<std::string> to assign a std::initializer_list<char> argument to it. The only near-viable overload of std::vector<T,Allocator>::operator= requires an argument of type std::initializer_list<T>:

vector& operator=( std::initializer_list<T> ilist );

Replaces the contents with those identified by initializer list ilist.

but T in this example is std::string, thus this overload is not viable.
In (B), on the other hand, we use the nested braced init syntax {{'a', 'b'}} such that the inner braced init list represents a std::initializer_list<char>, which may make use of the following std::string constructor:

basic_string( std::initializer_list<CharT> ilist,

                const Allocator& alloc = Allocator() );

to create a single std::string temporary which is in turned part of the outer braced init list, making use of std::vector copy assignment operator mention above:

vector& operator=( std::initializer_list<T> ilist )

The result of the different variations of (B) is the same: copy assigning to the svec vector a vector of a single std::string element.
Finally, note that if you were to copy assign to svec using a braced init list of "-separated strings, the result is copy assigning a vector of two elements:
svec = {"a", "b"};  // svec.size() is now 2

as we are no directly creating a std::initializer_list<std::string> of two elements, as compared to above where a std::initializer_list<char> of several characters result in a single string. I.e., a single std::string object is also a container of (zero or) several char elements.

A:
C++ Primer says that character and string literals may be converted to strings.

C-style string literals can convert to std::string implicitly, but chars can't.  That's different from assignment.
s = 's'; works because std::string has an overloaded operator= taking char.

*Replaces the contents with character ch as if by assign(std::addressof(ch), 1)

svec = {'a', 'b'}; doesn't work because std::vector only has overloaded operator=s taking std::vector or std::initializer_list, both of them can't be constructed from braced-init-list {'a', 'b'}. You might think the overload taking std::initializer_list<std::string> could be used for this case, but char can't be converted to std::string implicitly (std::string doesn't have such converting constructor taking a char), then std::initializer_list<std::string> failed to be constructed from {'a', 'b'}.
As the workaround, you can change the code to
svec = {"a", "b"};

"a" is of type const char[2] and decays const char*, which could be converted to std::string implicitly (via the std::string's converting constructor taking const char*), then std::initializer_list<std::string> gets constructed from {"a", "b"} and passed to std::vector::operator=. Of course svec = {std::string("a"), std::string("b")}; (or svec = {"a"s, "b"s};) works too, std::initializer_list<std::string> will be constructed directly without such implicit conversion to std::string.

A: The assignment of a character literal in the first expression works because the std::string class has an overload for the assignment operator that takes char.
The character literal arguments in the second expression cannot be implicitly converted to strings, like string literals can (i.e. svec = {"a", "b"}), because std::string has a constructor for const char* but not for char:
The expression:
svec = {"a", "b"};

uses the constructor
string (const char* s);

The expression:
svec = {'a', 'b'};

can't work because no such constructor exists that takes a single character argument.
What it does have is a constructor that takes an initializer_list (as you can see in the previous link):
string (initializer_list<char> il);

Available since C++11.
So to initialize std::string with character literals you need to use curly brackets (i.e. braced initializer list):
std::vector<std::string> svec;
svec = {{'a'}, {'b'}};

This will, as you know, initialize 2 strings in the first 2 positions of the vector one contains "a" and the other "b".
For a single string in the first position of the vector you can use:
svec = {{'a','b'}};


text:
Q: Javascript to input value into textbox instead of sendKeys() in Python I cant use send_Keys() method to input values in the current website im working on.
So im trying to use javascript to input values.
i tried click() and clear() together with send_keys() before i decided to use javascript but to my disappointment, it didnt work.
i use the javascript code to input value below
driver.execute_script("document.getElementById('CustCd').setAttribute('value', 'J590')")

and it worked.
But currently my code is inside a loop and the value changes, how can i replace J590 with a variable that gets the value?
Here is the code that i tried
ccr_No = XLUtlis.readData(path, 'ccr', r, 1)
driver.execute_script("document.getElementById('CCRNo').value=ccr_No")

I know its wrong, any help would be appreciated. My Javascript is weak.
Just some side note if anybody would be able to solve my send_keys() error.
The function only takes in the first character that i send. For example, send_keys("J590") gives J, send_keys("J590-TE21") gives J-

A: You need to insert the variable as variable, not literal
value = 'J590'
driver.execute_script(f"document.getElementById('CustCd').setAttribute('value', '{value}')")

A: First, the correct way to set the current value of an input is to assign to the value property. There is no attribute for the inputs current value (the value attribute is the input's default value, more here).
The rest is a special case of a general-purpose question: "How do I output a Python variable's value into JavaScript code?"
If the string you're outputting doesn't contain quotes or backslashes, you may get away with using a format string and outputting the value in quotes as Guy shows. (JavaScript has two kinds of quotes, ' and "; you only need to escape the kind you use around the value.) Those kinds of assumptions tend to break down, though; as soon as the string is Hi, I'm Joe that approach breaks.
In the general case, to ensure proper escaping and that all values are written correctly, you can use JSON:
import json
value = 'J590'
driver.execute_script(f"document.getElementById('CustCd').value = {json.dumps(value)};")

That outputs:
document.getElementById('CustCd').value = "J590";

Live Example
That way, you don't have to worry about quoting and escaping, it's all handled for you since valid JSON is valid JavaScript (thanks to a recent JavaScript specification fix; prior to that there was an edge case incompatibility that people almost never ran into).
It's also useful for numbers, or more complex things you might want to pass to hte JavaScript code. For instance:
import json

class Example:
    foo = ""
    bar = 0

    def __init__(self, foo, bar):
        self.foo = foo
        self.bar = bar

value = Example("I'm a string with \"quotes\" in it.", 42)
print(f"const obj = {json.dumps(value.__dict__)};")
num = 42
print(f"const num = {json.dumps(num)};")

That outputs:
const obj = {"foo": "I'm a string with \"quotes\" in it.", "bar": 42};
const num = 42;

obj ends up being an object, because the initializer is a valid JavaScript object literal containing the data from the Example object. Similarly, num is a valid JavaScript number.
Live Example

A: Using Javascript to input the values of a variable you can use the following solution:
ccr_No = XLUtlis.readData(path, 'ccr', r, 1)
# ccr_No = J590
driver.execute_script("document.getElementById('CCRNo').value='" + ccr_No + "';")

An example, to input the values of a variable within Search Box of Google Home Page:

*

*Code Block:
driver.get("https://www.google.com/")
value = 'J590'
driver.execute_script("document.getElementsByName('q')[0].value='" + value + "';")

*Browser Snapshot:

You can find a relevant discussion in Selenium : How to send variable character strings through executeScript()


text:
Q: Is it possible for a planetary system to orbit around something that wasn't a sun? Say for example that at the center of our solar system you replaced the sun, with something that wasn't a star, lets say that it was electrified and still produced the same amount of heat, would that planetary system be stable. If so that what else could a sun be replaced with, a water planet? a Gas giant? An Ice planet? A planet made of Uranium? what else could the center of a planetary system be replaced with?

A: If we assume all of the rest of the planets are neutral in charge, then only the mass of the sun matters for the Solar system. The gravity between the star and planets and other objects forms the main force that maintains the rotation of smaller objects around the sun and be stable for a long time. No matter what you fill in the sun, the mass of the sun should be far larger than other objects. Otherwise, objects will be rotating around some mass center outside of the sun which may cause collapse under some complicated movements. On the other hand, if the mass of the sun is very large as the current sun, then giant cloud of gas and ice may clash into a denser body because of the gravity. In the end, the sun will be a body with high pressure and high temperature like the usual stars you can talk.
If we assume all the rest of planets can be charged and ionized to orbit a electrified sun mainly due to the electrical force among them, then the planets themselves will have to compensate the repulsing force due to the charges of particles forming the planets. The most likely way to overcome this force is the gravity which is formed by the mass of the planet. We know that gravity is a relatively weak force compared with electrical forces, and it is unlikely to hold the planet balanced with gravity and electrical force -- unless its so densed as a black hole. However, it is possible to replace the sun with a charged black hole which has a large gravity field to maintain a large "solar" system with planets for a relatively long time no matter whether the planets are charged or not.

A: orbiting, graviting, means only mass maters.
It could be gaz, diamon, a bag of cockroach, or even a black hole, it would not change gravitational behaviors that orbits are.
( NB: yes, black hole too. Nothing different occurs in gravity as well when a star turn into blackhole. And it was attracting distant matter before exactly as well.)


text:
Q: Error:Could not initialize class org.gradle.api.internal.artifacts.ivyservice.ivyresolve.strategy.StaticVersionComparator I can not build project and every time I try below error is appear,

Error:Could not initialize class
  org.gradle.api.internal.artifacts.ivyservice.ivyresolve.strategy.StaticVersionComparator

this is my gradle :
 dependencies {
        classpath 'com.android.tools.build:gradle:2.1.0'

 }

Thanks!

A: I downloaded the latest gradle and changed my gradle, so problem solved, but of course its not the best solution!
sorry of my bad English.


text:
Q: How do I actually read an XML file in human form that makes sense? I downloaded a catalog and it is in XML format. How do change it from code to human-readable form, and ideally save it as a plain text file? I've never worked/seen these before; I tried messing with xslproc as it was recommended on here for somewhat similar things, but couldn't get it to work. I successfully loaded it in textWrangler, which formats it correctly (indents/colors/etc) in XML, but i don't see how I can actually 'run' it to print its contents. I also tried Excel, Word, Notepad, and just ended up with errors.
If that wasn't clear, i have stuff like this:
      51.9029244701
      47.0082067303

and I want it like this:
51.9029244701
47.0082067303

I want to make a text file with this catalog's information.

A: Late answer here: Ubuntu repository has a very good utility called xmlto that could help you. It converts xml to a variety of formats, including plain text, epub, pdf.
Online, there is Oxgarage which has many conversion options.

A: I wrote up a very simple Python script that will read in an xml file, and output its contents into another file:
import sys
inFile = open(sys.argv[1], 'r')
outFile = open(sys.argv[2], 'w')
read = True
for i in inFile.read():
    if i == '<':
        read = not read
    if read:
        outFile.write(i)
    if i == '>':
        read = not read

Save this as readxml.py and then call it from the shell like this: $ python readxml.py input.xml output.txt .  It's really rudimentary, so it might not be what you're looking for exactly, but it's something!

A: Try this:
grep "" yourfile.xml | awk -F "TD" '{gsub(">|</","",$0); print $2;}'

the output will be:
51.9029244701
47.0082067303

grep select xml TD tag, awk use TD as separator and remove > and </ from $2 field.
In order to select all node, try xslt transformation:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:output method="text" indent="yes"/>
   <xsl:template match="node()">
      <xsl:value-of select="." />
   </xsl:template>
</xsl:stylesheet>

This will output content of all node in your xml file.

A: This is easier than you think actually - XML elements have 4 'things' - a name, attributes, children and 'content'.
So you can iterate all the content elements and just print them (with or without a linefeed)
#!/usr/env/perl

use strict;
use warnings;

use XML::Twig;

my $twig = XML::Twig -> parsefile ( 'your_file');
print $_ -> text."\n" for grep { $_ -> is_pcdata } $twig -> get_xpath('//*');

This fishes out all the 'content' (pcdata) nodes, and prints them - one per line.
But really, when it comes to XML "human readable" is sort of the point. Why not just pretty print it and leave it at that, so the human reading it can ... well, read it, and not lose the data in the process.
You can reformat it if you like:
$twig -> set_pretty_print ('indented_a');
$twig -> print;

Which is a pretty good approximation of 'human readable'.


text:
Q: Inspire from Kantorovich Inequality Inspire from Kantorovich Inequality and my previous question. I am looking for a proof of the nice inequality as following:
Let $f(x)$ is a real continuous function that is strictly convex on $[m, M]$, let $m \le x_i \le M$, for $i=1,2,\ldots,n$ then show that:
$$nf\left(\frac{x_1+\cdots+x_n}{n}\right)+n\left(f(M)+f(m)-2f\left(\frac{M+m}{2}\right)\right) \ge f(x_1)+\cdots+f(x_n)$$
Equality holds if only if $m=x_1=x_2=\cdots=x_n=M$

A: This is true. Choose a linear function $\ell(x)$ such that $\ell(m)=f(m),\ell(M)=f(M)$. Denoting $g=f-\ell$ we get $g(m)=g(M)=0$ and have to prove $$ng\left(\frac{x_1+\cdots+x_n}{n}\right)-2ng\left(\frac{M+m}{2}\right) \geqslant g(x_1)+\cdots+g(x_n).$$
But $g$ is convex, thus $g$ is non-positive on $[m,M$]. So, RHS is non-positive, and it suffices to prove that LHS is non-negative.  Indeed, if we denote $t=\frac{x_1+\dots+x_n}n$, $s=\frac{m+M}2$, then $g(t)\geqslant g(t)+g(2s-t)\geqslant 2g(s)$.


text:
Q: SOAP-ERROR: Parsing WSDL:  'BillServicePortBinding' already defined Tengo este problema al tratar de consumir un webservice wsdl:
El código en php que estoy realizando para consumir el servicio web es el siguiente:

$wsdlURL = 'https://e-factura.sunat.gob.pe/ol-ti-itcpfegem/billService?wsdl';
$client  = new SoapClient($wsdlURL, array('trace' => true));
print_r($client);

Este es el error:

Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL:  'BillServicePortBinding' already defined in C:\xampp\htdocs\invoicePHP\xmlFactura.php:45 Stack trace

¿Cómo lo puedo solucionar?

A: Segun esta página oficial de PHP, es un bug desde la versión 5.*
Lo que recomiendan es usa la implementación Pear SOAP
http://pear.php.net/package/SOAP

A: El error se debe a que php no admite doble "namespace" cosa que si hace java y c#.
Por suerte tiene una solución fácil pero igual hay que tomarla con cuidado:
https://stackoverflow.com/questions/2342419/php-soapclient-problems-with-distributed-wsdl-file


text:
Q: Java ArrayList of ArrayList Scanner UserInput I am trying to store user input into ArrayList of ArrayList.
ArrayList<ArrayList<Integer>> a = new ArrayList<ArrayList<Integer>>();

For example, storing it as [[1,2,3],[4,5],[6,1,8]]
Below is my code,
    Scanner input = new Scanner(System.in);
    System.out.println("Enter a set of numbers:");
    String line = input.nextLine();
    String[] numbers = line.split(" +");

    ArrayList<ArrayList<Integer>> a = new ArrayList<ArrayList<Integer>>();
    ArrayList<Integer> a1 = new ArrayList<Integer>();

    for(int i=0; i<numbers.length; i++) {
        a1.add(new Integer(numbers[i]));

    }
    a.add(a1);

But then when I types it in to terminal, it becomes [[1,2,3,4,5,6,1,8]].
Thank you in advance!

A: Try this type of i/p and below code .
i/p : 1 2 3-4 5-6 1 8

String[] list= line.split("-");

ArrayList<ArrayList<Integer>> a = new ArrayList<ArrayList<Integer>>();
for(int i=0; i<list.length; i++) {

        String[] number= line.split(" ");
        ArrayList<Integer> a1 = new ArrayList<Integer>();
        for(int i=0; i<numbers.length; i++) {
            a1.add(new Integer(numbers[i]));

        }
        if(a1.length>0)
           a.add(a1);
}

A: From above comments I am bit clear what do you want to do.
You entered 1 2 3 4 5 6 1 8 on terminal. In your program you used split on - so I am providing some guidelines to solve your problem.
First, split your input on - to make the separation of arrays
String[] numbersArray = line.split("-");
//e.g. input 1 2 3 + 4 5 6 + 1 8
//here you will get numbersArray as [1 2 3,4 5 6,1 8]
ArrayList<ArrayList<Integer>> a = new ArrayList<ArrayList<Integer>>();

Now, to separate individual elements of inner array use for loop
for(int i=0; i<numbersArray.length; i++) {

    String[] numbers= numbersArray[i].split(" "); //split on " "
    //here you will get [1,2,3] for first iteration and 2nd [4,5,6], last [1,8]

    ArrayList<Integer> a1 = new ArrayList<Integer>();
    for(int j=0; j<numbers.length; j++) {
        a1.add(new Integer(numbers[j]));
        //here adding inner array list elements

    }
    //add to main array list
    a.add(a1);
}

A: I think it's due to the wrong input you are trying to enter on console, because when I hard code the ideal input to your ArrayList it prints the result as you expected. Here is the sample code that I wrote:
private static void doPrint(){
    List<List<Integer>> sample=new ArrayList<List<Integer>>();
    ArrayList<Integer> a1 = new ArrayList<Integer>();
    a1.add(12);
    a1.add(23);
    ArrayList<Integer> a2 = new ArrayList<Integer>();
    a2.add(22);
    a2.add(28);
    sample.add(a1);
    sample.add(a2);

    System.out.println(sample);
}

and here is the output:
[[12, 23], [22, 28]]

A: The way you are trying to use, will not work since you add all elements to inner list.
You can try some thing like following. You needs to create following arrays.
public static void main(String[] args) {
    ArrayList<ArrayList<Integer>> a = new ArrayList<>();
    int[] arr1={1,2,3}; // you need to create these arrays
    int[] arr2={4,5};
    int[] arr3={6,1,8};
    a.add(getList(arr1));
    a.add(getList(arr2));
    a.add(getList(arr3));
    System.out.println(a);
}

public static ArrayList<Integer> getList(int[] arr){
    ArrayList<Integer> list = new ArrayList<>();
    for (int anArr : arr) {
        list.add(anArr);
    }
    return list;
}

A: You are adding only one list to a that's why it seems like one element inside list a. If you want to have multiple elements inside list a then use like this.
for(int i=0; i<numbers.length; i++) {
        a1.add(new Integer(numbers[i]));
}
a.add(a1);
a.add(a1);

Output: As per input taken in your question
[[1,2,3,4,5,6,1,8], [1,2,3,4,5,6,1,8]]


text:
Q: Selecting or hightlight range of numbers using MATLAB Slider The default MATLAB Slider has one knob (value) only, Can I select range of values using the default slider? using two knobs or any other way?
I will be grateful if any one give an idea for a way to select a range of values using MATLAB Slider.

A: @excaza has mentioned the Undocumented matlab post that shows how to use a java based dual slider.
If you want to avoid getting wrapped in java you can just have two matlab sliders on top of one another. You can specify the click callback of these to then calculate the range of values, and limit the position relative to the other (if you aren't allowing a negative range).


text:
Q: Docker-compose persistent volume issue with elasticsearch I have a problem with mounting a volume for Elasticsearch in docker-compose. The mount is for another disk, mounted at: /mt/sda/ I am using the following docker-compose.yml:
version: "3.0"
services:
  elasticsearch:
    container_name: elastic-container-rescue
    image: docker.elastic.co/elasticsearch/elasticsearch:7.15.0
    volumes:
      - es-data:/mt/sda/es-data
    environment:
      - xpack.security.enabled=true
      - "discovery.type=single-node"
      - "ES_JAVA_OPTS=-Xms1g -Xmx1g"
      - "network.host:0.0.0.0"
      - ELASTIC_PASSWORD=$ES_PASS

    ports:
      - 9300:9200
    networks:
      - elastic
networks:
  elastic:
    driver: bridge
volumes:
  es-data:
    driver: local

When I check it with docker volume inspect, it still shows incorrect mountpoint - it should be: /mt/sda/es-data
    {
        "CreatedAt": "2021-11-09T13:51:05+01:00",
        "Driver": "local",
        "Labels": {
            "com.docker.compose.project": "rescue-es",
            "com.docker.compose.version": "1.25.5",
            "com.docker.compose.volume": "es-data"
        },
        "Mountpoint": "/var/lib/docker/volumes/rescue-es_es-data/_data",
        "Name": "rescue-es_es-data",
        "Options": null,
        "Scope": "local"
    }

Any suggestions on how to assign the correct mountpoint?

A: Elasticsearch Docker Container with Persistent Volume Configuration
docker-compose.yml
version: "3.0"
services:
  elasticsearch:
    container_name: elastic-container-rescue
    image: docker.elastic.co/elasticsearch/elasticsearch:7.15.0
    volumes:
      - es-data:/usr/share/elasticsearch/data
    environment:
      - xpack.security.enabled=true
      - "discovery.type=single-node"
      - "ES_JAVA_OPTS=-Xms1g -Xmx1g"
      - "network.host:0.0.0.0"
      - ELASTIC_PASSWORD=$ES_PASS

    ports:
      - 9300:9200
    networks:
      - elastic
networks:
  elastic:
    driver: bridge
volumes:
  es-data:
    driver: local
    driver_opts:
      o: bind
      type: none
      device: /mt/sda/es-data


text:
Q: How to run a seperate PHP file using a Button (Not a submit button inside a ) I have this button which is not a submit button, just a regualr button and it is not inside a <form> tag.
<button type="button" id="send" class="btn btn-outline-blue btn-sm">Send</button>

I need to execute a separate PHP file (send.php) when I click on the send button
I know how to do this if the button is a type="submit" and is inside a <form>
But in this kind of a situation, I can't think of how to do it. Please HELP...

A: Don't use a button. Use a regular link. Use CSS to make it look however you like.
Alternatively, make it a submit button and put it inside a form. The form doesn't need anything else in it. You can style the form to be display: inline if you like.
Alternatively, add a click event handler with JavaScript which assigns a new value to location.
Alternatively, add a click event handler with JavaScript which uses the XMLHttpRequest object or the fetch object to make an HTTP request without leaving the page.

A: You can use ajax to call the php class on button click event

A: Here's how I did it:
with some research I ended up writing this javascript code which use ajax
Here it's my HTML

    <input type="text" id="subject" name="subject" class="form-control ">
    subject

    <input type="text" name="to" id="to" class="form-control ">
    Your email

    <input type="text"  name="message" id="message" class="form-control">
    Message

Here's my PHP file
<?php
    $mailto=$_POST['to'];
    $mailSub=$_POST['subject'];
    $mailMSG=$_POST['message'];
    require 'PHPMailer-master/PHPMailerAutoload.php';
    $mail = new PHPMailer();
    $mail ->IsSmtp();
    $mail ->SMTPDebug=0;
    $mail ->SMTPAuth=true;
    $mail ->SMTPSecure='tls';
    $mail ->Host='smtp.gmail.com';
    $mail ->Port= 587; //465; //or 587
    $mail ->IsHTML(true);
    $mail ->Username="myemail";
    $mail ->Password="password";
    $mail ->SetFrom("email");
    $mail ->Subject=$mailSub;
    $mail ->Body=$mailMSG;
    $mail ->AddAddress($mailto);

    if(!$mail ->Send() || !isset($mailto) || trim($mailto)=='' || !isset($mailSub) || trim($mailSub)=='' || !isset($mailMSG) || trim($mailMSG)=='' ){
                echo '';
    }else{
        echo '';
    }
?>

This is myjavascript in HTML file...

Well, hope you can get understand about this. Thanks everyone helped :)


text:
Q: Why is 'stod' still not declared in this scope even after C++11 is enabled and I have included string? I am having an error while trying to convert a string vector to a double vector. The error keeps saying:
error: 'stod' was not declared in this scope

Even though I enabled C++11 for my compiler and I used #include <string> I also used using namespace std; And it still didn't work.
The code is is down below:
#include <iostream>
#include <cmath>
#include <string>
#include <algorithm>
#include <vector>
#include <sstream>

using namespace std;
using stod;
transform(userNums.begin(), userNums.end(), back_inserter(convUserNums), [](const string & astr){ return stod( astr) ; } ) ;

A: stod is defined in the namespace std. You should call it like std::stod.
Or put using namespace std; above.

A: Be sure to include the necessary header and using directive.
#include <string>

using std::stod;

int main( const int, const char** )
{
    stod( "3.4" );

    return EXIT_SUCCESS;
}

Please find the std::stod documentation here. Note that this function will throw both std::invalid_argument and std::out_of_range exceptions. A try-catch block is highly recommended.
The example was built with g++ -o main main.cpp -std=c++11 under gcc version 4.9.2 (Debian 4.9.2-10).


text:
Q: Android MessageQueue We know main(UI) Thread is having implicit Looper attach with it so that its having MessageQueue.
And we also know that we can attach MessageQueue to worker thread with the help of Looper.prepare()
My question is that is it both Queue are same?

A: It's not the same MessageQueue, when you call Looper.loop() in a new thread, a new MessageQueue will attache to the new created thread. Then we usually use Handler to communicate with the thread. The main UI thread's MessageQueue is created by system when you app start. You can compare the message queues by their reference.
private static final String TAG = MainActivity.class.getSimpleName();
private Handler mHandler;
private MessageQueue messageQueue;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    messageQueue = Looper.myQueue();
    new Thread() {

        @Override
        public void run() {
            super.run();
            Looper.prepare();
            mHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    if (Looper.myQueue().equals(messageQueue)) {
                        Log.d(TAG, "same message queue");
                    } else {
                        Log.d(TAG, "not the same queue");
                    }
                }
            };
            mHandler.sendEmptyMessage(0);
            Looper.loop();
        }
    }.start();
}

Here is a related discussion.


text:
Q: Why is this a memory copying error - Insure++ false positive? I've been trying run Insure++ with some scientific code and it reports many errors, although to be fair it officially does not support K&R C and I don't know what having a lot of K&R functions has done to its evaluation process. The C and C++ code it is testing is being run in a DLL invoked from a WPF application.
One error report that puzzles me is the following, which I'm confident is safe code but am trying to work out why it thinks is an error (it does work). I'd be interested if anyone has an insight into why this might be an error condition.
[MacImagePlot.c:984] **READ_OVERFLOW**
SetCursorQD(*GetCursorQD(watchCursor));

Reading overflows memory: GetCursorQD(watchCursor)

bbbbb
| 4 | 4 |
    rrrrr

Reading (r) : 0x5639d164 thru 0x5639d167 (4 bytes)
From block (b) : 0x5639d160 thru 0x5639d163 (4 bytes)
gWatchCursor, declared at WPFMacGraphics.cpp, 418

for some very simple code.
    typedef int Cursor;
    typedef Cursor* CursPtr;
    typedef CursPtr* CursHandle;
    CursHandle GetCursorQD (short cursorID);
    void SetCursorQD (const Cursor *crsr);
    enum {
    ....
     watchCursor =  4
    };

    // file globals
    Cursor gWatchCursor=watchCursor;
    CursPtr gWatchCursorPtr = &gWatchCursor;

    CursHandle GetCursorQD (short cursorID)
    {
      if (cursorID==watchCursor)  // this is actually the only case ever called
        return &gWatchCursorPtr;
      return 0;
    }

A: I'm not familiar at all with the tools you're talking about, but have you verified that your GetCursorQD function is returning the pointer you expect and not NULL/0?
Perhaps something wonky happened with your enum definition for watchCursor (such as it being declared differently elsewhere, or it picking up a local variable instead of the enum).

A: I hate to say it but I suspect your problem is going to be the lack of some arcane function modifiers needed to ensure that data on the stack isn't getting munged when crossing the DLL boundary.  I'd suggest writing a simple app that replicates the code but does it all in one module and see if Insure++ still detects an error.  If it doesn't, get ready to wade through __declspec documentation.

A: I assume that the following line is the Problem:
  if (cursorID==watchCursor)

*

*cursorID is  defined as short (usually 2 Bytes)

*watchCursor is part of a enum and thus of type int (4 Bytes on a 32Bit OS)
This actually is not a problem. The compiler will cast one of both parameters correctly, as far as the enum value will not exceed a 2 Byte range.
By my experience all static (as well as runtime-) code analysis tools  report many false positives (i tried some of them). They of course help, but it takes quite a while to assert false positives from real bugs.

A: Like Soapbox, I am not familiar with Insure++.
But looking at the code, it is admittedly a bit confusing...so
That typedef makes CursHandle effectively a pointer to pointer to int...

*

*CursHandle is a pointer of type CursPtr

*CursPtr is a pointer of type Cursor

*Cursor is typedef'd to type int

yet in the GetCursorQD, you are using a 'double address of' int? The reason I say 'double address' is the function is returning a address of gWatchCursorPtr (&gWatchCursorPtr) of type CursHandle, which in turn is a global variable which is a address of gWatchCursor (&gWatchCursor) which is of type Cursor.
Your definition of the return type for the function does not match up with the global variable name's typeof despite the typedef's...that's what my thinking is...
Hope this helps,
Best regards,
Tom.


text:
Q: Canvas perde a qualidade ao salvar frame de vídeo Estou utilizando uma função que captura um frame do vídeo para posteriormente defini-la como thumbnail.
function thumbnail()
    {
        var canvas = document.getElementById('thumb');
        $('#thumb').css('width',$('#video').css('width'));
        $('#thumb').css('height',$('#video').css('height'));

        var video = document.getElementById('video');
        canvas.getContext('2d').drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, canvas.width, canvas.height);
    }

Este frame será definido pelo usuário, então toda vez que ele clicar em um determinado botão, essa função será chamada.
A função funciona corretamente, mas acontece que quando o determinado frame é replicado para o canvas, a imagem perde a qualidade e não fica como é no vídeo.
Eis a imagem de exemplo:

Na esquerda é o vídeo sendo reproduzido, enquanto na direita é a thumb gerada depois do clique no botão. (A qualidade do vídeo não é das melhores, mas reparem na legenda que está bem definida e olhem como ela fica na imagem gerada pelo canvas).
Como faço para que a qualidade da imagem gerada seja fiel ao frame do meu vídeo?


text:
Q: Hadoop reduce become slower when there are less reduce task I'm experiencing a really weird case when I am doing some performance tuning of Hadoop. I was running a job with large intermediate output (like InvertedIndex or WordCount without combiner), the network and computation resources are all homogeneous. According to how mapreduce work, when there is more WAVES of reduce task, the overall run time should be slower as there is less overlap between map and shuffle, but it is not the case. It turns out that the job with 5 WAVES of reduce task is about 10% faster than the one with only one WAVE of task. And I checked the log and it turns out that the map tasks' execution time is longer when there is less reduce tasks, also, the overall computation time(not shuffle or merge) during reduce phase is longer when there is less task. I tried to rule out other factors by setting reduce slow-start factor to be 1 so that there is no overlap between map and shuffle, I also limited it to be only one reduce task to be executed at the same time so there is no overlap between reduce tasks, and I modified the scheduler to force mapper and reducer to locate on different machines so there is no I/O congestion. Even with above approach, the same thing still happen. (I also set the map memory buffer to be large enough and the io.sort.factor to be 32 or even larger and io.sort.mb to be larger than 320 accordingly)
I really can't think of any other reason that cause this problem, so any suggestions would be greatly appreciated!
Just in case of confusion, the problem I am experiencing is:
0. I'm comparing the performance of running 1 reduce task vs 5 reduce task of the same job under all other same configurations. There is only one tasktracker for reduce computation.
1. I have forced all reduce task to be executed sequentially by having only one tasktracker for redcue task in both cases, and mapred.tasktracker.reduce.tasks.maximum=1, so there won't be any parallelism during reduce phase
2. I have set mapred.reduce.slowstart.completed.maps=1 so none of the reducer will start to pull data before all map is done
3. It turns out that having one reduce task is slower than having 5 SEQUENTIAL reduce tasks!
4. Even if I set set mapred.reduce.slowstart.completed.maps=0.05 to allow overlap between map & shuffle, (thus when there is only one reduce task, the overlap should be more and it should run faster, because the 5 reduce task are SEQUENTIALLY executing) the 5-reduce-task is still faster than 1-reduce task and the map phase of 1-reduce task become slower!

A: This is not a problem. The more reduce tasks you have, the faster your data gets processed.
The outputs of the map phase are sent to the reducers . If you have two reducers, the load is distributed between the two reducers.
Incase of the wordcount example, you will have two seperate files with count divided between them. So you will have to manually add the total, or run another map reduce job to calculate the total if you had lots of reduce tasks.

A: This is as expected, if you only have a single reducer than your job has a single point of failure. Your number of reducers should be set to about 90% capacity. You can find your reduce capacity by multiplying your number of reduce slots with your total number of nodes. I have found that it is also good practice to use a combiner if it is applicable.

A: If you have just 1 reduce task, then that reducer has to wait for all mappers to finish, and the shuffle phase has to collect all intermediate data to be redirected to just that one reducer. So, it's natural that the map and shuffle times are larger, and so is the overall time, if you have just one reducer.
However if you have more reducers, your data gets processed in parallel, and that makes it faster. Again, if you have too many reducers, then there's too much data being shuffled around, resulting in increase in network traffic. So you have to find that optimal number of reducers which gives you a good balance.

A: The right number of reduces seems to be 0.95 or 1.75 * (nodes * mapred.tasktracker.tasks.maximum). At 0.95 all of the reduces can launch immediately and start transfering map outputs as the maps finish. At 1.75 the faster nodes will finish their first round of reduces and launch a second round of reduces doing a much better job of load balancing.
courtesy:
http://wiki.apache.org/hadoop/HowManyMapsAndReduces
Setting the number of map tasks and reduce tasks
(similar question wirth resolved answer)
Hope this helps!


text:
Q: What's the most efficient way to batch UPDATE queries in MySQL? I'm writing an application that needs to flush out a large number of updates to the database for an extended period of time, and I've gotten stuck at how to optimize the query. Currently I'm using INSERT INTO ... VALUES (..), (..) ON DUPLICATE KEY UPDATE, which works to batch all of the values into one query, but executes excruciatingly slowly on large tables. I don't ever actually need to insert rows.
Other approaches I've seen are to update using SET value = CASE WHEN... (which would be hard to generate due to the way I'm building the queries, and I'm not sure about the performance of CASE for hundreds/thousands of keys), and simply multiple concatenated updates. Would either of these be faster than my current method?
It baffles me that, as far as I can tell, there's no idiomatic, efficient way to do this in MySQL. If there really isn't a way that's faster than ON DUPLICATE KEY, would it be worth it to switch to PostgreSQL and use its UPDATE FROM syntax?
Any other suggestions are also greatly appreciated!
Edit: here's one of the tables that gets updated frequently. I've removed column names due to them being irrelevant.
CREATE TABLE IF NOT EXISTS `table` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `a` bigint(20) unsigned NOT NULL DEFAULT '0',
  `b` bigint(20) unsigned NOT NULL DEFAULT '0',
  `c` enum('0','1','2') NOT NULL DEFAULT '0',
  `d` char(32) NOT NULL,
  -- trimmed --
  PRIMARY KEY (`id`),
  KEY `a` (`a`),
  KEY `b` (`b`),
  KEY `c` (`c`),
  KEY `d` (`d`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

A: Since you're using InnoDB tables, the most obvious optimization would be to group multiple UPDATEs into a transaction.
With InnoDB, being a transactional engine, you pay not just for the UPDATE itself, but also for all the transactional overhead: managing the transaction buffer, transaction log, flushing the log to disk.
If you are logically comfortable with the idea, try and group 100-1000 UPDATEs at a time, each time wrapped like this:
START TRANSACTION;
UPDATE ...
UPDATE ...
UPDATE ...
UPDATE ...
COMMIT;

Possible downsides:

*

*One error will collapse the entire transaction (but would be easily fixed in code)

*You might wait for a long time to accumulate your 1000 UPDATEs, so you might also want to have some timeout

*More complexity on your application code.


text:
Q: How do I create a word document in rails I'm attempting to create a word document from inside my rails app.
I gave the htmltoword gem a go and it's close to working.
Where it falls down.  If I have a spelling mistake in the content, and open the document generated, word doesn't highlight the mistake. Word also doesn't find the mistake when I do a manual spell check.
I think it might have to do with "compatibility mode", but I'm not sure.
I'm wondering if anyone knows a better way to make a "true" word doc.
I'm also wondering if anyone has see this behaviour and corrected for it. I need spelling to work.

A: Looking at the htmltoword gem source...It looks like they set the proofState to clean by default...
In the source code, templates/default/word/settings.xml has this line that "Gets or sets the state of the spelling checker in this document."...
<w:proofState w:spelling="clean" w:grammar="clean"/>
It has two possible values...clean (the default) or dirty (which seems to be what you want).
So, you can either modify the config (maybe this will help) or use your own cloned version of the gem if there is no way to modify this.


text:
Q: Can I use URLSession in a function with return? I have this function recovering the player score from a MySQL database. From other tutorials, I have found the URLSession approach useful when sending data out from the app, but would I be able to actually use the return of the function anywhere? Kept searching for something like a
task.resume()
task.end()
return (rank, name, score)

?
func downloadLocalScores(_ choice: Int) -> ([String], [String], [String]) {
    var url: URL
    let id: String = getUserID("id")
    if choice == 0 {
        url = NSURL(string: "myPHPscript.php")! as URL
    } else {
        url = NSURL(string: "myPHPscript2.php")! as URL
    }
    let request = NSMutableURLRequest(url: url)
    request.httpMethod = "POST"
    let postString = "id=\(id)"
    request.httpBody = postString.data(using: String.Encoding.utf8)
    var name: [String] = []
    var score: [String] = []
    var rank: [String] = []
    if Reachability().isInternetAvailable() == true {
        let task = URLSession.shared.dataTask(with: request as URLRequest) {
            data, response, error in
            if error == nil {
                let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
                let variables = try! JSONSerialization.jsonObject(with: data! as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSArray
                for i in 0..<variables.count {
                    let level = variables[i] as! [String:AnyObject]
                    name.append(level["name"] as! String)
                    score.append(level["score"] as! String)
                    rank.append(level["rank"] as! String)
                }
            } else {
                print(error)
            }
        }
        task.resume()
        return (rank, name, score)
    } else {
        return (["NO CONNECTION"], ["0"])
    }
}

I have another function to download scores, but being a request for top scores, doesn't need to take any input from app
func downloadScores(_ choice: Int) -> ([String], [String]) {
var url: URL
if choice == 0 {
     url = NSURL(string: "myPHPscript.php")! as URL
} else {
     url = NSURL(string: "myPHPscript2.php")! as URL
}
let data = NSData(contentsOf: url)
var variables: NSArray = []
if Reachability().isInternetAvailable() == true {
    variables = try! JSONSerialization.jsonObject(with: data! as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSArray

    var name: [String] = []
    var score: [String] = []

    for i in 0..<variables.count {
        let level = variables[i] as! [String:AnyObject]
        name.append(level["name"] as! String)
        score.append(level["score"] as! String)
    }
    return (name, score)
} else {
    return (["No connection"], [""])
}

}
I am still not perfectly familiar with other options of sending data out of my app, so could the last function be adapted to POST? Have tried something last night but got stuck at data = NSData asking for a type URL instead of the NSMutableURLRequest I had.
Should mention I created global variables and append inside first function, but the result is recovered after they are used and I can't find a way to delay or refresh once they have been filled. I don't mind app waiting for them, as they are used after the viewDidLoad().

A: You cant return because a network requests happen asychronously. Instead of using a return, use a closure that is called when the request has completed. Check out the following:
func sendRequest(_ _request:URLRequest, completion:@escaping (_ success:Bool,_ error:Error?, _ _data:[String:AnyObject]?)->Void) -> URLSessionDataTask {
    let session:URLSession = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: self.queue)
    let task:URLSessionDataTask = session.dataTask(with: _request) { (_data, _response, _error) in
        if let resultsDic:[String:AnyObject] = self.parseJSONFromData(retrievedData, withInitalKey: self.getInitialKey()){
            completion(true, nil, resultsDic)
        } else {
            completion(false, nil, nil)
        }
    }
    task.resume()
    return task
}

A: I created a small example to show the difference between the input, return, and async completion.  Paste this into your playground and experiment.
You'll see the 'passed in' prints first.
Followed by the return.
And last the completion when the async has finished.
import UIKit
import PlaygroundSupport
import Foundation

func getStuffFromServer(_ passedIn: String, completion: @escaping (_ completion: String)->()) -> String {

    print(passedIn)

    PlaygroundPage.current.needsIndefiniteExecution = true

    URLSession.shared.dataTask(with: URL(string: "http://stackoverflow.com")!) {
    result in

        completion("I've completed")

        PlaygroundPage.current.finishExecution()

    }.resume()

    let returnValue = "I'm being returned"
    print(returnValue)
    return returnValue
}

let returned = getStuffFromServer("I'm passed in", completion: { completion in
    print(completion)
})


text:
Q: why while reading a file we always check for -1? I am trying to read the file from "read.txt"and while reading a file we always check for -1 (line:while(readfile!=-1).
Why we always check  the end file by  comparing it with "-1".Is there any specific reason?
(int readfile = filereadrer.read();)always returns unicode value by this argument does -1 means the unicode value of end of file,if it is then how we got to know that unicode value of end of file is "-1"
public class FilesPractise {

   public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub

     File file = new File("read.txt");

     file.createNewFile();

     FileReader filereadrer = new FileReader(file);

     int readfile = filereadrer.read();

       while(readfile!=-1){
            System.out.println((char)readfile);

             readfile = filereadrer.read();
    }

}

}

A: These things can be found out in the documentation of the methods. For example, the method that you are trying to find out about is read, from FileReader.
Here is the documentation for the read method: https://docs.oracle.com/javase/8/docs/api/java/io/InputStreamReader.html#read--
In the page, under the "Returns" section,

The character read, or -1 if the end of the stream has been reached

See? That's how you get to know these things.

A:
Why we always check the end file by comparing it with "-1".Is there any specific reason?

Because if you don't you will never detect end of stream and you will loop endlessly.

(int readfile = filereadrer.read();) always returns unicode value

No it doesn't. It returns -1 or a Unicode value. See the Javadoc.

by this argument

This is not an argument. It is a false assumption.

does -1 means the unicode value of end of file

There is no such thing as (a) a Unicode value of -1 or (b) a Unicode value of end of file.

if it is

It isn't.

then how we got to know that unicode value of end of file is "-1"

It isn't either -1 or "-1". It is a sentinel value returned by the API instead of a Unicode value.