text:
Q: Static background image location in obj-c (similar to background-attachment: fixed) I am trying to create a view that, no matter how it's moved, will keep its background image at the same location.  So, if the view is dragged around, the background stays put, similar to background-attachment:fixed in css3.
My problem is that clipsToBounds = YES does not appear to work.  The image still takes up the whole screen and does not get clipped to the parent's frame.  Any ideas?
@implementation StaticBackgroundView {
    UIImageView *imageView;
}

// Must be init'd from code or won't work
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"myImage.png"]];
        imageView.clipsToBounds = YES;
        self.clipsToBounds = YES;

        [self addSubview:imageView];
        [self sendSubviewToBack:imageView];
    }
    return self;
}

- (void) setFrame:(CGRect)frame
{
    // Call the parent class to move the view
    [super setFrame:frame];

    // Do your custom code here.
    NSLog(@"Setframe");
    imageView.frame = CGRectMake(-1*frame.origin.x, frame.origin.y, imageView.frame.size.width, imageView.frame.size.height);
}

A: Whenever the StaticBackgroundView gets moved - the background image center must also be adjusted.
In the example given below, updateBackgroundImage is called every time the StaticBackgroundView gets moved during a PanGesture update.
-(void)updateBackgroundImage
{
    imageView.center = CGPointMake(( (imageView.image.size.width*0.5) - self.center.x) + (self.bounds.size.width*0.5)
                               ,     ((imageView.image.size.height*0.5) - self.center.y) + (self.bounds.size.height*0.5));
}

If you move the StaticBackgroundView towards to right, the image gets moved towards the left and appears to remain static beneath the StaticBackgroundView.
Example code below which allows you to use your finger to move the StaticBackgroundView about and show a static image beneath:
StaticBackgroundView.h
#import <UIKit/UIKit.h>
@interface StaticBackgroundView : UIView
-(void)updateBackgroundImage;
@end

StaticBackgroundView.m
#import "StaticBackgroundView.h"

@implementation StaticBackgroundView {
    UIImageView *imageView;
}

// Must be init'd from code or won't work
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        NSLog(@"StaticBackgroundView:initWithFrame");

        if([[UIDevice currentDevice]userInterfaceIdiom]==UIUserInterfaceIdiomPhone)
        {
            if ([[UIScreen mainScreen] bounds].size.height == 568)
            {
                NSLog(@"iPhone5 image");
                imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"myImage-568h"]];
            }
            else
            {
                NSLog(@"iPhone4 image");
                imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"myImage"]];
            }
        }
        self.clipsToBounds = YES;
        [self updateBackgroundImage];
        [self addSubview:imageView];
        [self sendSubviewToBack:imageView];
    }
    return self;
}

-(void)updateBackgroundImage
{
    imageView.center = CGPointMake(( (imageView.image.size.width*0.5) - self.center.x) + (self.bounds.size.width*0.5)
                               ,     ((imageView.image.size.height*0.5) - self.center.y) + (self.bounds.size.height*0.5));
}

ViewController.m
#import "ViewController.h"
#import "StaticBackgroundView.h"

@interface ViewController ()

@property (strong, nonatomic)  StaticBackgroundView *outletStaticView;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.outletStaticView = [[StaticBackgroundView alloc] initWithFrame:CGRectMake(100, 100, 120, 150)];
    [self.view addSubview:self.outletStaticView];

    UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];

    [self.outletStaticView addGestureRecognizer:panGestureRecognizer];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)handlePan:(UIPanGestureRecognizer *)gestureRecognizer
{

    if([gestureRecognizer state] == UIGestureRecognizerStateChanged)
    {

        CGPoint translation = [gestureRecognizer translationInView:self.view];

        gestureRecognizer.view.center = CGPointMake(gestureRecognizer.view.center.x + translation.x, gestureRecognizer.view.center.y + translation.y);

        [gestureRecognizer setTranslation:CGPointMake(0, 0) inView:self.view];

        StaticBackgroundView * theView = (StaticBackgroundView*)gestureRecognizer.view;
        [theView updateBackgroundImage];

    }

}
@end


text:
Q: Writing partition for quicksort in scheme I am having a lot of trouble with writing scheme...
I am trying to write quicksort using scheme.  I have seen tons of answers but they don't really make any sense to me and this is mostly because I barely understand functional programming at all.
I have defined my pivot like this:
(define (pivot lis)
  (car lis))

That works fine (and is easy to write..)
For my understanding of the partition function, you have the original list and then you split it into 2 new lists, one that contains values larger than the pivot, and one that contains values smaller or equal to the pivot.
This is how I've tried to implement it:
(define (partition lis)
  (if (null? lis) '())
  (else (lambda (lis1 lis2)
          (if (< (car lis) pivot) append lis1)
          (partition (append lis2)))))

This is the error I'm getting:
. else: not allowed as an expression in: (else (lambda (lis1 lis2) (if (< (car lis) pivot) append lis1) (partition (append lis2))))
I am not really sure how to do this, any ideas on how I can make this work?  Or is my reasoning off?

A: (define (partition ls)
  (partition-aux ls (pivot ls) '() '()))

(define (parition-aux ls pivot smaller larger)
  (cond
    ((empty? ls) (list smaller larger))
    ((< (car ls) pivot)
     (parition-aux (cdr ls) pivot (cons (car ls) smaller) larger))
    (else
     (partition-aux (cdr ls) pivot smaller (cons (car ls) larger)))))

you need to define another function to do the job. because you need 2 more arguments to hold the list of smaller and larger numbers. This is one way of doing it. there are other ways that are shorter to type. but I wanted to be explicit.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Determine max peaks in a time series R I would like to calculate the months where the peaks occur in this time series and determine if these changes over the analysed record. Can I get this info from the phase? How can I do it in R?
This is the time series
 [1] -2.566983e-02 -5.782524e-02 -7.808027e-02 -7.600751e-02 -5.500182e-02 -1.794568e-02  2.287965e-02  6.176569e-02  8.517858e-02  8.618686e-02  6.599044e-02  2.595632e-02
 [13] -2.468891e-02 -7.291849e-02 -1.013152e-01 -1.052718e-01 -7.944368e-02 -2.482406e-02  3.896659e-02  9.315530e-02  1.286337e-01  1.274909e-01  9.111597e-02  2.842469e-02
 [25] -4.845922e-02 -1.157328e-01 -1.537427e-01 -1.534016e-01 -1.060450e-01 -2.458452e-02  6.501879e-02  1.385970e-01  1.746728e-01  1.629937e-01  1.037831e-01  1.111534e-02
 [37] -8.784113e-02 -1.601244e-01 -1.872461e-01 -1.614843e-01 -9.001538e-02  8.044579e-03  1.037991e-01  1.691924e-01  1.878601e-01  1.587651e-01  8.405491e-02 -1.356792e-02
 [49] -1.069555e-01 -1.710607e-01 -1.853867e-01 -1.499666e-01 -7.398990e-02  1.654048e-02  1.006945e-01  1.533522e-01  1.701250e-01  1.431100e-01  8.169068e-02  2.343733e-05
 [61] -8.011875e-02 -1.382533e-01 -1.624560e-01 -1.458858e-01 -9.018088e-02 -1.271360e-02  6.579380e-02  1.277067e-01  1.637702e-01  1.500510e-01  1.026965e-01  2.813767e-02
 [73] -5.578174e-02 -1.241554e-01 -1.614667e-01 -1.555724e-01 -1.118590e-01 -4.256574e-02  3.614970e-02  1.097938e-01  1.532000e-01  1.612439e-01  1.229504e-01  4.904072e-02
 [85] -3.726522e-02 -1.116908e-01 -1.535943e-01 -1.555642e-01 -1.110113e-01 -3.607084e-02  4.671452e-02  1.141403e-01  1.515199e-01  1.411410e-01  9.221573e-02  1.711825e-02
 [97] -6.117735e-02 -1.198699e-01 -1.431554e-01 -1.232685e-01 -6.267357e-02  1.360005e-02  8.311781e-02  1.294568e-01  1.384708e-01  1.110949e-01  4.826190e-02 -3.187023e-02
[109] -1.029242e-01 -1.465521e-01 -1.493273e-01 -1.069210e-01 -3.451630e-02  4.808568e-02  1.152376e-01  1.475487e-01  1.423903e-01  9.678471e-02  2.042843e-02 -6.301876e-02
[121] -1.307709e-01 -1.621329e-01 -1.482143e-01 -9.408793e-02 -1.091879e-02  7.770917e-02  1.466600e-01  1.752333e-01  1.613551e-01  1.014390e-01  1.233963e-02 -8.395569e-02
[133] -1.568942e-01 -1.900819e-01 -1.721025e-01 -1.060657e-01 -9.791183e-03  8.962102e-02  1.643729e-01  1.959725e-01  1.698956e-01  9.874419e-02  4.063712e-03 -9.332515e-02
[145] -1.653777e-01 -1.908999e-01 -1.714995e-01 -1.056551e-01 -9.412571e-03  9.176901e-02  1.704038e-01  2.107884e-01  1.959427e-01  1.302384e-01  2.709246e-02 -8.280759e-02
[157] -1.722022e-01 -2.242869e-01 -2.189376e-01 -1.606955e-01 -5.842590e-02  5.697796e-02  1.590890e-01  2.238129e-01  2.332621e-01  1.821653e-01  8.796006e-02 -2.804040e-02
[169] -1.370321e-01 -2.171222e-01 -2.378465e-01 -2.004218e-01 -1.160496e-01 -4.281969e-03  1.050972e-01  1.908922e-01  2.247106e-01  2.014388e-01  1.247218e-01  2.324572e-02
[181] -7.522908e-02 -1.497589e-01 -1.809624e-01 -1.666022e-01 -1.176099e-01 -4.498645e-02  3.233885e-02  9.812366e-02  1.361637e-01  1.352237e-01  1.010775e-01  4.642129e-02
[193] -1.229179e-02 -6.198903e-02 -8.762626e-02 -8.745873e-02 -7.072290e-02 -4.123783e-02 -8.680191e-03  1.983371e-02  4.176359e-02  4.857435e-02  4.229918e-02  2.785419e-02
[205]  1.123948e-02 -7.127771e-03 -2.058425e-02 -2.566657e-02 -2.470011e-02 -1.869947e-02 -1.005953e-02  4.231329e-03  2.079108e-02  3.393548e-02  3.458949e-02  2.465338e-02
[217]  8.125533e-03 -9.914837e-03 -2.958697e-02 -3.901624e-02 -4.084610e-02 -2.888188e-02 -1.052842e-02  1.739696e-02  3.451113e-02  4.782416e-02  5.209275e-02  4.578052e-02
[229]  2.652363e-02  1.504811e-04 -2.352872e-02 -4.675681e-02 -5.486831e-02 -5.110543e-02 -3.164919e-02 -2.465634e-03  3.044004e-02  5.946521e-02  7.533064e-02  6.878881e-02
[241]  3.968605e-02 -8.599631e-04 -3.705050e-02 -6.874023e-02 -7.858607e-02 -6.366839e-02 -2.886664e-02  1.470032e-02  5.256284e-02  7.871812e-02  7.941835e-02  5.261808e-02
[253]  3.232945e-03 -4.866670e-02 -8.060033e-02 -8.655462e-02 -6.345511e-02 -1.341964e-02  4.022795e-02  7.877580e-02  9.041708e-02  7.017194e-02  2.731874e-02 -2.426977e-02
[265] -6.618300e-02 -8.652564e-02 -7.566890e-02 -4.360560e-02  2.427347e-04  4.560736e-02  7.147917e-02  7.334999e-02  5.439404e-02  1.828790e-02 -2.180237e-02 -5.176644e-02
[277] -6.194357e-02 -5.263502e-02 -2.702600e-02  5.459462e-03  2.764591e-02  3.515949e-02  2.904689e-02  9.856334e-03 -1.099115e-02 -2.476568e-02 -2.473909e-02 -1.470535e-02
[289]  9.901777e-04  1.269958e-02  1.628164e-02  1.215371e-02 -7.787407e-05 -1.170293e-02 -2.252639e-02 -2.297631e-02 -1.216422e-02  7.715951e-03  2.662490e-02  3.497172e-02
[301]  2.913067e-02  1.052321e-02 -1.770285e-02 -4.316586e-02 -5.294941e-02 -4.598436e-02 -2.154287e-02  1.347715e-02  4.857204e-02  6.759757e-02  6.256019e-02  3.480956e-02
[313] -8.177469e-03 -4.727875e-02 -7.296587e-02 -7.333275e-02 -4.710260e-02 -2.676638e-03  4.868405e-02  8.367411e-02  9.452564e-02  7.463526e-02  2.867804e-02 -2.773269e-02
[325] -7.303544e-02 -9.532996e-02 -8.841880e-02 -5.778710e-02 -9.568579e-03  4.231762e-02  7.537721e-02  8.680084e-02  7.547977e-02  4.510019e-02  3.801842e-03 -3.529420e-02
[337] -6.033518e-02 -6.668869e-02 -5.458891e-02 -2.999038e-02 -2.593124e-04  2.806880e-02  4.193105e-02  4.383955e-02  3.707603e-02  2.022521e-02  6.101334e-03 -5.717493e-03
[349] -1.234244e-02 -1.620367e-02 -1.806666e-02 -1.922020e-02 -2.110791e-02 -2.127266e-02 -2.096110e-02 -1.714399e-02 -2.783072e-03  1.654030e-02  3.282535e-02  4.414188e-02
[361]  4.770084e-02  3.847246e-02  1.832072e-02 -1.056649e-02 -3.722579e-02 -5.740149e-02 -6.341912e-02 -5.426390e-02 -2.980793e-02  7.470599e-04  3.212034e-02  5.011929e-02
[373]  5.734303e-02  4.622466e-02  2.630451e-02  1.905363e-03 -2.046357e-02 -3.383679e-02 -3.753406e-02 -2.872917e-02 -1.366504e-02  1.757055e-03  1.296441e-02  1.619348e-02
[385]  1.238192e-02  5.528508e-03 -5.078213e-03 -1.051610e-02 -1.070992e-02 -3.608823e-03  4.587764e-03  1.269367e-02  1.821489e-02  1.886193e-02  9.326559e-03 -6.350481e-03
[397] -2.268550e-02 -3.562078e-02 -3.750427e-02 -2.826171e-02 -9.722588e-03  1.425940e-02  3.382628e-02  4.683378e-02  4.966529e-02  3.399604e-02  7.296378e-03 -2.218337e-02

A: Try ?which.max
> which.max( iris[,1] )
[1] 132

This will give you the index of the maximum value in a given series. You need to provide much more information, however. How is this data stored, and is it monthly data? Please refer to this in the future.


text:
Q: Connect custom cloudtrail with custom eventbus? Quick question. I was trying to create custom cloud-trail for one s3 bucket.
Create custom event bus in Eventbridge, so that I can map rules to this particular s3 events only.
Basiaclly I am trying to feed portion of my events related to particular s3 bucket to an event bus that can have seperate rules. But I think the only way is to set those rules in default eventbus? Like you cannot create a partial event bus (for particular groups of events) without a lambda in between.

A: Your S3 events are preconfigured to be delivered to the default eventbus. If you want to send them to a custom bus, you can create a rule for cross-account event delivery.
There's additional documentation at https://docs.aws.amazon.com/eventbridge/latest/userguide/eventbridge-cross-account-event-delivery.html


text:
Q: Rails field "can't be blank", even though it's not blank I'm using Rails 3 and failing to submit a form because one of the fields fails to pass validates_presence_of. My model is called dinner, and the field, which is used in conjunction with a datepicker, is called date.
views/dinners/new.html.erb:
<%= f.text_field :date,  id: "datepicker" %>

models/dinner.rb:
attr_accessible :date
validates_presence_of :date

dinners_controller.rb:
def create
  @dinner = Dinner.new params[:dinner]
  if @dinner.save
    flash[:notice] = "Dinner created successfully."
    redirect_to controller: 'dinners'
  else
    flash.now[:alert] = @dinner.errors.full_messages.join("<br>").html_safe
    render action: "new"
  end
end

Whenever I fill out all of the fields, including date, I get the error "Date can't be blank", even though it is not blank. What's going on here?

A: I've found the answer.
My date column was of type date, and before validation Rails ran .to_date on it. Unfortunately, the datepicker that I use creates dates in the American mm/dd/yy format, which Rails can't handle, so .to_date returned nil. That's why the date failed validation: because it really was nil, even though the POST request was fine.
I chose the easy solution and changed the default date of datepicker, as shown here.
Note: For my version of datepicker, I had to use format instead of dateFormat, and also had to use yyyy-mm-dd instead of yy-mm-dd because Rails String#to_date thinks that the year "13" is literally '0013' and not '2013'.


text:
Q: How to skip user creation when installing I am customising a Ubuntu Live CD.
I want to skip the user creation step during installation and instead asks for a root password. Is it possible to do so?
My workaround:

*

*create a user first,

*Then passwd root to change the UNIX password.

*Then log in to the root account and usedel user.

But I want to skip the user creation all together.

A: You can install Ubuntu as an OEM distributor, with the installer. That way it installs the OS but asks to create a user and it contunues the further setup at a client eg. But in your case this might also be handy.


text:
Q: Converting a multidimensional array of strings into a multidimensional array of numbers I am trying to convert this array of strings:
[['2014', '913', '5.78254241807211', '52.3749951170618', '2014', '1', '2024448.00', '89316.00', '29187.00', '427000.00', '60.00','0'] ['1', '222.2']]

into an array that looks the same but is made of numbers because I need to make computations with it.
I already tried .astype(np.float) but it gives me the following error:
category_array=(category).astype(np.float)
VelueError: could not convert string to float

How can I slove this?

A: You first have to convert your list of lists to a numpy array.
>>> import numpy as np
>>> list_of_lists = [['1', '1.5'], ['2', '2.5'], ['3', '3.5']]
>>> numpy_array = np.array(list_of_lists)
>>> float_array = numpy_array.astype(np.float)
>>> float_array
array([[1., 1.5], [2., 2.5], [3., 3.5]])

A: Solution with basic python list approach
>>> array_str = [['2014', '913', '5.78254241807211', '52.3749951170618', '2014', '1', '2024448.00', '89316.00', '29187.00', '427000.00', '60.00', '0'], ['1', '2']]
>>> array_n = [[float(num) for num in item] for item in array_str]
>>> array_n
[[2014.0, 913.0, 5.7825424180721097, 52.3749951170618, 2014.0, 1.0, 2024448.0, 89316.0, 29187.0, 427000.0, 60.0, 0.0], [1.0, 2.0]]
>>>

A: Have you tried the float or int method ?
    array  = ['2014','913','5.78254241807211','52.3749951170618','2014','1','2024448.00','89316.00' ,'29187.00', '427000.00' ,'60.00'],['1','2','8']]

    floatlist=[[float(str) for str in subarray] for subarray in array]

    print floatlist


text:
Q: "No Module Named" error in Jupyter A very similar problem, but different solution.
When I try to do import speech_recognition as sr in Jupyter, it returns the no moduled named... error.
But doing it in a terminal is fine. So I looked through the sys.paths of both. In Jupyter:
//anaconda/lib/python3.5/site-packages/six-1.10.0-py3.5.egg',
 '/Users/don',
 '/Users/don/Users/don/Documents/PyModules/skynet',
 '//anaconda/lib/python35.zip',
 '//anaconda/lib/python3.5',
 '//anaconda/lib/python3.5/plat-darwin',
 '//anaconda/lib/python3.5/lib-dynload',
 '/anaconda/lib/python3.5/site-packages/Sphinx-1.3.1-py3.5.egg',
 '//anaconda/lib/python3.5/site-packages',
 '//anaconda/lib/python3.5/site-packages/aeosa',
 '//anaconda/lib/python3.5/site-packages/IPython/extensions',
 '/Users/don/.ipython'

In terminal:
/Users/don/Applications/miniconda3/lib/python3.5/site-packages
/datashader-0.4.0-py3.5.egg
/Users/don
/Users/don/Users/don/Documents/PyModules/skynet
/Users/don/Applications/miniconda3/lib/python35.zip
/Users/don/Applications/miniconda3/lib/python3.5
/Users/don/Applications/miniconda3/lib/python3.5/plat-darwin
/Users/don/Applications/miniconda3/lib/python3.5/lib-dynload
/Users/don/Applications/miniconda3/lib/python3.5/site-packages
/Users/don/Applications/miniconda3/lib/python3.5/site-packages/setuptools-23.0.0-py3.5.egg

If I run this first in Jupyter, then the module speech_recognition imports fine:
sys.path.append('/Users/don/Applications/miniconda3/lib/python3.5/site-packages')
I'd just like to know what's going on? I've found a solution of sorts, but I'd like a more elegant one, so I don't have to do sys.path.append every time. This is particularly endemic to a bunch of modules I've installed lately using pip install <module>.

A: This fixed it, but I don't know how or why. I just did $ pip3 install jupyter, and everything magically imported correctly after that. Nevertheless, if someone could give me a clue about what got fixed (because I don't even know what went wrong), that would be great.


text:
Q: Is the Linux install procedure the same on a VM as it is on a physical machine? I'm a Windows user, but have been considering a switch to Linux.
My aim is to make this transition as smooth as possible, so to that end, I've been thinking of creating a Virtual Machine and run a Linux distribution on it.
Would this be the same as installing Linux on a physical machine? Would it provide the same experience?  Would I still need to install all drivers (etc.) that I would normally do, or would it somehow be different when run as a Virtual Machine?

A: [The Question used to start "Best way to start using Linux" but has since been edited out, now my answer is a little superfluous but still relevant.]
You could start by using the programs available in Linux to see if you like them, many have Windows & Mac versions too. Like LibreOffice, OpenOffice, GIMP, Firefox, Chromium, Thunderbird, Pidgin, VLC, Transmission?
If you can use those, trying out a few different live ISO's (CD/DVD/USB) for a few hours or days would be good to see if they even run on your computer, and if you like them. Many can run "persistent" on a USB to save changes too. There are lots of them available:  Debian (Stable version should be more... stable, but older), Ubuntu, Linux Mint, CrunchBang, Puppy Linux, Fedora, OpenSUSE... at least a hundred others too.
Most with multiple different desktop environments available too like XFCE, gnome shell, Cinnamon, Mate, LXDE, K, Unity...)
see http://www.distrowatch.com for good overviews & search capability. And watch some videos of them in action on youtube (there were some videos of an Australian guy who has his mom test a bunch of different OS's that are interesting & fun).
Running in a virtual machine would give the feel, but not really test the hardware compatibility. I've used iso's in VirtualBox that completely fail to boot when run "for real." Some like Linux Mint & Ubuntu will usually "just work" but sometimes they need special "boot parameters" to work too... usually have to try & see, then search for any problems that come up.
Most of the "drivers" are built into the kernel, there are some proprietary video drivers that may be (optionally) available. Ubuntu and Mint (at least) have a "Driver Manager" type program that can find some easily.

A: Virtual Machines have their own devices, i.e. They virtualize your devices to their own type. This means that you may not have to install the drivers.
Also as I know VmWare Workstation has something called Guest Additions Which is installed on the OS once it has completed installing the OS on virtual machine. This little program has the drivers needed to use the virtual devices made by VMware itself.
So the answer is NO, You dont have to install all the drivers on the virtual machine compared to physical machine, neither for virtual windows nor linux installation.

A: Microsoft's virtualization system is called Hyper-V and is included in Windows Server. There is comprehensive information for Linux under Hyper-V located at Linux and FreeBSD Virtual Machines on Hyper-V. Also, see Ubuntu 14.04 in a Generation 2 VM on Ben Armstrong's Virtualization Blog.
For a non-"Windows Server" OS a couple of your other virtualization options are Windows Virtual PC and Oracle VirtualBox.
For the most part this will be the same experience you would otherwise have, although some of the driver behavior may be a little different due to the virtualization.


text:
Q: XML & YQL (similar to SQL) - how to get a subnode's attribute? I'm trying to select a certain set of data with YQL, but I'm confused on how to get to sublevels with my YQL. For example, if I run this query:
select * from music.track.search where keyword="Asia"
I get this:
<query xmlns:yahoo="http://www.yahooapis.com/v1/base.rng" yahoo:count="22" yahoo:created="2011-07-07T16:47:41Z" yahoo:lang="en-US">
    <results>
        <Track discNumber="1" duration="0" explicit="0" flags="0"
            id="61642071" label="Mark Saliba" popularity="3" rating="-1"
            releaseYear="2008" rights="2208" title="Asia"
            trackNumber="3" url="http://new.music.yahoo.com/mark-j-saliba/tracks/asia--61642071">
            <Artist catzillaID="0" flags="2" hotzillaID="0"
                id="205843271" name="Mark J Saliba" rating="-1"
                trackCount="11"
                url="http://new.music.yahoo.com/mark-j-saliba/" website=""/>
            <Album>

and if I run this query:
select ID from music.track.search where keyword="Asia"
I get this:
<query xmlns:yahoo="http://www.yahooapis.com/v1/base.rng"
    yahoo:count="22" yahoo:created="2011-07-07T16:50:13Z" yahoo:lang="en-US">
    <results>
        <Track id="61642071"/>...

But what I want to do is just get the artist IDs, not the track IDs (specifically, just the first result would be fine). What is the YQL statement for that?

A: For all artist ids:
select Artist.id from music.track.search where keyword="Asia"

For just the first artist id:
select Artist.id from music.track.search where keyword="Asia" limit 1


text:
Q: Mule - Parse CSV to ArrayList of hash maps based on CSV header values I have a simple csv
TYPE,DATE,NAME
 SERIAL,20170808,TR
NUEROUS,20160608,WB
This is my flow for converting csv to arraylist of hashmaps(currently using indexes)
<set-property propertyName="Content-Type" value="text/csv"
mimeType="application/csv" doc:name="Property"/>

  <dw:transform-message doc:name="Transform Message">
    <dw:input-payload doc:sample="sample_data/string.dwl" mimeType="application/csv"/>

      <dw:set-payload><![CDATA[%dw 1.0
%output application/java
---
payload map ((payload , indexOfPayload) -> {
operationType:payload[0],
issueDate:payload[1],
issueNumber:payload[2]
})]]></dw:set-payload>
         </dw:transform-message>

Thing is that currently i am using indexes, but what when header csv indexes will be changed? so i need to do the parsing based on csv header names. e.g
operationType: payload.TYPE

How to do that?

A: You can achieve this by using header column name as the key for getting value.
<dw:transform-message doc:name="Transform Message">
            <dw:input-payload mimeType="application/csv"/>
            <dw:set-payload><![CDATA[%dw 1.0
%output application/java
---
payload map ((payload , indexOfPayload) -> {
operationType:payload.TYPE,
issueDate:payload.DATE,
issueNumber:payload.NAME
})]]></dw:set-payload>
        </dw:transform-message>

As per Mule documentation

When header=true you can then access the fields within the input anywhere by name. Ex: payload.userName.
When header=false you must access the fields by index, referencing first the entry and then the field, Ex: payload[107][2]

Hope this helps.


text:
Q: Binding CheckBox.Visibility and CheckBox.IsChecked I'm developing a Windows Phone 8 application with a listbox with this datatemplate:
<phone:PhoneApplicationPage.Resources>
    <DataTemplate x:Key="LocalizationItemTemplate">
        <Border BorderBrush="Black" BorderThickness="2" CornerRadius="8" Background="#FF003847" Height="80">
            <StackPanel x:Name="contentGrid" Margin="4" Orientation="Horizontal">
                <CheckBox x:Name="selectedCheck" Visibility="{Binding CheckBoxVisibility}" IsChecked="{Binding IsChecked}"
                        HorizontalAlignment="Left" Margin="10,0,0,0" VerticalAlignment="Center" IsEnabled="False"/>
                <TextBlock x:Name="locationName" TextWrapping="Wrap" Text="{Binding Content}" VerticalAlignment="Center" FontSize="24" HorizontalAlignment="Left" Margin="10,0,0,0"/>
            </StackPanel>
        </Border>
    </DataTemplate>
</phone:PhoneApplicationPage.Resources>

I'm using an ObservableCollection<LocationToShow> as ItemsSource:
public class LocationToShow : ARItem
{
    public double Distance { get; set; }

    public string FormatedDistance
    {
        get
        {
            if (Distance == double.NaN)
                return string.Empty;
            else
                return string.Format("{0} metros", Distance.ToString("N0"));
        }
    }

    public Visibility CheckBoxVisibility { get; set; }

    public bool IsChecked { get; set; }
}

But, when I change CheckBoxVisibility or IsChecked I don't see the checkbox appears or checked it.
How can I fix this problem?

A: LocationToShow or ARItem class need to implement INotifyPropertyChanged interface and each time view model property changes value you need to raise PropertyChanged event:
public event PropertyChangedEventHandler PropertyChanged;

private void NotifyPropertyChanged(String propertyName)
{
    var handler = PropertyChanged;
    if (handler != null)
        handler(this, new PropertyChangedEventArgs(propertyName));
}

private bool _isChecked;

public bool IsChecked
{
    get { return _isChecked; }
    set
    {
        if (_isChecked != value)
        {
            _isChecked = value;
            NotifyPropertyChanged("IsChecked");
        }
    }
}

A: Implement INotifyPropertyChanged on your class LocationToShow to notify UI to update on any property change.
Refer to this - How to Implement INotifyPropertyChanged notification.
public class LocationToShow : ARItem, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    // Create the OnPropertyChanged method to raise the event
    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
           handler(this, new PropertyChangedEventArgs(name));
        }
     }

     private bool isChecked;
     public bool IsChecked
     {
         get { return isChecked; }
         set
         {
            if (isChecked != value)
            {
               isChecked = value;
               OnPropertyChanged("IsChecked");
            }
         }
     }
}

Change all other properties to follow the same pattern in case you want UI to refresh on any property change in your class.


text:
Q: responsive full screen iframe undistinguishable I am using an iFrame inside a page and trying to make user feel that the iframe is the main original page.
There are bunch of questions abt it here but they are not working as I expected.
I have already checked and follwed all the relative topics about full screen responsice iframe. but for no reason I can figure, It is not working.
I have used this method for example
How to make an iframe responsive full height and full width

body {
  margin: 0;
}
iframe {
  height:calc(100vh - 4px);
  width:calc(100vw - 4px);
  box-sizing: border-box;
}
<iframe src="https://www.youtube.com/embed/7ipiybRLqZc" frameborder="0" allowfullscreen></iframe>

but still when I switch to smart phone view, the webpage is not being shown as mobile version and it is not responsive.
This is the page with an Iframe in it:
https://alumsharif.org/testProfile.php
and the iFrame source it self is this page:
https://alumsharif.org/people/alireza.ghaderi
as you can see the original page works as expected and mobile version works. but when I ue the first URL, mobile version is bot being activated on mobile view.
What step am I missing?


text:
Q: How can i dynamically call my css file on index.html - angular2 My requirement is i need to call a css url from a variable. Actually i dont want to hard code it. As per the logged in user , the name of the css will be downloaded in local storage and from there i want to load it on index.html, how can i make this possible ?
My index.html
<!doctype html>

  <meta charset="utf-8">
  <title>Wbuilder</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <link rel="stylesheet" href="./assets/files/css/style.css">
  // instead of this i need to call this from a variable

  <app-root>Loading...</app-root>

A: Why not create an Angular component that dynamically generates an in-line


text:
Q: Limitations on C++ chrono library? I have extracted the following simple code from a bigger project. I am trying to simulate futures dates, day by day, by extracting day,month,year.
I am using the std::chrono library. After a certain amount of days (approximately 8835 days on my computer), the date goes wrong.
I have tried to :

*

*Playing with g++ optimization flag

*Launch with valgrind

*Looking for chrono documentation about limits

Can you reproduce this behaviour?
// COMPILE OK && RUN KO (wandbox)
// g++ prog.cc -O2 -march=native -std=c++11

// COMPILE OK && RUN OK (wandbox)
// clang++ prog.cc -Wall -Wextra -std=c++11

#include <iostream>
#include <chrono>

using namespace std;

int main(int ac, char* av[])
{
  (void) ac; (void) av;
  auto faketime = chrono::system_clock::now();

  for( int i=0; i<100000; ++i) {
    // doDaily();
    faketime += chrono::hours(24);
    time_t ftime = chrono::system_clock::to_time_t(faketime);
    if( i% 1000 == 0)
         cout << "faketime (" << ftime << ") is : " << ctime(&ftime) << endl;
  }
  auto currtime = chrono::system_clock::now();
  time_t cutime = chrono::system_clock::to_time_t(currtime);
  cout << "currtime is : " << ctime(&cutime);
  return 0;
}

RESULT (The third line goes wrong) :
[...]
faketime (9105738161) is : Tue Jul 20 20:42:41 2258
faketime (9192138161) is : Mon Apr 15 20:42:41 2261
faketime (-9168205912) is : Wed Jun 21 21:27:07 1679
faketime (-9081805912) is : Tue Mar 17 21:27:07 1682
faketime (-8995405912) is : Mon Dec 11 21:27:07 1684
currtime is : Thu May  7 12:48:56 2020

EDITED :

*

*Added where exactly it goes wrong.

*I have tested this code on https://wandbox.org/ : I can reproduce the problem with gcc 11, but it works ok with clang++

*It looks like there exists a limitation but only compiling with g++.

A: You are experiencing an overflow in system_clock::time_point.
The precision of system_clock::time_point varies with platform:

*

*gcc:  nanoseconds

*Windows:  1/10 microseconds

*clang/libc++:  microseconds

But the representation is the same on all three platforms:  signed 64 bit integral.  And this is all conforming.
64 signed bits of nanoseconds gets you a range of about +/-292 years.  For system_clock this range is centered on 1970-01-01.  So overflow in the year 2262 is normal.
If you need greater range, you can reduce your precision.  For example:
auto faketime = chrono::time_point_cast<chrono::microseconds>(chrono::system_clock::now());

One can programmatically inspect the limits of a time_point with the time_point static member functions min() and max().
Update
The range on microseconds is about +/-292 thousand years.  I'm unsure what the range on ctime is, but I would be surprised if it could format dates that far in the past/future.


text:
Q: Getting All Items Earlier Than Now From DB I have a table which stores tasks to be performed in the future by an MVC system. This is going to be done by a page which will be called periodically to find all tasks that need to be done.
The future tasks are going to be stored with a datetime in them which is the time they should be completed. They will also contain other information which i will use to process the task accordingly. Once a task has been pulled from the DB i will remove it from the db so it cannot be called again.
I am trying to query the db to get all the tasks that have a "dueDateTime" that is before now. and store them in a object list. Something like this:
tasksList = db.ScheduledTasks.Where(s => s.date.CompareTo(System.DateTime.UtcNow));

This does not work and is more psudo code than anything, but i cant seem to find any resouces online to help me with this. Could someone help please.
Thanks in advance.

A:  db.ScheduledTasks.Where(s => s.date < System.DateTime.UtcNow);

If you compare with UTC time, the time should be parsed to UTC before saved to db.
Lambda expression do not support compare method.

A: Have you tried s.date < DateTime.Now?  Note there's a caveat with Daylight savings.
Also check out this SO link.


text:
Q: Convergence of maximum of sequences of random variables Let $X_1^n,\ldots,X_k^n$ be sequences of random variables, where $k$ is fixed. The sequences are not independent. I'd like to prove the following statement:

Assume that $X_1^n \to x_1, \ldots, X_k^n \to x_n$ in probability, where $x_1,\ldots,x_n$ are constants. Then:
  $$
\max_{i \in \{1,\ldots,k\}} X_i^n \to \max_{i \in \{1,\ldots,k\}} x_i
$$
  in probability.

Notice that this setting is different than the usual one, where the maximum is usually taken over $n$.
I'm not entirely sure if this can be seen as a direct application of the continuous mapping theorem, especially if the sequences live in other spaces than $\mathbb{R}$ (for instance on $\mathbb{N}$).
Any insight is very much appreciated!

A: It is indeed just the ($k$-dimensional) continuous mapping theorem, since $F(x_1, \dots, x_k) := \max(x_1, \dots, x_k)$ is a continuous function from $\mathbb{R}^k$ to $\mathbb{R}$ (easy exercise).  You have a sequence of $\mathbb{R}^k$-valued random vectors $\mathbf{X}^n := (X_1^n, \dots, X_k^n)$ converging in probability to a constant vector $\mathbf{x} = (x_1, \dots, x_k)$, and you are claiming that $F(\mathbf{X}^n) \to F(\mathbf{x})$ in probability.  That is exactly the continuous mapping theorem.
It makes no difference if your random variables only take values in a subset of $\mathbb{R}$, such as $\mathbb{N}$ or $\mathbb{Z}$ or what have you.  You can still view them as real-valued random variables.
(Of course, if your random variables take values in some space completely different from $\mathbb{R}$, then you need to know quite a bit about the order and topological structure of that space to even make sense of the statement.)

A: It is easy to verify that $|max \{a_1,a_2,...,a_k) - max \{b_1,b_2,...,b_k)|>\epsilon$ implies $|a_i-b_i| >\epsilon$ for some $i$. [Use proof by contradiction]. Hence  the result follows immediately from definition of convergence in probability.


text:
Q: Free $R-module$ over an integral domain R that is not a field has finite length iff it is $0-module$ Free $R-module$ over an integral domain R that is not a field has finite length iff it is $0-module$
I try to begin with the most navie case:If $F$ is free $R-module$ on singleton,that is,$R$,I attempt to prove if submodule $M$ is simple,then it must be trivial.But I can't see how to do it..Any hint will be helpful , thanks.


text:
Q: Fixing nginx 1.4.6 dependency on old openssl version (libssl0.9.8)? I'm trying to enable TLSv1.1 & TLSv1.2 on my Ubuntu 12.04 EC2 instance w/ nginx 1.4.6, but this version of nginx is dependent upon libssl0.9.8, even though the newest version of OpenSSL is installed (1.0.1).
How can I resolve this so I can enable TLSv1.1 & TLSv1.2?


text:
Q: Ember.js ember-data and cross-domain ajax requests folks! Any examples of using ember-data to store data getted from remote server with cross-domain ajax request? Now I have this, but...
TravelClient.Tour = Ember.Object.extend({
});

TravelClient.Tour.reopenClass({
  allTours: [],
  find: function(){
    $.ajax({
      url: 'http://someIP:somePORT/tours.json',
      dataType: 'jsonp',
      context: this,
      success: function(data){
        data.forEach(function(tour){
          this.allTours.addObject(TravelClient.Tour.create(tour))
        }, this)
      }
    })
    return this.allTours;
  }
});

UPDATE:
Now i'm doing it in this way:
TravelClient.Tour.reopenClass({
  allTours: [],
  find: function(){
    $.ajax({
      url: 'http://someIP:somePORT/tours.json',
      dataType: 'jsonp',
      context: this,
      success: function(response){
        response.data.forEach(function(tour){
          this.allTours.addObject(TravelClient.Tour.create(tour))
        }, this)
      }
    })
    return this.allTours;
  }
});

But get this error:
Uncaught TypeError: Cannot call method 'forEach' of undefined

SNAPSHOT:
with this:
$.ajax({
  dataType: 'jsonp',
  url:"http://192.168.1.39:3000/tours.json",
  success:function(response){
    return response.data;
  }
});

I get this:
Object
abort: function (e){var t=e||S;return r&&r.abort(t),N(0,t),this}
always: function (){return i.done(arguments).fail(arguments),this}
complete: function (){if(a){var t=a.length;(function r(t){y.each(t,function(t,n){var i=y.type(n);i==="function"?(!e.unique||!c.has(n))&&a.push(n):n&&n.length&&i!=="string"&&r(n)})})(arguments),i?o=a.length:n&&(s=t,l(n))}return this}
done: function (){if(a){var t=a.length;(function r(t){y.each(t,function(t,n){var i=y.type(n);i==="function"?(!e.unique||!c.has(n))&&a.push(n):n&&n.length&&i!=="string"&&r(n)})})(arguments),i?o=a.length:n&&(s=t,l(n))}return this}
error: function (){if(a){var t=a.length;(function r(t){y.each(t,function(t,n){var i=y.type(n);i==="function"?(!e.unique||!c.has(n))&&a.push(n):n&&n.length&&i!=="string"&&r(n)})})(arguments),i?o=a.length:n&&(s=t,l(n))}return this}
fail: function (){if(a){var t=a.length;(function r(t){y.each(t,function(t,n){var i=y.type(n);i==="function"?(!e.unique||!c.has(n))&&a.push(n):n&&n.length&&i!=="string"&&r(n)})})(arguments),i?o=a.length:n&&(s=t,l(n))}return this}
getAllResponseHeaders: function (){return E===2?s:null}
getResponseHeader: function (e){var t;if(E===2){if(!o){o={};while(t=wn.exec(s))o[t[1].toLowerCase()]=t[2]}t=o[e.toLowerCase()]}return t==null?null:t}
overrideMimeType: function (e){return E||(c.mimeType=e),this}
pipe: function (){var e=arguments;return y.Deferred(function(n){y.each(t,function(t,s){var o=s[0],u=y.isFunction(e[t])&&e[t];i[s[1]](function(){var e=u&&u.apply(this,arguments);e&&y.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[o+"With"](this===r?n.promise():this,u?[e]:arguments)})}),e=null}).promise()}
progress: function (){if(a){var t=a.length;(function r(t){y.each(t,function(t,n){var i=y.type(n);i==="function"?(!e.unique||!c.has(n))&&a.push(n):n&&n.length&&i!=="string"&&r(n)})})(arguments),i?o=a.length:n&&(s=t,l(n))}return this}
promise: function (e){return e!=null?y.extend(e,r):r}
readyState: 4
setRequestHeader: function (e,t){var n=e.toLowerCase();return E||(e=b[n]=b[n]||e,g[e]=t),this}
state: function (){return n}
status: 200
statusCode: function (e){var t;if(e)if(E<2)for(t in e)m[t]=[m[t],e[t]];else x.always(e[x.status]);return this}
statusText: "success"
success: function (){if(a){var t=a.length;(function r(t){y.each(t,function(t,n){var i=y.type(n);i==="function"?(!e.unique||!c.has(n))&&a.push(n):n&&n.length&&i!=="string"&&r(n)})})(arguments),i?o=a.length:n&&(s=t,l(n))}return this}
then: function (){var e=arguments;return y.Deferred(function(n){y.each(t,function(t,s){var o=s[0],u=y.isFunction(e[t])&&e[t];i[s[1]](function(){var e=u&&u.apply(this,arguments);e&&y.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[o+"With"](this===r?n.promise():this,u?[e]:arguments)})}),e=null}).promise()}
__proto__: Object

A: This is more a about how the server should return data to the client than about ember-data, what you need to do is, wrap the response to the ajax call in a callback whose value is sent as a parameter to the server. Once you do that, it's business as usual for ember-data i.e quite transparent to it
Here's an example using ruby on rails
On the client side
$.ajax({
    dataType: 'jsonp',
    success: function(response) {
       // loop through your objects
       response.accounts.forEach(function(account){
          console.info(account.id)
       })
    }
});

On the server side you should do something similar to
params[:callback] + '("' + response + '");';

Yielding for example a response similar to:
callbackValue00923411(
    {
        "accounts":
        [
            {
                "id": 123,
                "name": "Personal",
            },
            {
                "id": 234,
                "name": "Corporate",
            }
        ]
    }
);

Then in your success function you access the list of accounts, as I stated above, this way
success: function(response) {
   // loop through your objects
   response.accounts.forEach(function(account){
      console.info(account.id)
   })
}

Here's an example on how to use/handle jsonp ajax request
If you have access to the server, you may consider configuring it to use CORS instead and avoid using jsonp


text:
Q: Oracle 11g Enterprise downgrade to Standard One I'm checking possibilty of downgrade Oracle 11g from Enterpise Edition to Standard One edition. I've cross-checked edition comparison with
select name from dba_feature_usage_statistics where currently_used='TRUE'

Query result from dba_feature_usage_statistics:
Job Scheduler
Oracle Java Virtual Machine (user)
Oracle Java Virtual Machine (system)
Automatic Memory Tuning
Oracle Utility Metadata API
Segment Advisor
Automatic SQL Tuning Advisor
Object
Materialized Views (User)
Audit Options
Automatic Maintenance - Optimizer Statistics Gathering
Automatic Maintenance - Space Advisor
Automatic Maintenance - SQL Tuning Advisor
Automatic Segment Space Management (system)
Automatic Segment Space Management (user)
Automatic Undo Management
Client Identifier
Character Set
Locally Managed Tablespaces (system)
Locally Managed Tablespaces (user)
Parallel SQL Query Execution
Partitioning (system)
Recovery Area
Recovery Manager (RMAN)
RMAN - Disk Backup
Backup BASIC Compression
Logfile Multiplexing
Server Parameter File
Shared Server
Streams (user)
LOB
SecureFiles (system)

I think Parallel SQL Query Execution and Partitioning (system) are only in Enterprise Edition, but I'm not sure about rest, especially:
Automatic Memory Tuning
Segment Advisor
Automatic SQL Tuning Advisor
Automatic Maintenance - SQL Tuning Advisor
Recovery Area

Do you guys know which edition of Oracle is needed to use these features?

A: Ultimate source for such answers is Oracle Database Licensing Information.
Sadly to downgrade from Enterprise to Standard Edition you have to export all the data install Oracle Standard Edition and import data (Doc ID 139642.1).
From your list "Automatic SQL Tuning Advisor" is Enterprise Edition only feature. As a rule of thumb - features which needs AWR are Enterprise Edition only plus you need to buy Oracle Diagnostics Pack.


text:
Q: Why Windows Live Messenger on Win 7 doesn't pop up the window with the new message, but "let me choose"? On Windows 7, when clicking on the small icon on the task bar, it is nice to pop up a few small windows and let me choose which one to use.
But, with Windows Live Messenger, when I have several chat windows open, and a friend send me a new message, so I click on the small icon, and it shows which one has the new message with an orange background, and still "let me choose" which window to open up.
In this situation, I think it is one that it can directly pop up the one with the new message, instead of letting the user scan which one has the new message, move the mouse to pinpoint that one, and click on it.
Or is there a way around it?

A: You can try the following to make Live Messenger work like in XP or Vista for Win 7;
1-Open C:\Program Files\Windows Live\Messenger
2-Right Click "msnmsgr.exe"
3-Properties > Select Compatibility Mode
4-Activate compatibility box to select an OS
5-Select Windows Vista or Windows XP SP3

A: It's not a Windows Messenger feature you're really talking about here. You'll find the same behaviour in Windows 7 for all applications that are highlighted on the task bar.
I don't think you're asking something that's possible, because I think the behaviour is by design.

A: Windows 7 stopped letting MSN work the way it wanted and made it work the same as every other application - which was a mistake IMHO.
I prefer MSN to hide itself away in the notification area and pop up message notifications. Conversations should appear in the task bar.
I can't think why they did this, but... there's no way to put it back the way it should be that I can find. What I'd suggest is to move to an alternative, like Pidgin, Digsby, Miranda or Trillian, or try a new messaging client like Skype or Google Talk.


text:
Q: error in dataSearch using berkley DB I've created a database using Berkley DB that stores N records where a record is a key/value pair. I originally populated it with only 20 records. With 20 records I managed to do a Key Search, and a Data Search (where I search through the database record by record for a data value that matches the string data inputted by the user).
public String dataSearch (String dataInput) {
    String foundKey = null;
    String foundData = null;
    Cursor cursor = null;
    try {
        cursor = myDb.openCursor(null, null);
        DatabaseEntry theKey = new DatabaseEntry();
        DatabaseEntry theData = new DatabaseEntry();
        while (cursor.getNext(theKey, theData, LockMode.DEFAULT) == OperationStatus.SUCCESS) {
            foundKey = new String(theKey.getData(), "UTF-8");
            foundData = new String(theData.getData(), "UTF-8");
                // this is to see each key - data - inputdata as I was having an issue
            System.out.println("KEY: " + foundKey +
                    "\nDATA: " + foundData +
                    "\nINPUT_DATA: " + dataInput + "\n\n");

            if (foundData.equals(dataInput)) {
                System.out.println("-----------------------------------\n\n");
                System.out.println("Found record: " + foundKey +
                            "\nwith data: " + foundData);
                System.out.println("\n\n-----------------------------------");
            }
        }

 /* I then close the cursor and catch exceptions and such */

this works fine when I have less than (or equal to) 20 records... but when I use a bigger number I seem to have some funny behaviour. I set the number of records to 1000... the last key/data values to be inserted into the database are:
KEY: zghxnbujnsztazmnrmrlhjsjfeexohxqotjafliiktlptsquncuejcrebaohblfsqazznheurdqbqbxjmyqr

DATA: jzpqaymwwnoqzvxykowdhxvfbuhrsfojivugrmvmybbvurxmdvmrclalzfscmeknyzkqmrcflzdooyupwznvxikermrbicapynwspbbritjyeltywmmslpeuzsmh

I had it print out the last values to be inserted into the database then did a key search on the above key to ensure that the data above was infact the data associated with that key in the database. However, when I do a data search on the data listed above I get no found matching record (whereas the same process found a record when there was 20 records). I looked into it a bit more and got each my data search to print each key/data pair that it returned and found the following result:
KEY: zghxnbujnsztazmnrmrlhjsjfeexohxqotjafliiktlptsquncuejcrebaohblfsqazznheurdqbqbxjmyqrpzlyvnmdlvgyvzhbceeftcqssbeckxkuepxyphsgdzd
DATA: jzpqaymwwnoqzvxykowdhxvfbuhrsfojivugrmvmybbvurxmdvmrclalzfscmeknyzkqmrcflzdooyupwznvxikermrbicapynwspbbritjyeltywmmslpeuzsmhozy
INPUT DATA: jzpqaymwwnoqzvxykowdhxvfbuhrsfojivugrmvmybbvurxmdvmrclalzfscmeknyzkqmrcflzdooyupwznvxikermrbicapynwspbbritjyeltywmmslpeuzsmh

as you can see it seems to have randomly appended some extra bytes to the data value. however if I do a key search these extra bytes don't show up. So I think the problem is in the dataSearch function. The same results occur if I use b+tree or hash.
Any Ideas?
Thanks

A: After a long time looking at this I realized my error was that I was not reinitializing the theKey & theData variables.
the fix is in the while loop
       while (cursor.getNext(theKey, theData, LockMode.DEFAULT) == OperationStatus.SUCCESS) {
            foundKey = new String(theKey.getData(), "UTF-8");
            foundData = new String(theData.getData(), "UTF-8");
                // this is to see each key - data - inputdata as I was having an issue
            System.out.println("KEY: " + foundKey +
                    "\nDATA: " + foundData +
                    "\nINPUT_DATA: " + dataInput + "\n\n");

            if (foundData.equals(dataInput)) {
                System.out.println("-----------------------------------\n\n");
                System.out.println("Found record: " + foundKey +
                            "\nwith data: " + foundData);
                System.out.println("\n\n-----------------------------------");
            }
            // THIS IS THE FIX
            theKey = new DatabaseEntry();
            theData = new DatabaseEntry();
            // ----------------------------

        }


text:
Q: Проблемы с версткой Проблемы с версткой, при определенных условиях верстка ломается и вот как это выглядит:

Вот html разметка:

»

1 Приб.

in 0:08:52 ч.

А вот как должно быть правильно:

Как исправить ошибку? Как исправить верстку? Что для этого нужно? Какой CSS нужно использовать, что бы добиться такого результата как на второй картинке?

A: Засуньте все эти кружочки в один отдельный блок, задайте ему ширину и примените стиль:
margin: 0 auto;

Для блоков можете применить
float: left/right;

Ну и
min-width


text:
Q: Convolution/FFT algorithm for a machine with slow memory and no cache? I'm trying to write a convolution function for a GPU using OpenCL.
Benchmarking shows that the GPU's data load instructions are very expensive and the run time scales linearly with the total number of LD instructions, indicating the GPU as little or no cache.
This causes convolutions with small- and medium-sized kernels (~48) very inefficient (~1% of the peak GFLOPS).
Is there a particular convolution algorithm, or a FFT algorithm that maximizes data reuse in registers (up to 64 float4 registers are available) and optimized for memory access?
Update: Floating point is preferred.


text:
Q: c# how long does it take to start a task Just wondering how long does the task creation take:
Task<int> tsk = Task<int>.Factory.StartNew(() => ReadOscilloscopeData(2, val.ADC_PSC, val.ADC_ARR, val.ADCSAMPLES, val.ADCFRAMES, val.NCHANNELS, 1000, out outdata));

A: Why not use stopwatch to see?
var stopWatch = new Stopwatch();
stopwatch.Start();
Task<int> tsk = Task<int>.Factory.StartNew(() => ReadOscilloscopeData(2, val.ADC_PSC, val.ADC_ARR, val.ADCSAMPLES, val.ADCFRAMES, val.NCHANNELS, 1000, out outdata));
stopwatch.Stop();
Console.WriteLine(stopwatch.Elapsed);

A: Actually, it depends on a number of conditions.
E.g., if thread pool is depleted, it will wait 0.5-1 seconds for any of existing threads to yield and if none of them is released by this time, it will create an extra thread to run your task.
You can find a pretty exhaustive investigation into the subject here.


text:
Q: $\operatorname{Ann}(G)=$?, where $G$ is a module over $\mathbb{Z}$. As every Abelian Group $G$ is a $\mathbb{Z}$-module. It is easy to see that if $|G|=n$, then $n\mathbb{Z} \subset \operatorname{Ann}(G)$.
Can we tell that for every group $G$, $n\mathbb{Z}=\operatorname{Ann}(G)$?
If $G=\mathbb{Z}_n$ then it is true. Is this true in general?

A: You have ${\rm Ann}(G)=e\mathbb{Z}$ where $e$ is the exponent of $G$, i.e. the lcm of the orders of the elements of $G$.
For instance
$${\rm Ann}((\mathbb{Z}/2\mathbb{Z})^r)=2\mathbb{Z}
$$
whatever $r$.


text:
Q: Angular multi-select and jQuery plugin I would like to use Angular to make a multi-select with this dropdown:
http://tympanus.net/Development/ResponsiveMultiLevelMenu/index5.html

The structure works with jQuery but when I want to add AngularJS I have problems. There is just the first level which works. Maybe It's a scope problem but I don't master it very well.
Here is a demo which works with jQuery (expand the view window to be well displayed)
http://jsfiddle.net/x6h54vey/

Here is my directive:
app.directive('selectFilter', function(){
    return{
        restrict: 'E',
        templateUrl: "select-filter.html",
        controller: function(){
            this.filters = filters_tab;
        },
        controllerAs: "selectFilter",
        link: function(scope, elem, attrs) {
        // CALL PLUGIN DLMENU
        $(elem).dlmenu({
            animationClasses : { classin : 'dl-animate-in-4', classout : 'dl-animate-out-4' }
        });
        }

    };
});

My directive template:
<button class="dl-trigger">Filter</button>

And my demo. There is just the first level which works:
http://plnkr.co/edit/NCLnd3DB8X7LA80J6hJE

In addition, don't hesitate if you have advices to optimize it.
Thank You !


text:
Q: Compile app in Sunmi v2 with Android Studio I have an application that is developed for SUNMI v1, but the client has changed to v2. They gave me a device to do the respective tests, but Android Studio does not recognize it. ADB devices recognize it as unauthorized, but for the SUNMI v1 if it recognizes it, I kill and start the ADB server, but it still doesn't recognize the SUNMI v2.
What can I do in this case?


text:
Q: issue on reading from textfile? I have a function which checks for username and password. I have two text files, one for a single line username and the other for a single line password. I then read this data from txtfile and store them as 2 strings. Then I compare these with the username and password input by the user using the function which returns 1 for success. But my code gives the wrong output.
int compare(char C[], char E[])
{
    ifstream fil1;
    ifstream fil2;
    fil1.open("user.txt", ios::in);
    fil2.open("pass.txt", ios::in);
    char ch1, ch2;
    char B[50], F[50];
    int i1 = 0, i2 = 0;

    while (!fil1.eof())
    {
        fil1.get(ch1);
        F[i1] = ch1;
        i1++;
    }
    F[i1] = '\0';
    fil1.close();

    while (!fil2.eof())
    {
        fil2.get(ch2);
        B[i2] = ch2;
        i2++;
    }
    B[i2] = '\0';
    fil2.close();

    int flag;
    int X = strlen(E);
    int Y = strlen(B);
    if (X == Y)
    {
        if ((strcmp(C, F) == 0) && (strcmp(E, B) == 0))
            flag = 1;
        else
            flag = 0;
    }
    else
        flag = 0;
    return flag;
}

It gives the wrong output even when username and password are right. Where is the error??

A: In simple words, eof() returns true only when we try to read past the end of file (more than size of file).
So you should change the code as follows:
while(true)
{
  fil1.get(ch1);
  if(fil1.eof())
    break;
  F[i1]=ch1;
  i1++;
}

A: Consider you have "user.txt" with "user" text inside. You will have F = "userr" with double last symbol 'r' because fil.eof() returns true only when an attempt to read past the end of file was made. Correct loop is:
while(fil1.get(ch1)) {
  F[i1] = ch1;
  i1++;
}

Same for second loop.

A: If you use std::string, this:
 while (!fil1.eof())
 {
     fil1.get(ch1);
     F[i1] = ch1;
     i1++;
 }

Is turned into:
std::string F;
file1 >> F;

So replacing your program with the relevant code will result into:
#include <fstream>
#include <string>

bool compare(std::string C, std::string E)
{
    std::ifstream file1("user.txt");
    std::ifstream fil2("pass.txt");

    std::string B, F;

    file1 >> F;
    file2 >> B;

    int size1 = F.size(), size2 = B.size();
    bool flag = (C == F) &&  (E == B);

    return flag;
}

You also seem to be using int instead of bool. I don't know if this is because of the compiler you are using, but you should seriously think about upgrading if so.


text:
Q: Comcast Business Class router setup I do know a little about networking but im having some trouble trying to figure out in my head how to make this work before comcast comes to do the install on thursday.
Right now we have AT&T DSL with one dynamic IP so im using dyndns to run a webpage, a sharepoint site, a helpdesk site, and email all using port forwarding thru a Linksys gigabit wireless router. We have a small domain with about 10 workstations also. We will be getting comcast business class and 5 static IP's
My problem is trying to figure out how to get the computers that will be using the public IP's to be able to talk to our DC which will be behind the linksys router. From what i have been reading i know i could just allow one public IP to pass thru the comcast router to my linksys router and life would go on as normal just as it is now. However, once i take our web server, which needs to talk to the DC because we have some apps that require AD usernames/passwords, and move it out from behind the linksys router to give it one of the public IP's i dont think it will be able to get thru the router to talk to the DC. The DC is also running our DHCP server.
To make this work, would i need to just scrap the idea of using our linksys router and just use the comcast router/gateway? If i did that can i just have the DC give out IP's in our private 192.168.5.* scope, and give out the IP's in the public space as well? does it work like that?
Right now the linksys router only allows me to forward port 80 or 443 to one IP, im assuming the comcast router will allow me to forward 80 thru to whichever public IP its intended to go to?
Sorry if im making this more confusing then it needs to be but i cant figure it out in my head!

A: The "least impactful" approach is to probably go with a NAT router which can service multiple public/WAN IPs - whether that is through the Comcast equipment (if it has the functionality you need) or through a replacement of the Linksys. That will allow you to specify per IP-to-port mappings for each Internet/WAN IP simultaneously, so your current internal IP plan can stay the same.

A: TommyB, I was close to your exact position with Comcast. I do IT for a living, was using Comcast home service, running a Windows server, including Exchange for e-mail. My port 25 kept getting blocked, so I moved to business class. I also use Dynamic DNS, and have a SonicWALL firewall in the middle.
When they put in my business-class modem/router with its small switch, it became clear very early on that the new modem would not work because it did not handle bridging so it kept giving a 192.168.x.x IP address to the WAN interface of my SonicWALL which was being reported to my dynamic DNS provider, so I had three choices:

*

*Pay through the nose for a static IP (then it can be put into bridged mode)

*Dump the SonicWALL (in your case the Linksys) and use their modem as a firewall, which was not appealing since it is very limited

*Or simply trade the business-class modem for a home version, which can be bridged, but make sure they kept my IP in the business-class range.

I also had to use their smarthost with my username and password for relaying e-mail.
I chose the last, and have been working that way for over a year, but since you already made the commitment to the statics, ask them about putting it into bridged mode. You will probably need to upgrade your Linksys to a more functional firewall.
In the alternative, if you are OK with the Comcast modem/router as a firewall, it also does 1-to-1 NAT (as well as port forwarding), allowing you to use multiple external IP's and map them to internal servers.

A: Sounds like the best way would be to put your Comcast modem/router into bridge mode, then get a business class router/firewall (I like Sonicwall) and configure the WAN interface with your static IP addresses.  In the firewall and NAT rules on the Sonicwall, setup the ports (Sonicwalls actually have a handy wizard for this):

*

*8.2.3.4 port 80/443 goes to web server 1 (192.168.1.10)

*8.2.3.5 port 80/443 goes to web server 2 (192.168.1.11)

*8.2.3.6 port 25 goes to email server (192.168.1.12)

*etc.

This will allow you to essentially keep everything behind the firewall the same (no changes to DHCP or configuring servers' NICs with wan IPs).
Some other points:

*

*Keep everything behind the firewall if possible.  It doesn't sound like you need to move your web server in front of the firewall, so don't.  Moving it in front of your firewall will make the web server that much easier to hack and will significantly complicate the AD communication back to your DC.  We could get into a big discussion on DMZs and AD communication and what's possible and not possible, but for your situation, it sounds like it would be logical to just keep everything as-is and do the port forwarding as described above.

*I never rely on the ISP's equipment to do anything other than provide an interface to their connection (i.e. just be a modem).  Their routers are usually sub-par quality, lacking features, poor support.  Bridge from the ISP's modem/router to your own equipment whenever possible.  I setup offices around the country and have had a chance to work with lots of different ISP's.  I've found it's better to just make the ISP equipment as dumb as possible and use your own equipment for all the firewall, port forwarding, wan IP config, etc.  Using a sonicwall, for example, you can utilize all the support resources of sonicwall to achieve whatever you need instead of relying on Comcast 1-800-WHO-CARES to try to configure whatever the Comcast/Time-Warner/Verizon/AT&T router flavor of the month is.  Just get the ISP modem/router into bridge mode and you're done dealing with their device.


text:
Q: How do I update the SQL Server 2008 to include the studio? How do I update the SQL Server 2008 to include the studio?
Here is what I currently have on my machine:

I assume I am supposed to clidk on "SQL Server Installation Center"
From there I get this window:

and I assume I am supposed to click on the first item on the right side, "New SQL Server stand-alone installation or add features to an existing installation". Is this right?
When I do this, I am asked to "Browse For Folder" but every folder I have picked so far has been denied. What do I do?
I have even resorted to uninstalling everything (via the OS Control Panel) and reinsatlling.  I still get o the point where it asks me for the location of the installation.  I install of a network, but it does not accept the location of the newtork when I give it.

A: Try running setup.exe from the network directory where the SQL 2008 binaries are located.

A: Is this the Express version of Microsoft SQL server?
If so you'll need to download the management tools from here:
http://www.microsoft.com/download/en/details.aspx?id=8961

A: From your Installation menu, run the first option.  This will install some necessary setup files then allow you to select the instance you wish to modify.  On the Feature Selection page of the install, you will have the ability to just select the SSMS.


text:
Q: IndexedDB can make database unreachable (getting blocked), how unblock? UPDATE
I discovered the issue is that it's blocked. Despite the database always being created and upgraded by the same extension, it does not get closed. So now I'm getting the "onblocked" function called.
How do I "unblock" currently blocked databases? And how do I prevent this in the future? This is an app, so no tabs are using it. And since I can't open those databases to even delete them (this also gets blocked), how do I close them?
(For anyone wondering, to avoid this issue from the start, you HAVE to do the folllowing:)
mydb.onversionchange = function(event) {
    mydb.close();
};

Original Post
IndexedDB dies and becomes unopenable if I (accidentally) try to open and upgrade with the wrong version. As far as I can tell, there's no way to ask indexedDB for the latest version of a DB. So if I try to run the following code twice, it destroys the database and it becomes unopenable:
And it never throws an error or calls onerror. It just sits silently
var db = null;

//Note, no version passed in, so the second time I do this, it seems to cause an error
var req = indexedDB.open( "test" );
req.onsuccess = function(event) { console.log( "suc: " + event.target.result.version ); db = event.target.result; };
req.onerror = function(event) { console.log( "err: " + event ); };
req.onupgradeneeded = function(event) { console.log( "upg: " + event.target.result.version ); };

//We're doing in interval since waiting for callback
var intv = setInterval(
    function()
    {
        if ( db === null ) return;

        clearInterval( intv );

        var req2 = indexedDB.open( "test", db.version + 1 );
        req2.onsuccess = function(event) { console.log( "suc: " + event.target.result.version ); };
        req2.onerror = function(event) { console.log( "err: " + event ); };
        req2.onupgradeneeded = function(event) { console.log( "upg: " + event.target.result.version ); };
    },
    50
);

All of that code is in my chrome.runtime.onInstalled.addListener. So when I update my app, it calls it again. If I call indexedDB.open( "test" ) without passing in the new version and then again run the setInterval function, it causes everything to become unusable and I'm never able to open "test" again. This would be solved if I could query indexedDB for the version of a database prior to attempting to open it. Does that exist?

A: Maybe this helps?
function getVersion(callback) {
  var r = indexedDB.open('asdf');
  r.onblocked = r.onerror = console.error;
  r.onsuccess = function(event) {
    event.target.result.close();
    callback(event.target.result.version);
  };
}

getVersion(function(version) {
  console.log('The version is: %s', version);
});

Ok, based on the convo, this little util function might set you on the path:
var DATABASE_NAME_CONSTANT = 'whatever';

// Basic indexedDB connection helper
// @param callback the action to perform with the open connection
// @param version the version of the database to open or upgrade to
// @param upgradeNeeded the callback if the db should be upgraded
function connect(callback, version, upgradeNeeded) {
   var r = indexedDB.open(DATABASE_NAME_CONSTANT, version);
   if(upgradeNeeded) r.onupgradeneeded = updateNeeded;
   r.onblocked = r.onerror = console.error;
   r.onsuccess = function(event) {
     console.log('Connected to %s version %s',
       DATABASE_NAME_CONSTANT, version);
     callback(event.target.result);
   };
}

// Now let us say you needed to connect
// and need to have the version be upgraded
// and need to send in custom upgrades based on some ajax call

function fetch() {
  var xhr = new XMLHttpRequest();
  // ... setup the request and what not
  xhr.onload = function(event) {
    // if response is 200 etc
    // store the json in some variable
    var responseJSON = ...;

    console.log('Fetched the json file successfully');
    // Let's suppose you send in version and updgradeNeeded
    // as properties of your fetched JSON object
    var targetVersion = responseJSON.idb.targetVersion;
    var upgradeNeeded = responseJSON.idb.upgradeNeeded;

    // Now connect and do whatever
    connect(function(db) {
      // Do stuff with the locally scoped db variable
      // For example, grab a prop from the fetched object
      db.objectStore('asdf').put(responseJSON.recordToInsert);

      // If you feel the need, but should not, close the db
      db.close();
      console.log('Finished doing idb stuff');
    }, targetVersion, upgradeNeeded);
  }
}

A: I think it is best to provide the version number always. If you don't how are you going to manage upgrades on the db structure? If you don't its a good chance you will get in a situation where same db versions on a client will have an other database structure, and I don't think that is the thing you want. So I would suggest to keep the version number in a variable.
Also when working with indexeddb you will have to provide an upgrade plan from al previous versions to the current. Meaning version 4 has a certain structure, but you will have to be able to get that same structure from scratch as from version 1,2 and 3


text:
Q: empty string in dynamic SQL cause exception I need to use dynamic SQL in a store procedure. Here is my code
set @value = ''(empty string)

set @SQL = 'INSERT INTO #temp(ID)
        SELECT distinct contact.ID FROM contact
        LEFT JOIN address on address.ID = contact.ID'
set @where = 'where ' + @parameter + '=' + @value  + 'OR ' + @parameter + ' = address.cityCode'

begin
    set @all =  @SQL + @where
    EXEC sp_executesql @all
end

when transaction begins, @parameter also has a value of ''(empty string).

exception throwed by JDBC:
Incorrect syntax near '='. at com.microsoft.jdbc.base.BaseExceptions.createException

I think it's caused by the value of empty string. So what can I do to make empty string valid when concatenating dynamic SQL? Thanks!

A: You need to wrap your empty string in quotes. Right now, it will work out to WHERE parameter =OR which is clearly bad syntax.
Change your code to include the quotes and it should work.
set @where = 'where ' + @parameter + ' = ''' + @value  + ''' OR ' + @parameter + ' = address.cityCode'

Note, of course, that you then won't want them in whatever you do set @value to be. So if you were accounting for the lack of quotes there, either remove it, or set your empty @value to ''''' (a quote, two escaped quotes, then another quote).

A: *

*For standard application make, writing dynamic SQL inside of a stored procedure is just as bad as writing it in client code. SQL injecton and performance can still kill you.

*In the context of your SQL statement, there is no value you can generically assign to @parameter that will make it work, @parameter takes the place of a column name (twice) in your SQL expression. What could possibly be a useful substitute? You might in theory test for @parameter and generate different SQL  for the lack of a parameter name (but you would have to know what alternative would be good in your case).

*You will need to quote parameter if you use a "illegal" column name like embedded spaces or a SQL keyword.

*You will also need to quote @value if if represents a string. In T-SQL you can also quote integer values, etc. without causing problems.

*Did I mention don't use dynamic situation for an application like this even in a stored procedure.


text:
Q: Problem in cropping a bounding box out of an image My objective is to crop a bounding box out of an image using opencv's cv2 library. I've found an interesting way of doing it from here, however I am getting an error like
>ValueError: not enough values to unpack (expected 3, got 2)

This is the complete traceback:
Traceback (most recent call last):
  File "text_extraction.py", line 13, in <module>
    image, contours, hierarchy = cv2.findContours(mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
ValueError: not enough values to unpack (expected 3, got 2)

And this is my complete code:
import cv2
import numpy as np
import pytesseract

pytesseract.pytesseract.tesseract_cmd = 'C:/Program Files/Tesseract-OCR/tesseract.exe'
im = cv2.imread('detected-image-2.png')
grayimage = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(grayimage, 170, 255, cv2.THRESH_BINARY)
cv2.imshow('mask', mask)
image, contours, hierarchy = cv2.findContours(mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
    if cv2.contourArea(contour) < 200:
        continue
    rect = cv2.minAreaRect(contour)
    box = cv2.boxPoints(rect)

    ext_left = tuple(contour[contour[:, :, 0].argmin()][0])
    ext_right = tuple(contour[contour[:, :, 0].argmax()][0])
    ext_top = tuple(contour[contour[:, :, 1].argmin()][0])
    ext_bot = tuple(contour[contour[:, :, 1].argmax()][0])

    roi_corners = np.array([box], dtype=np.int32)

    cv2.polylines(im, roi_corners, 1, (255, 0, 0), 3)
    cv2.imshow('image', im)
    cv2.waitKey(0)

    cropped_image = grayimage[ext_top[1]:ext_bot[1], ext_left[0]:ext_right[0]]
    cv2.imwrite('crop.jpg', cropped_image)

What exactly is wrong in this code?
I am relatively new to OpenCV, please help me out.
EDIT: I even tried a way by referring to this answer however the problem still persists.
EDIT-2: upon solving the Value Error, the script was unable to save the cropped image(It was saving the image as it as). Based on statemachines code I changed the code to this:
im = cv2.imread('detected-image-2.png')
grayimage = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(grayimage, 170, 255, cv2.THRESH_BINARY)
cv2.imshow('mask', mask)
cv2.waitKey(0)
contours, hierarchy = cv2.findContours(mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

for contour in contours:
    if cv2.contourArea(contour) < 200:
        continue
    rect = cv2.minAreaRect(contour)
    box = cv2.boxPoints(rect)
    X, Y, W, H = cv2.boundingRect(contour)
    cropped_image = im[Y:Y + H, X:X + W]
    print([X, Y, W, H])
    plt.imshow(cropped_image)
    cv2.imwrite('contour1.png', cropped_image)

However the output is still the same(cropping is not happening).

A: Solved it myself after figuring it out where I was making a mistake, in case if someone faces a similar issue, this piece of code would help.
def crop():
    # reading image
    image = cv2.imread("detected-image-1.png")

    # converting to gray scale
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # applying canny edge detection
    edged = cv2.Canny(gray, 10, 250)

    # finding contours
    (cnts, _) = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    idx = 0
    for c in cnts:
        x, y, w, h = cv2.boundingRect(c)
        if w > 50 and h > 50:
            idx += 1
            new_img = image[y:y + h, x:x + w]
            # cropping images
            cv2.imwrite("cropped/" + str(idx) + '.png', new_img)
    print('Objects Cropped Successfully!')


text:
Q: Reconstructing a restricted distribution from its mean and standard deviation For simplicity lets assume we have a continuous distribution from 0 to 100.
If the mean is 60 and std is 10, then it would make sense to simply model it as a gaussian with those parameters.
However if the mean is 85 and std is 40, then it is quite clear that the distribution cannot look like a gaussian. My question is, what can we say about such a distribution. How could such a distribution be estimated?

A:
I've attached a picture of various beta densities from the wiki on the Beta Distribution.  It really matters what your density looks like beyond the first two moments you specified, but in general, this will ensure the values are restricted to a bounded interval.

If you aren't concerned with some density living outside your interval you might consider using a Gamma Density.
If you really have no idea what the density looks like and want to restrict to a bounded interval you determine the maximal entropy density.  This will be the one subject to the constraints of a bounded interval with fixed mean and variance.  See this wiki page on the Maximum Entropy Probability Distribution.  In particular, the section headed "A theorem due to Boltzmann".


text:
Q: How to put numeric vector into function instead of character in R? Suppose I have a data frame:
gr <- c(0,0,1,0,1,1)
x <- c(10, 11, 12, 13, 14, 15)
y <- c(20, 21, 22, 23, 24, 25)
z <- c(30, 31, 32, 33, 34, 35)
data <- data.frame(gr, x, y, z)

I would like to perform a t.test of all variables in my data frame. To do that I wrote a function
t_test <- function(var){
  p <- t.test(var ~ gr)$p.value
  t <- t.test(var ~ gr)$statistic

  if (p < 0.05) {
    des <- 'good'
  } else { des <- 'bad'}

  out <- list(p, t, des)
  return(out)
}

And then I'd like to perform t.test.
What I figured out is that if I put name of column into function, the function doesn't work. For example
t_test('x')

In this case an error occurs. But when I run the following code
t_test(x)

i.e. without quotes everything works well.
How to resolve this problem?
This is very important because I have a data frame with 80 columns and I need to perform this test in loop like this:
data_colnames <- names(data)[2:ncol(data)]
t_test_data <- data.frame(matrix(ncol = 4, nrow = 0))
names(t_test_data) <- c("variable", "t_stat", "p_value", "decision")

for (i in 1:length(data_colnames)){
  t_test_data[i,  'variable'] <-  data_colnames[i]
  t_test_data[i, 't_stat']  <- t_test(data_colnames[i])[2]
}

A: We can use paste or reformulate to create the formula from a string input.  In the OP's code, two times the model was build to access the 'p.value' and 'statistic'.  Instead, build the model once and extract the components by assinging it to an object ('tmodel')
t_test <- function(var){
  tmodel <- t.test(reformulate("gr", response = var))
  p <- tmodel$p.value
  t <- tmodel$statistic

  if (p < 0.05) {
    des <- 'good'
  } else { des <- 'bad'}

  out <- list(t, p, des)
  return(out)
}

-testing
> t_test("x")
[[1]]
        t
-1.870829

[[2]]
[1] 0.1347019

[[3]]
[1] "bad"

For multiple cases, do
> sapply(data_colnames, \(x) setNames(t_test(x), names(t_test_data)[-1]))
               x         y         z
t_stat   -1.870829 -1.870829 0.1492787
p_value  0.1347019 0.1347019 0.8931025
decision "bad"     "bad"     "bad"

Or using the OP's for loop
for (i in seq_along(data_colnames)){
    t_test_data[i,  'variable'] <-  data_colnames[i]
   t_test_data[i, -1] <- t_test(data_colnames[i])
 }

-output
> t_test_data
  variable     t_stat   p_value decision
1        x -1.8708287 0.1347019      bad
2        y -1.8708287 0.1347019      bad
3        z  0.1492787 0.8931025      bad

A: Here is an alternative how you could achieve your task:
library(dplyr)
library(broom)
data %>%
    mutate(gr = as.character(gr)) %>%
    select_if(is.numeric) %>%
    map_df(~ tidy(t.test(. ~ gr)), .id = 'var') %>%
    select(var, statistic, p.value) %>%
    mutate(decision = ifelse(p.value < 0.05, "good", "bad"))

  var   statistic p.value decision
  <chr>     <dbl>   <dbl> <chr>
1 x         -1.87   0.135 bad
2 y         -1.87   0.135 bad
3 z         -1.87   0.135 bad


text:
Q: java UnknownHostException I am trying this simple tutorial from oracle : http://www.oracle.com/technetwork/java/socket-140484.html (the Example 1 ). Here you have the two classes, SocketServer.java and SocketClient.java. When I run the client ( after I started the server), I get "Unknown host: kq6py.eng" in the console. I am on MAC OS X. What should I do? I tried setting the proxy settings in Eclipse but nothing changed.

A: It's written The listenSocket method first creates a Socket object with the computer name ( kq6py) and port number (4321)
I doubt you got the same computer name as the example, so you should replace it by your computer name.


text:
Q: Prove the following integral inequality: $\int_{0}^{1}(f''(x))^2dx\ge 1920\left(\int_{0}^{1}f(x)dx\right)^2$
Let $f$ be a twice continuously differentiable function from $[0,1]$ into $\mathbb R$. Given that
  $$f(0)+2f(\frac{1}{2})+f(1)=0,$$
  show that
  $$\int_{0}^{1}(f''(x))^2dx\ge 1920\left(\int_{0}^{1}f(x)dx\right)^2.$$

I tried some methods, such as Cauchy-Schwarz inequality
$$\int_{0}^{1}(f''(x))^2dx\cdot\int_{0}^{1}g^2(x)dx\ge\left(\int_{0}^{1}f''(x)g(x)dx\right)^2,$$
where $g(x)$ is polynomial function and $\max{\deg{(g(x))}}\le 2$.
And by parts integral we have
$$\int_{0}^{1}f''(x)g(x)dx=f'(1)g(1)-f'(0)g(0)-f(1)g'(1)+f(0)g'(0)+\int_{0}^{1}f(x)g''(x)dx=
f'(1)g(1)-f'(0)g(0)-f(1)g'(1)+f(0)g'(0)+C\int_{0}^{1}f(x)dx.$$

A: *

*Let $g_1(x)=x(x-1/2)$, $g_2(x)=(x-1)(x-1/2)$. By two integration by parts, we have

$$\int_0^{1/2}f^{\prime\prime}(x)g_1(x)dx=-\frac{f(1/2)+f(0)}{2}+2\int_0^{1/2}f(x)dx$$
and
$$\int_{1/2}^{1}f^{\prime\prime}(x)g_2(x)dx=-\frac{f(1/2)+f(1)}{2}+2\int_0^{1/2}f(x)dx$$
Hence
$$\int_0^{1/2}f^{\prime\prime}(x)g_1(x)dx+\int_{1/2}^{1}f^{\prime\prime}(x)g_2(x)dx=2\int_0^1f(x)dx$$

*By Cauchy-Schwarz:

$$\left(\int_{0}^{1/2}f^{\prime\prime}(x)g_1(x)dx\right)^2\leq \left(\int_{0}^{1/2}f^{\prime\prime}(x)^2dx\right)\frac{1}{15.2^6}$$
$$\left(\int_{1/2}^{1}f^{\prime\prime}(x)g_2(x)dx\right)^2\leq \left(\int_{1/2}^{1}f^{\prime\prime}(x)^2dx\right)\frac{1}{15.2^6}$$

*Use now $\sqrt{U}+\sqrt{V}\leq \sqrt{2}\sqrt{U+V}$ with $\displaystyle U=\int_{0}^{1/2}f^{\prime\prime}(x)^2dx$ and $\displaystyle V=\int_{1/2}^{1}f^{\prime\prime}(x)^2dx$ to finish the proof.

A: Let $g(x)$ be the piecewise differentiable function defined as,
$$g(x)=\begin{cases}
g_1(x),\quad x\in\left[0,\frac{1}{2}\right)\\
g_2(x),\quad x\in\left[\frac{1}{2},1\right]
\end{cases}$$
By integration by parts, we find
\begin{align*}
\int_0^{\frac{1}{2}}g_1(x)f''(x)\mathrm{d}x
&=g_1(x)f'(x)\bigg|_0^{\frac{1}{2}}-\int_0^{\frac{1}{2}}g_1'(x)f'(x)\mathrm{d}x\\
&=g_1(x)f'(x)\bigg|_0^{\frac{1}{2}}-g_1'(x)f(x)\bigg|_0^{\frac{1}{2}}+\int_0^{\frac{1}{2}}g_1''(x)f(x)\mathrm{d}x
\end{align*}
and
\begin{align*}
\int_{\frac{1}{2}}^1g_2(x)f''(x)\mathrm{d}x
&=g_2(x)f'(x)\bigg|_{\frac{1}{2}}^1-\int_{\frac{1}{2}}^1g_2'(x)f'(x)\mathrm{d}x\\
&=g_2(x)f'(x)\bigg|_{\frac{1}{2}}^1-g_2'(x)f(x)\bigg|_{\frac{1}{2}}^1+\int_{\frac{1}{2}}^1g_2''(x)f(x)\mathrm{d}x
\end{align*}
First, we need
$g_1''(x)=g_2''(x)=\text{constant}$, so, $g_1(x)$ and $g_2(x)$ are quadratic polynomials
$$\begin{cases}
g_1(x)=cx^2+a_1x+a_0,\quad x\in[0,\frac{1}{2})\\
g_2(x)=cx^2+b_1x+b_0,\quad x\in[\frac{1}{2},1]
\end{cases}$$
Next, Let $$g_1(x)f'(x)\bigg|_0^{\frac{1}{2}}+g_2(x)f'(x)\bigg|_{\frac{1}{2}}^1=0$$
we get,
$$g(1)=g(0)=0\Rightarrow a_0=0,c+b_1+b_0=0 \tag{1}$$
and
$$g_1\left(\frac{1}{2}\right)=g_2\left(\frac{1}{2}\right)\Rightarrow \frac{1}{2}a_1=\frac{1}{2}b_1+b_0\tag{2}$$
Next, Let
$$g_2'(x)f(x)\bigg|_{\frac{1}{2}}^1+g_1'(x)f(x)\bigg|_0^{\frac{1}{2}}=g'(1)f(1)+\left(g_1'\left(\frac{1}{2}\right)-g_2'\left(\frac{1}{2}\right)\right)f\left(\frac{1}{2}\right)-g'(0)f(0)=0$$
Since, $f(0)+2f(\frac{1}{2})+f(1)=0$, we get
$$g_1'\left(\frac{1}{2}\right)-g_2'\left(\frac{1}{2}\right)=-2g'(0)=2g'(1)$$
so
$$a_1-b_1=-2a_1=4c+2b_1 \tag{3}$$
from $(1),(2),(3)$, we get
$$a_0=0,\quad a_1=-\frac{1}{2}c,\quad b_1=-\frac{3}{2}c,\quad b_0=\frac{1}{2}c$$
Therefore,
$$\int_0^1g(x)f''(x)\mathrm{d}x
=\int_0^1g''(x)f(x)\mathrm{d}x=2c\int_0^1f(x)\mathrm{d}x$$
by Cauchy-Schwarz inequality, we get
$$\left(2c\int_0^1f(x)\mathrm{d}x\right)^2\leqslant \int_0^1(g(x))^2\mathrm{d}x\int_0^1(f''(x))^2\mathrm{d}x$$
Among,
$$\int_0^1(g(x))^2\mathrm{d}x=\int_0^{\frac{1}{2}}(g(x))^2\mathrm{d}x+\int_{\frac{1}{2}}^1(g(x))^2\mathrm{d}x=\frac{c^2}{480}$$
Finally, we get
$$\int_{0}^{1}(f''(x))^2\mathrm{d}x\geqslant 1920\left(\int_{0}^{1}f(x)\mathrm{d}x\right)^2. \tag*{$\Box$}$$


text:
Q: AppCenter "App not installed as package conflicts with an existing package"
I have seen a similar stack overflow question but none that was for AppCenter. You can see that I have completely different version number and version codes for each release. I downloaded release 332, then tried download release 333 and this error message happens. How do I fix this? Why does this not happen on iOS appcenters?

A: Your old app has the same package name that the new app has. Whatever the version number maybe, you cannot install another app with same package name.  Assuming, the old package name is com.demoapp New app will not accept its package name as the same as above. It should be something like com.demoappCopy.

A: Are all of your builds signed with the same release signing config? If the builds are not signed with the same key then you will get this error because it treats them as two different applications instead of an upgrade to the existing application.


text:
Q: Azure Apns Hub not working with production Certificate I have successfully tested an azure apns hub in sandbox mode. Now when I try to switch  over to production, nothing works. I have read the tutorials, and i'm sure that I generated the production certificate right. Does anybody have an idea what the problem would be? At some point I think I have read that while I was using an Iphone to test the sandbox apns, it may not work after switching to production.

A: After debugging some more, I figured out what the problem was. I had to run my application with the production certificate. That means, that I could not test the production APNS running the app through Xcode, since xcode would automatically install the development certicicate that is linked to the sandbox apns. Run the app outside of xcode, with the production certificate.


text:
Q: MySQL LOAD DATA INFILE and STR_TO_DATE first conversion error I have a basic script that takes a file submitted by an html form and adds it to a database:
<?php

move_uploaded_file($_FILES["file"]["tmp_name"], "C:/xampp/files/" . $_FILES["file"]["name"]);

$con= @new mysqli("127.0.0.1","root","","soilmois");

$file_location = "C:/xampp/files/" . $_FILES["file"]["name"];

$query =    "LOAD DATA LOCAL INFILE '$file_location'
            INTO TABLE testing
            FIELDS TERMINATED BY ','
            LINES TERMINATED BY '\\n'
            (@datetime,column2)
            SET datetime = STR_TO_DATE(@datetime, '%c/%e/%Y %H:%i:%s')";

?>

I am having no trouble uploading the file, except the very first entry for the datetime field is always null:
0000-00-00 00:00:00

I have tried this with multiple text files of the same format and get the same result.
I suspect it has something to do with the character encoding, perhaps the leading character in the file is being included in the first datetime entry.  Any ideas as how to verify the character encoding is the source of the problem?
Thanks


text:
Q: PHP : show all rows in MySQL that contain the same value in a column I am trying write code in PHP with a Mysql database, and the problem is I want to show all rows with a same column value. for example like this:
id  |   Name   | age | Location | type
----+----------+-----+----------+------
 1  | Ane      | 22  |  SG      |  1
 2  | Angi     | 19  |  IND     |  2
 3  | Bobby    | 23  |  PH      |  1
 4  | Denis    | 26  |  IND     |  1
 5  | Jerry    | 21  |  SG      |  1
 6  | Mikha    | 25  |  JP      |  2

I want only show the rows with value in column type = 1 or value in column Location and showing as table in html view.
The result what I want is like this:
id  |   Name   | age | Location | type
---+----------+-----+----------+------
 1  | Ane      | 22  |  SG      |  1
 3  | Bobby    | 23  |  PH      |  1
 4  | Denis    | 26  |  IND     |  1
 5  | Jerry    | 21  |  SG      |  1

This is my code:
<?php
$con = mysqli_connect("localhost","root","","testuser");
$query = mysqli_query("SELECT * FROM `usersdata` WHERE `type`='1'");
$result = mysqli_query($con,$query);

echo "

ID
Name
Age
Location
Type

";

while($row = mysqli_fetch_array($result)){
echo "
";
echo "" . $row['id'] . "	";
echo "" . $row['name'] . "	";
echo "" . $row['age'] . "	";
echo "" . $row['location'] . "	";
echo "" . $row['type'] . "	";
echo "
";
}
echo "
";
?>

But I got errors like this:

Warning: mysqli_query() expects at least 2 parameters, 1 given in www.myweb.com\users_list\type.php on line 94 << this point "$query" line
  Warning: mysqli_query(): Empty query in www.myweb.com\users_list\type.php on line 95 << this point "$result" line
  Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in www.myweb.com\users_list\type.php on line 109 << this point "while ($row=" line

I was trying understand and still i don't get it, anyone can help me please?! thanks.

A: Change
$query = mysqli_query("SELECT * FROM usersdata WHERE type='1'");
to
$query = "SELECT * FROM usersdata WHERE type='1'";
EDIT
Just for explanation:
mysqli_query takes 2 arguments: connection and query. I assumed that you wanted to just create query string in this line where this error arouse since it is used one line furter as a query string.

A: Issue is in bolow lines.
    $query = mysqli_query("SELECT * FROM usersdata WHERE type='1'");
    $result = mysqli_query($con,$query);
You have 2 ways to resolve this.
1. $query = "SELECT * FROM `usersdata` WHERE `type`='1'";
$result = mysqli_query($con,$query);

2. $query = mysqli_query($con,"SELECT * FROM `usersdata` WHERE `type`='1'");

A: Try this one. It should be working fine
<?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "test";

    // Create connection
    $conn = mysqli_connect($servername, $username, $password, $dbname);
    // Check connection
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }

    $sql = "SELECT * FROM `usersdata` WHERE `type`='1'";
    $result = mysqli_query($conn, $sql);

    echo "

    ID
    Name
    Age
    Location
    Type

";

    while($row = mysqli_fetch_array($result)){
        echo "
";
        echo "" . $row['id'] . "	";
        echo "" . $row['name'] . "	";
        echo "" . $row['age'] . "	";
        echo "" . $row['location'] . "	";
        echo "" . $row['type'] . "	";
        echo "
";
    }
    echo "
";
    ?>


text:
Q: how to export a specific table with oneclick? I have this function that makes a table download in csv format, my problem is that I want to implement this same function but with the "onclick" attribute, selecting the specific table that I want to download, if someone could help me how to do it I would be very grateful.
<button id="export"class="btn btn-success" title="Download CSV">Download table</button>

                        <script type="text/javascript">
                                    const toCsv = function (table) {
                                // Query all rows
                                const rows = table.querySelectorAll('tr');

                                return [].slice
                                    .call(rows)
                                    .map(function (row) {
                                        // Query all cells
                                        const cells = row.querySelectorAll('th,td');
                                        return [].slice
                                            .call(cells)
                                            .map(function (cell) {
                                                return cell.textContent;
                                            })
                                            .join(',');
                                    })
                                    .join('\n');
                            };

                            const download = function (text, fileName) {
                                const link = document.createElement('a');
                                link.setAttribute('href', `data:text/csv;charset=utf-8,${encodeURIComponent(text)}`);
                                link.setAttribute('download', fileName);

                                link.style.display = 'none';
                                document.body.appendChild(link);

                                link.click();

                                document.body.removeChild(link);
                            };

                            const table = document.getElementById('exportMe');
                            const exportBtn = document.getElementById('export');

                            exportBtn.addEventListener('click', function () {
                                // Export to csv
                                const csv = toCsv(table);

                                // Download it
                                download(csv, 'download.csv');
                            });
                                </script>


text:
Q: Plugin System without rebuilding for each OS? I'm making a game that will allow content development and I'd like it to be sort of a DLL based system. But, my game works for Linux (X86 arch) , Mac OSX and 32 bit Windows. Is there a way I could allow content developers to compile only one thing and have it work based on the platform? I fear it might get confusing if there are 3 versions per plugin. What could I do?
Thanks

A: You can decide to use a cross-platform scripting environment like Lua for plugins. This is essentially what most cross-platform games do.

A: You could possibly use LLVM as a middle ground if you want C or C++ plugins.  Have plugin devs ship LLVM assembly/bytecode, and use LLVM's runtime code emission to compile it to native code when you load it.

A: Unless things have changed drastically since I last looked at cross platform development if you are using c/c++ you need to compile and link for the operating system you are going to execute on.
So if you want to run on 3 operating systems you need 3 binaries.

A: weren't e.g. Xfree86 and/or Xorg drivers (video? or something else?)
"cross-OS" so they could be built once and "run" on any OS, at least on the same CPU....
no idea how that works ... a virtual machine of some kind perhaps???
probably overkill ...but certainly possible.....


text:
Q: Hibernate saveOrUpdate() doesn't seem to cascade creation and saving I'm new to Hibernate and am trying to save a "UserState" with a list of "WorkspaceState"s. UserState objects are keyed by a username that is set, the WorkspaceStates are set by UUID scheme. My issue is that if I have a UserState with one WorkspaceState in it, the UserState gets saved but the WorkspaceState does not.
Here are the Hibernate mapping
<hibernate-mapping>
    <class name="UserState" table="USERSTATE">
        <id name="owner" type="java.lang.String">
            <column name="OWNER" />
            <generator class="assigned" />
        </id>
        <list name="workspaces" inverse="false" cascade="all" table="WORKSPACESTATE" lazy="true">
            <key>
                <column name="UID" />
            </key>
            <list-index></list-index>
            <one-to-many class="WorkspaceState" />
        </list>
    </class>
</hibernate-mapping>

<hibernate-mapping>
    <class name="WorkspaceState" table="WORKSPACESTATE">
        <id name="uid" type="java.lang.String">
            <column name="UID" />
            <generator class="uuid" />
        </id>
        <property name="owner" type="java.lang.String">
            <column name="OWNER" />
        </property>
    </class>
</hibernate-mapping>

I have a UserState object with one WorkspaceState in it. When I do a session.saveOrUpdate(userst), I see that hibernate has already removed the WorkspaceState from my userst object. Then the commit saves it to the DB without the workspacestate in it.
In truth the WorkspaceState themselves have lists, but I suspect whatever I'm doing wrong continues onward.
Thanks
Edit - how it's committed. HibernateUtil is as it appears in the standard hibernate document examples:
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;

try {
    transaction = session.beginTransaction();
    String username = (String) session.merge(state);
    transaction.commit();
} catch (HibernateException e) {
    transaction.rollback();
    e.printStackTrace();
    return false;
} finally {
    session.close();
}

A: you need to change cascade reference to save-update and remove inverse attribute from workspace list mapping


text:
Q: The ratio of the arc lenght to the radius Using elementary geometry how is proved that the ratio of the arc length to the radius is the same for concentric arcs of different diameters.

A: It is proved by constructing a similarity of the Euclidean plane, which fixes the center point $O$ of those concentric arcs, and which stretches each ray based at that point by a common factor equal to the quotient $q = \frac{r_2}{r_1}$. One then uses elementary geometry to conclude that the length of every line segment is stretched by that same common factor $q$. By approximating a circular arc with a concatenation of chords, it follows that the length of a circular arc is also stretched by that same factor $q$.
If you were modelling your Euclidean plane with Cartesian coordinates, and if $O$ were the origin of the coordinate system, then this similarity map would simply be
$$f(x,y) = (qx,qy)
$$

A: This is a matter of proportions.
$$\frac{\text{arclength}}{\text{circumference}}=\frac{\text{angle}}{2\pi}\implies \frac{s}{2\pi r}=\frac{\theta}{2\pi}\implies \frac{s}{r}=\theta$$