text:
Q: Objective c - Cell Reuse, AutoLayout and Dynamic Cell Height, How to re-use cells when adding Youtube in UIWebView I have a UITableView that holds information such as an Image, User, Date, Message and a Youtube Video (if there is a Youtube Video). I have used Auto Layout throughout the App and this all worked until i wanted to add Youtube Videos with a UIWebView.
Whats happening is that i don't think i have got the code right for re-using the cells in my UITableView so when i scroll, the cells just don't scroll properly as if the data has been jumbled up.
Just wanted to ask where i am going wrong, i will show you the code:
Custom Cell that has Dynamic Height:
#import "PostTableViewCell.h"

        @implementation PostTableViewCell

        @synthesize main;
        @synthesize top;
        @synthesize center;
        @synthesize centerLeft;
        @synthesize centerRight;
        @synthesize bottom;
        @synthesize labelMessage;
        @synthesize labelCat;
        @synthesize labelSubCat;
        @synthesize labelCountry;
        @synthesize labelUser;
        @synthesize labelDate;
        @synthesize imageviewThreadImage;
        @synthesize youtube;
        @synthesize webviewYoutube;
        @synthesize labelYoutubeTitle;

        - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
            self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
            if (self) {
            [self.contentView setTranslatesAutoresizingMaskIntoConstraints:NO];
            self.contentView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;

            CGRect screenBound = [[UIScreen mainScreen] bounds];
            CGSize screenSize = screenBound.size;
            CGFloat screenWidth = screenSize.width;
            //CGFloat screenHeight = screenSize.height;

            main = [UIView new];
            [self.contentView addSubview:main];
            main.translatesAutoresizingMaskIntoConstraints = NO;
            [main sizeToFit];
            main.backgroundColor = [UIColor whiteColor];

            top = [UIView new];
            [main addSubview:top];
            top.translatesAutoresizingMaskIntoConstraints = NO;
            [top sizeToFit];
            top.backgroundColor = [UIColor whiteColor];

            labelUser = [UILabel new];
            [top addSubview:labelUser];
            labelUser.translatesAutoresizingMaskIntoConstraints = NO;
            [labelUser sizeToFit];
            [labelUser setFont:[UIFont systemFontOfSize:14]];
            labelUser.textColor = [UIColor colorWithRed:(114.0/255.0) green:(114.0/255.0) blue:(114.0/255.0) alpha:1.0];

            labelDate = [UILabel new];
            [top addSubview:labelDate];
            labelDate.translatesAutoresizingMaskIntoConstraints = NO;
            [labelDate sizeToFit];
            [labelDate setFont:[UIFont systemFontOfSize:14]];
            labelDate.textColor = [UIColor colorWithRed:(114.0/255.0) green:(114.0/255.0) blue:(114.0/255.0) alpha:1.0];

            center = [UIView new];
            [main addSubview:center];
            center.translatesAutoresizingMaskIntoConstraints = NO;
            [center sizeToFit];
            center.backgroundColor = [UIColor whiteColor];

            imageviewThreadImage = [UIImageView new];
            [center addSubview:imageviewThreadImage];
            imageviewThreadImage.translatesAutoresizingMaskIntoConstraints = NO;
            imageviewThreadImage.backgroundColor = [UIColor colorWithRed:(207.0/255.0) green:(215.0/255.0) blue:(248.0/255.0) alpha:1.0];
            [imageviewThreadImage sizeToFit];

            labelMessage = [UILabel new];
            [center addSubview:labelMessage];
            labelMessage.translatesAutoresizingMaskIntoConstraints = NO;
            [labelMessage sizeToFit];
            [labelMessage setFont:[UIFont systemFontOfSize:14]];
            labelMessage.preferredMaxLayoutWidth = screenWidth - 10 - 36;
            labelMessage.lineBreakMode = NSLineBreakByWordWrapping;
            labelMessage.numberOfLines = 0;
            labelMessage.textColor = [UIColor lightGrayColor];
            //labelMessage.backgroundColor = [UIColor colorWithRed:(207.0/255.0) green:(215.0/255.0) blue:(248.0/255.0) alpha:1.0];
            //labelMessage.lineBreakMode = UILineBreakModeWordWrap;

            bottom = [UIView new];
            [main addSubview:bottom];
            bottom.translatesAutoresizingMaskIntoConstraints = NO;
            [bottom sizeToFit];

            labelCat = [UILabel new];
            [bottom addSubview:labelCat];
            labelCat.translatesAutoresizingMaskIntoConstraints = NO;
            [labelCat sizeToFit];
            [labelCat setFont:[UIFont systemFontOfSize:12]];
            labelCat.textColor = [UIColor colorWithRed:(58.0/255.0) green:(82.0/255.0) blue:(207.0/255.0) alpha:1.0];
            labelCat.lineBreakMode = NSLineBreakByWordWrapping;
            labelCat.numberOfLines = 0;

            labelSubCat = [UILabel new];
            [bottom addSubview:labelSubCat];
            labelSubCat.translatesAutoresizingMaskIntoConstraints = NO;
            [labelSubCat sizeToFit];
            [labelSubCat setFont:[UIFont systemFontOfSize:12]];
            labelSubCat.textColor = [UIColor colorWithRed:(58.0/255.0) green:(82.0/255.0) blue:(207.0/255.0) alpha:1.0];

            labelCountry = [UILabel new];
            [bottom addSubview:labelCountry];
            labelCountry.translatesAutoresizingMaskIntoConstraints = NO;
            [labelCountry sizeToFit];
            [labelCountry setFont:[UIFont systemFontOfSize:12]];
            labelCountry.textColor = [UIColor colorWithRed:(58.0/255.0) green:(82.0/255.0) blue:(207.0/255.0) alpha:1.0];

            youtube = [UIView new];
            [main addSubview:youtube];
            youtube.translatesAutoresizingMaskIntoConstraints = NO;
            [youtube sizeToFit];
            }

            return self;
        }

        - (void)layoutSubviews
        {
            [super layoutSubviews];
            // Make sure the contentView does a layout pass here so that its subviews have their frames set, which we
            // need to use to set the preferredMaxLayoutWidth below.
            [self.contentView setNeedsLayout];
            [self.contentView layoutIfNeeded];

            // Set the preferredMaxLayoutWidth of the mutli-line bodyLabel based on the evaluated width of the label's frame,
            // as this will allow the text to wrap correctly, and as a result allow the label to take on the correct height.
            self.labelMessage.preferredMaxLayoutWidth = CGRectGetWidth(self.labelMessage.frame);
        }

        - (void)updateConstraints {
            [super updateConstraints];

            if (self.didSetupConstraints) return;

            NSDictionary *viewsDictionary7 = @{@"main":main};
            NSArray *constraint_H37 = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[main]|"
                                              options:0
                                              metrics:nil
                                            views:viewsDictionary7];

            NSArray *constraint_V37 = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[main]|"
                                              options:0
                                              metrics:nil
                                            views:viewsDictionary7];
            [self.contentView addConstraints:constraint_H37];
            [self.contentView addConstraints:constraint_V37];

            //NSString *text = labelMessage.text;

            NSDictionary *viewsDictionary3 = @{@"top":top,@"center":center,@"bottom":bottom,@"youtube":youtube};
            NSArray *constraint_H3 = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-10-[top]-5-[center(>=50)]-5-[bottom]-5-[youtube(>=0)]-10-|"
                                             options:0
                                             metrics:nil
                                               views:viewsDictionary3];

            NSArray *constraint_H33cvcv4545 = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[youtube]|"
                                              options:0
                                              metrics:nil
                                            views:viewsDictionary3];

            NSArray *constraint_H33 = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[top]|"
                                              options:0
                                              metrics:nil
                                            views:viewsDictionary3];

            NSArray *constraint_H333 = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[center]|"
                                               options:0
                                               metrics:nil
                                             views:viewsDictionary3];

            NSArray *constraint_H3335657 = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[bottom]|"
                                               options:0
                                               metrics:nil
                                                 views:viewsDictionary3];

            NSDictionary *viewsDictionary4 = @{@"labelUser":labelUser,@"labelDate":labelDate};
            NSArray *constraint_H4 = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[labelUser]|"
                                             options:0
                                             metrics:nil
                                               views:viewsDictionary4];

            NSDictionary *viewsDictionary45 = @{@"labelDate":labelDate};
            NSArray *constraint_H4555 = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[labelDate]|"
                                            options:0
                                            metrics:nil
                                              views:viewsDictionary45];

            NSArray *constraint_H44 = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-5-[labelUser]-20-[labelDate]-5-|"
                                              options:0
                                              metrics:nil
                                            views:viewsDictionary4];

            NSDictionary *viewsDictionary48 = @{@"labelMessage":labelMessage,@"imageviewThreadImage":imageviewThreadImage};

            NSArray *constraint_H48 = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-5-[labelMessage]|"
                                              options:0
                                              metrics:nil
                                            views:viewsDictionary48];

            NSArray *constraint_H48342 = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-8-[imageviewThreadImage(36)]"
                                             options:0
                                             metrics:nil
                                               views:viewsDictionary48];

            NSArray *constraint_H448345fgdfg = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-5-[imageviewThreadImage(36)]"
                                               options:0
                                               metrics:nil
                                                 views:viewsDictionary48];

            CGRect screenBound = [[UIScreen mainScreen] bounds];
            CGSize screenSize = screenBound.size;
            CGFloat screenWidth = screenSize.width;
            //CGFloat screenHeight = screenSize.height;

            NSArray *constraint_H448345fgdfgdfdf454 = [NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"H:|-46-[labelMessage(%f)]-10-|",screenWidth - 51]
                                                   options:0
                                                   metrics:nil
                                                 views:viewsDictionary48];

            /**NSArray *constraint_H448 = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-5-[labelMessage]-5-|"
                                               options:0
                                               metrics:nil
             views:viewsDictionary48];**/

            NSDictionary *viewsDictionary488 = @{@"labelCat":labelCat,@"labelCountry":labelCountry,@"labelSubCat":labelSubCat};
            NSArray *constraint_H488 = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-5-[labelCat]|"
                                               options:0
                                               metrics:nil
                                             views:viewsDictionary488];
            NSArray *constraint_H48898 = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-5-[labelCountry]|"
                                             options:0
                                             metrics:nil
                                               views:viewsDictionary488];
            NSArray *constraint_H48898fgf54 = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-5-[labelSubCat]|"
                                                  options:0
                                                  metrics:nil
                                                views:viewsDictionary488];

            NSArray *constraint_H4488 = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-5-[labelCat]-10-[labelSubCat]-10-[labelCountry]"
                                            options:0
                                            metrics:nil
                                              views:viewsDictionary488];

            [self.contentView addConstraints:constraint_H3];
            [self.contentView addConstraints:constraint_H33];
            [self.contentView addConstraints:constraint_H333];
            [self.contentView addConstraints:constraint_H4];
            [self.contentView addConstraints:constraint_H44];
            [self.contentView addConstraints:constraint_H48];
            //[self.contentView addConstraints:constraint_H448];
            [self.contentView addConstraints:constraint_H4555];
            [self.contentView addConstraints:constraint_H3335657];
            [self.contentView addConstraints:constraint_H488];
            [self.contentView addConstraints:constraint_H48342];
            [self.contentView addConstraints:constraint_H4488];
            [self.contentView addConstraints:constraint_H448345fgdfg];
            [self.contentView addConstraints:constraint_H48898];
            [self.contentView addConstraints:constraint_H48898fgf54];
            [self.contentView addConstraints:constraint_H448345fgdfgdfdf454];
            [self.contentView addConstraints:constraint_H33cvcv4545];

            self.didSetupConstraints = YES;

        }

        -(void)setYoutube: (NSString*)youtubeID :(NSString*)title {

            if(youtubeID.length > 0){

            dispatch_async( dispatch_get_main_queue(), ^{

                webviewYoutube = [UIWebView new];
                [youtube addSubview:webviewYoutube];
                webviewYoutube.translatesAutoresizingMaskIntoConstraints = NO;
                [webviewYoutube sizeToFit];

                [webviewYoutube setAllowsInlineMediaPlayback:YES];
                [webviewYoutube setMediaPlaybackRequiresUserAction:NO];

                NSString* embedHTML = [NSString stringWithFormat:@"\
                           <html>\
                           <body style='margin:0px;padding:0px;'>\
                           <script type='text/javascript'>\
                           </script>\
                           <iframe id='playerId' type='text/html' width='%d' height='%d' src='http://www.youtube.com/embed/%@?enablejsapi=1&rel=0&playsinline=1' frameborder='0'>\
                           </body>\
                           </html>", 100, 80, youtubeID];
                [[NSURLCache sharedURLCache] removeAllCachedResponses];
                [webviewYoutube loadHTMLString:embedHTML baseURL:[[NSBundle mainBundle] resourceURL]];

                NSDictionary *viewsDictionary7 = @{@"webviewYoutube":webviewYoutube};
                NSArray *constraint_H37 = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-5-[webviewYoutube(80)]|"
                                                  options:0
                                                  metrics:nil
                                                views:viewsDictionary7];

                NSArray *constraint_V37 = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[webviewYoutube(100)]"
                                                  options:0
                                                  metrics:nil
                                                views:viewsDictionary7];
                [self.contentView addConstraints:constraint_H37];
                [self.contentView addConstraints:constraint_V37];

                CGRect newFrame = youtube.frame;

                newFrame.size.height = 100;
                [youtube setFrame:newFrame];

            });

            }else{

            }
        }

        - (void)awakeFromNib {
            // Initialization code
        }

        - (void)setSelected:(BOOL)selected animated:(BOOL)animated {
            [super setSelected:selected animated:animated];

            // Configure the view for the selected state
        }

        @end

The UITableView cellForRowIndexPAth:
if(tableView == tableViewPost){
            //static NSString *simpleTableIdentifier = @"SimpleTableItem";

            //PostTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
            static NSString *simpleTableIdentifier = @"SimpleTableItem2";

            PostTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
            //cell.layer.shouldRasterize = YES;
            //cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
            if (cell == nil) {
                cell = [[PostTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
            }

            Post *t = (Post*)[tmpArray2 objectAtIndex:indexPath.row];
            cell.labelMessage.text = t.message;
            cell.labelCat.text = t.cat;
            cell.labelSubCat.text = t.subcat;
            cell.labelCountry.text = t.country;
            cell.labelUser.text = [NSString stringWithFormat:@"%@", t.user];
            cell.labelDate.text = [NSString stringWithFormat:@"%@", t.date];
            [cell setYoutube:t.youtube :@""];

            [cell.contentView setNeedsUpdateConstraints];
            [cell.contentView updateConstraintsIfNeeded];
            [cell.contentView setNeedsLayout];
            [cell.contentView layoutIfNeeded];
            return cell;
            }

The UITableView heightForRowAtIndexPath:
            if(tableView == tableViewPost){

            int h = 0;
            static NSString *simpleTableIdentifier = @"SimpleTableItem2";
            PostTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
            //PostTableViewCell *cell = (PostTableViewCell*)[self tableView:tableView cellForRowAtIndexPath:indexPath];
            if (cell == nil) {
                cell = [[PostTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];

            }

            [cell.contentView setNeedsUpdateConstraints];
            [cell.contentView updateConstraintsIfNeeded];
            [cell.contentView setNeedsLayout];
            [cell.contentView layoutIfNeeded];

            CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
            //CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];

            return height + h;
            }

The Model Object that stored the Post Data:
#import <Foundation/Foundation.h>

        @interface Post : NSObject

        @property int idThread;
        @property int postID;
        @property(nonatomic,copy) NSString *user;
        @property(nonatomic,copy) NSString *message;
        @property(nonatomic,copy) NSString *youtube;
        @property(nonatomic,copy) NSString *desc;
        @property(nonatomic,copy) NSString *cat;
        @property(nonatomic,copy) NSString *subcat;
        @property(nonatomic,copy) NSString *country;
        @property(nonatomic,copy) NSString *date;
        @property(nonatomic,copy) NSString *imageName;
        @end

        #import "Post.h"

        @implementation Post

        @enda


text:
Q: Add http headers to RestTemplate by Interceptor or HttpEntity? If I have some static headers that should be applied to any request sending with RestTemplate: how should those be added?
In this example, I'd always want to sent the http header accept=applicaton/json. (it could as well be any other header, also multiple ones).
1) HttpEntity directly before sending:
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);

ResponseEntity<Rsp> http = restTemplate.postForEntity(host, new HttpEntity<>(req, headers), type);

2) ClientHttpRequestInterceptor:
class MyInterceptor implements ClientHttpRequestInterceptor {
    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        request.getHeaders().set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
        return execution.execute(request, body);
    }
}

@Bean
public RestTemplateCustomizer customizer() {
    return restTemplate -> restTemplate.getInterceptors().add(new MyInterceptor());
}

And then just post:
restTemplate.postForEntity(host, req, type);

Which one has an advantage over the other, and should thus be preferred?

A: Option 1 seems a little hard to maintain since the developer would need to remember to do it every time. Option 2 would be better, I would only do the following change:
Where you do
restTemplate.getInterceptors().add(new MyInterceptor())

I would do
List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
if (CollectionUtils.isEmpty(interceptors)) {
    interceptors = new ArrayList<>();
}
interceptors.add(new MyInterceptor());
restTemplate.setInterceptors(interceptors);

This way you can initialize the list in case it's empty.
Also, be careful because someone can set a new interceptor list to the bean and lose yours.

A: Java 8 Lambda way of doing it with interceptor
new RestTemplateBuilder().interceptors(
   (HttpRequest request, byte[] body, ClientHttpRequestExecution execution) -> {
      request.getHeaders().set(AUTHORIZATION, token);
      return execution.execute(request, body);
   }
).build()

A: 1) HttpEntity directly before sending: fine-grained control of the restTemplate. It works but you must repeat the code everywhere and the developer may forget it (DRY)
2) ClientHttpRequestInterceptor with RestTemplateCustomizer: Each restTemplate created from restTemplateBuilder bean will have this interceptor, suitable for a general behavior.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make this google script more efficient I got this script to get into a folder and get the key for each file.
function listFilesInFolder(id) {

  var folder = DriveApp.getFolderById('');
  var contents = folder.getFiles();
  var file;
  var name;
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Imported");
  var date;
  var size;

  sheet.clear();
  sheet.appendRow(["Name", "Data", "Size", "Id"]);

  while(contents.hasNext()) {
    file = contents.next();
    name = file.getName();
    date = file.getDateCreated()
    size = file.getSize()
    id = file.getId()

    data = [name, date, size, id]
    sheet.appendRow(data);

    //appendRow
  }
};

my problem is that taking too much time to finish going through the whole folder, it usually hits run-time limit before it finishes.
The folder contains 1000+ different files, we automatically upload files daily.
is there any way to make this script more efficient?

A: I believe your goal as follows.

*

*You want to retrieve the file list just under the specific folder using Google Apps Script.

*You want to reduce the process cost of your current script in your question.

Modification points:

*

*In your script, appendRow is used in a loop. In this case, the process cost will be high. Ref

*And, I thought that in your situation, when Drive API is used, the process cost might be able to be a bit reduced.

When above points are reflected to your script, it becomes as follows.
Modified script:
Before you use this script, please enable Drive API at Advanced Google services.
function listFilesInFolder(id) {
  var folderId = "###"; // Please set the folder ID. If you want to use "id" for this, you can use var folderId = id;

  // 1. Retrieve file list using Drive API.
  var ar = [["Name", "Data", "Size", "Id"]];
  var pageToken = "";
  do {
    const res = Drive.Files.list({corpora: "allDrives", includeTeamDriveItems: true, supportsAllDrives: true, maxResults: 1000, pageToken: pageToken, q: `'${folderId}' in parents`});
    ar = ar.concat(res.items.map(({title, createdDate, fileSize, id}) => [title, createdDate, fileSize || 0, id]));
    pageToken = res.nextPageToken;
  } while(pageToken);

  // 2. Put the file list to Spreadsheet.
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Imported");
  sheet.clear();
  sheet.getRange(1, 1, ar.length, ar[0].length).setValues(ar);
}

Note:

*

*From your question, I couldn't understand about the detail of your situation. So in this modified script, the folders in both your Google Drive and the shared Drive can be searched.

References:

*

*Benchmark: Reading and Writing Spreadsheet using Google Apps Script

*Files: list


text:
Q: Underline Rows in Only One Column of Multirow Multicolumn Table with ONLY Two Columns I am trying to make a multicolumn, multirow table with two columns and 5 rows. I want each row in the second column only underlined. Obviously, \bottomrule underlines both columns, as does \hline. \hline also throws a \noalign error. Neither \cline{2-2}, \cline{2-3}, nor \cline{2} work. Both \cline{2-2} and \cline{2} underline both columns, and \cline{2-3} throws an Extra alignment tab error.
I have tried many different package combinations without luck, and I want the final document to be simple for school teachers to use (Grades 1 - 12.)
\documentclass[12pt]{article}
\usepackage[text={7.25in,10in}]{geometry}
\usepackage{multirow}
\usepackage[latin1]{inputenc}
\usepackage[pdftex]{hyperref}
%------------------------------%
\usepackage{graphicx}
\usepackage{booktabs}
\usepackage{float}
\usepackage{array}

\begin{document}

    \begin{table}[H]
        \begin{tabular}{ll}
        \toprule
        \multicolumn{2}{l}{Learning Standard(s): }\begin{minipage}{5.5in} CCSS # \end{minipage}\\
        \bottomrule
        \multicolumn{2}{l}{Lesson Objective(s): }\begin{minipage}{5.5in}\par The learner                                        will be able to . . . \end{minipage}\\
        \bottomrule

        %------problem begins here-----

        \multicolumn{2}{l|}{\multirow{5}{*}{\rotatebox{90}{Lesson Activities}}}\begin{minipage}
        {6in}Demonstration:\end{minipage}\\
        \multicolumn{2}{l|}{}\begin{minipage}{6in}Guided Practice: \end{minipage}\\
        \multicolumn{2}{l|}{}\begin{minipage}{6in}Individual Practice:\end{minipage}\\
        \multicolumn{2}{l|}{}\begin{minipage}{6in}Formative Assessment: \end{minipage}\\
        \multicolumn{2}{l|}{}\begin{minipage}{6in}Other/Notes: \end{minipage}\\

        %-----problem ends here-----
        \toprule
        \multicolumn{2}{l}{Lesson Resources: }\begin{minipage}{5.5in} \end{minipage}\\
        \bottomrule
        \multicolumn{2}{l}{Lesson Close: }\begin{minipage}{5.5in} \end{minipage}\\
        \bottomrule
    \end{tabular}
\end{table}

\end{document}

I am expecting something like the following.
_______________________
|     |_______________|
|     |_______________|
|     |_______________|
|     |_______________|
|_____|_______________|

A: *

*you must not use # in your table without escaping it

*latin1 input encoding is most probably wrong. Double check if your file really is encoded in latin1, this would be very unusual this century

*don't specify a driver to hyperref - in the best case it is unnecessary because hyperref will automatically detect it, in all other case it will simply be wrong

*if you want to have the rule only in one column, then you should actually use more than one column and not bake everything together into a single column

*have a look at the tabularray package, this would make your table way less painful

\documentclass[12pt]{article}
\usepackage[text={7.25in,10in}]{geometry}
\usepackage{multirow}
%\usepackage[latin1]{inputenc}
\usepackage[]{hyperref}
%------------------------------%
\usepackage{graphicx}
\usepackage{booktabs}
\usepackage{float}
\usepackage{array}

\begin{document}

    \begin{table}[H]
        \begin{tabular}{p{1in}l}
        \toprule
        \multicolumn{2}{l}{Learning Standard(s): }\begin{minipage}{5.5in} CCSS \# \end{minipage}\\
        \bottomrule
        \multicolumn{2}{l}{Lesson Objective(s): }\begin{minipage}{5.5in}\par The learner                                        will be able to . . . \end{minipage}\\
        \bottomrule

        %------problem begins here-----

        \multirow{5}{*}{\rotatebox{90}{Lesson Activities}} & Demonstration:\\ \cmidrule{2-2}
        & Guided Practice: \\ \cmidrule{2-2}
        & Individual Practice:\\ \cmidrule{2-2}
        & Formative Assessment: \\ \cmidrule{2-2}
        & Other/Notes: \\

        %-----problem ends here-----
        \toprule
        \multicolumn{2}{l}{Lesson Resources: }\begin{minipage}{5.5in} \end{minipage}\\
        \bottomrule
        \multicolumn{2}{l}{Lesson Close: }\begin{minipage}{5.5in} \end{minipage}\\
        \bottomrule
    \end{tabular}
\end{table}

\end{document}


text:
Q: Why won't my hard drive work properly on my laptop, but work fine on my desktop? I've been having this issue for the last couple of weeks and I ran out of ideas.
2-3 weeks after adding an SSD to my laptop (alongside a HDD) my hard disk is constantly showing errors and getting removed by Intel RST. So far I tried these in order to find the problem:
-uninstalling Intel RST, which made little to no difference
-booting from a live Ubuntu USB drive, which made no difference
-connected my HDD to my old computer and somehow it worked perfectly (!?)
-ran many different programs to check my hard disk for errors and try to fix them (most didn't manage to do much because my hard drive got disconnected, while others showed no error)
-some antivirus software to check for potential issues - there were none
Some things I noticed:
-almost always when I check the notifications, there is one from Security and Maintenance asking to scan drive for errors - nothing happens when I click it
-the hard drive keeps restarting (a.k.a clicking noises) randomly
It's worth mentioning that I run Windows 10 and it's installed on my SSD. Also, the first time I noticed something was wrong was after I downloaded a big video file and when I tried to play it, there were lots of interruptions. The next morning I got the errors and disconnections (over night the laptop was powered on and running my torrent program).
Maybe there could be something wrong with the cable connecting my hard drive, but I have no idea how to check that, since my old computer has different cables and I couldn't find a similar cable online.
Do you have any ideas that could help me solve this issue ?

A: For those having this issue, this is what I found that helps:

*

*Computer Management

*Device Manager

*IDE ATA/ATAPI controllers

*Properties

*Driver

*Update

*Browse

*Pick from a list of available drivers

*Standart SATA AHCI Controller

*Next, Close and Restart

For some reason, my HDD stopped getting disconnected, although it's still kind of slow.
EDIT:
It was too slow so I had to buy a HDD rack and use it as an external hard drive. I really suggest this approach for everyone having this issue, since the rack is way cheaper than other solutions.


text:
Q: Add Gesture to UICollectionViewCell subview with xib I'm trying to add a gesture to a subview of a UICollectionViewCell make with xib, I'm doing this:
.h
@interface MyCell : UICollectionViewCell <UIGestureRecognizerDelegate>

@property (weak, nonatomic) IBOutlet UIView *containerButton;

@end

.m
@implementation MyCell

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self initialize];
    }
    return self;
}

- (void)initialize
{
    UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)];
    [panGestureRecognizer setDelegate:self];

    if (self.containerButton) {
        NSLog(@"ok"); //not enter here
        [self.containerButton addGestureRecognizer:panGestureRecognizer];
    }
}

-(void)prepareForReuse {
    [super prepareForReuse];
    if (self.containerButton) {
        NSLog(@"ok 2");
    }
}

I have created the UICollectionViewCell subclass connected with the xib file, where I have created the container button view, if I try to add the gesture in the initialize method, the containerButton is nil, so doesn't work, but in the prepareForReuse method is not empty, I can add the gesture there? or I can do it in other place?

A: Try this:
- (void)awakeFromNib
{
    UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)];
    [panGestureRecognizer setDelegate:self];

    if (self.containerButton) {
        NSLog(@"ok"); //not enter here
        [self.containerButton addGestureRecognizer:panGestureRecognizer];
    }
}


text:
Q: What does "this" word do in jQuery? So, here is the question
I can not undestand when i should use "this" instead class or id
If u can show example - it will be fantastic
Thanks

A:
I can not undestand when i should use "this" instead class or id

Usually, you do that when you want to refer to the element on which an event was triggered from within the event handler:
$(".foo").on("click", function() {
    var $el = $(this);           // `this` is the element that was clicked,
                                 // so `$(this)` gives you a jQuery wrapper
                                 // around just that one element.
                                 // But $(".foo") would give you a wrapper
                                 // around **all** .foo elements, not just the
                                 // one that was clicked.
    // ...
});

Live Example:

$(".foo").on("click", function() {
  var $el = $(this); // `this` is the element that was clicked
  $el.text("You've clicked this one");
});

Not clicked yet

Not clicked yet

Not clicked yet

Not clicked yet

Not clicked yet

Not clicked yet

Not clicked yet

Not clicked yet

Sometimes, it comes up when using either each or $.each, because jQuery calls the callback to each of those methods with this referring to the element for that call:
$(".foo").each(function() {
    var $el = $(this);               // `this` is the element for this callback
    // ...
});

The jQuery API documentation will tell you when it's going to set this to a specific value in a callback.


text:
Q: Loading sql dump into oracle database I had sqlite database which contained nearly 100k entries. SQL features of sqlite turned out to be insufficient for my needs, so i decided to move the whole db to oracle. The only problem is - i have sql dump file, 150mb, and i cant load it into oracle - i just dont know how.
I tried to use oracle's web-based control panel, but it cant upload file as it's too big.
Seems like tools like SQL*Loader work only with data files, but i already have complete sql dump and i wonder how to feed it to Oracle XE.
What shud i do?

A: If the dump file is indeed a list of SQL squeries, just run it at a SQL*Plus prompt.
prompt> cd my\dump\script\dir
prompt> sqlplus /

Connected to:
Personal Oracle Database 11g Release 11.2.0.1.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

sql> @dumpscript.sql

Alternatively, open the script in SQL Developer (or equivalent, i.e. TOAD, SquirrelSQL) and run it from there.


text:
Q: Excel - The most spending occurred around this date I feel like as a human I can understand this, but I can't figure out how to get it into an Excel formula.
Given the dates and amounts spent on those dates below, how can I find a date on which the most spending occurred around? Sort of like a "heat map."
Date        Spending
01/01/22    1000.00
02/02/22    523.25
04/01/22    2015.35
04/15/22    1258.62
04/18/22    3025.35
06/23/22    152.35
07/22/22    852.36

Looking at it, I can assume the majority of the total spending happened around 04/16/22 due to the three close April dates with higher amounts.
I can't figure out a formula to calculate that.

A: Based on your description the result should be 4/18/2022.
If my understanding is correct, try this formula:
=INDEX($A$2:$A$8,MATCH(MAX($B$2:$B$8),$B$2:$B$8,0))


text:
Q: Trying to build server side datatable from pdo query I have to build a data table from server side because I have more than 200k rows, and I don't have the choice I need to make it from an execute statement like:
$result['draw']=1;
$temp = BD::query('SELECT * FROM `ersmessages` WHERE 1 LIMIT 10');
$result['recordsTotal'] = sizeof($temp);
$result['recordsFiltered'] = sizeof($temp);
$result['data'] = $temp;

But when I'm doing this that does not page my results and for 200k rows it's giving an error. If I limit the query that works but on one page.
My JS looks like:
 $('#tableAllMessages').DataTable( {
        "processing": true,
        "serverSide": true,
        "paging": true,
        "searching": { "regex": true },
        "lengthMenu": [ [10, 25, 50, 100, -1], [10, 25, 50, 100, "All"] ],
        "pageLength": 10,
        "ajax": "req/getAllMessages.php"
    } );

How should I proceed to have a paged data table with 200k rows? I can't obviously use the ssp.

A: ok the problem has been solved, i needed to put the recordsTotal to my maximum(200k rows)  size and i needed to add an offset to the query, that way i am able to paginate my table.
$offset = $_REQUEST['start'];
$result['recordsTotal'] = 200000;
$query = BD::query('SELECT * FROM `ersmessages` WHERE 1 ORDER BY `idERSMessage` ASC LIMIT 10 OFFSET '.intval($offset))
$result['data'] = $query;
$result['draw']=$_REQUEST['draw'];


text:
Q: React onChange event does not fire The issue is onChange event does not fire in the input tag. I was using LinkedStateMixin to track input value before. Lately, I want to add onChange event to run some function then I removed LinkedStateMixin, but the onChange cannot fire. I tried to add e.stopPropagation() to setUsername(), but it is not working too. I tried other event such as onKeyDown, onClick, and ect. none of them can be fired. What is the problem?
var React = require('react');

var SessionActions = require('../../actions/session_actions');
var UserStore = require('../../stores/user_store');

var LogInForm = React.createClass({

  getInitialState: function() {
    return ({
      user: undefined,
      username: '',
      password: '',
    });
  },

  componentDidMount: function() {
    this.token = UserStore.addListener(this.updateUserStore);
  },

  componentWillUnmount: function() {
    this.token.remove();
  },

  updateUserStore: function() {
    this.setState({user: UserStore.all()});
    this.setState({username: ''});
    this.setState({password: ''});
  },

  setUsername: function(e) {
    console.log("Fired");
  },

  handleSubmit: function(e) {
    e.preventDefault();
    SessionActions.logIn({
      username: this.state.username,
      password: this.state.password
    });
    this.updateUserStore();
  },

  render: function() {
    return (

Log In

        <form onSubmit={this.handleSubmit}>
          <input onChange={this.setUsername} placeholder="Username" type="text"/>

          <input placeholder="Password" type="password"/>

          <input type="submit" value="Log In"/>
        </form>

    );
  }
});

module.exports = LogInForm;

A: I created this jsfiddle with the code you posted and, despite the obvious warnings, the onchange event is fired. So I guess there is something else wrong with your code.
Does the component even render? Could you provide a fiddle where it is not working so I can take a look?

A: Change the function name from setUsername to handleUsername.


text:
Q: Dimension of sub-spaces Given U,W Sub-spaces of linear space V.
1.If $dim(U \cap W)= dimU$ then $U \subseteq  W$
I tried to prove it like that: if $dim(U \cap W)= dimU$ then $(U \cap W)= U$
and  because $U \subseteq U \cap W$ and $W \subseteq U \cap W$,  $(U \cap W)= U$
then $U \subseteq W $ . But I know I'm pretty sure all wrong, hope you can direct me to the right solution.

A: It is clear that $(U \cap W)\subseteq U$. Now, you need prove $U\subseteq (U \cap W)$. To proceed, let $B=\{b_1,\dots,b_n\}$ is a basis of $U \cap W$ with $n$ is its dimension. We know that $B$ are linearly independent set and of course $B\subseteq U$. It follows that $B$ is also a basis for $U$. Now put any $u\in U$, then $u$ is a linear combination of elements in $B$ which is also in $U \cap W$ which says $U\subseteq (U \cap W)$.

A: You can prove it this way:
Since $\dim (U \cap W)=\dim U$, and $U\cap W \subset U$, then $U \cap W = U$ (Can you prove it? Just take a basis of $U\cap W$ and see that it's als o a basis of $U$). Therefore, since $U \cap W \subset W$, $U \subset W$.


text:
Q: Ubuntu 20.04 flickring when using Nvidia driver I have just installed Ubuntu 20.04 on my laptop [Omen 15 2020].
I use an external monitor.
When I placed the usb-stick with Ubuntu, I tried it out and everything worked Ok!
Upon finishing the installation I enrolled in MOK.
When I first started the computer, only the laptop monitor was detected. I checked and the used driver was the X.org driver. Afterwards, I changed to Nvidia 470  [My laptop has a NVIDIA GTX 1650 Ti]. When I rebooted the laptop I had the second monitor working but the laptop was like this:
laptop monitor
I am not able to use the laptop monitor.. I was able to circumvent the situation by making the external monitor a single display.
How can I fix this?

A: You need to install the nvidia-settings app. It is an app created by nvidia themselves, which reads in input from your system, takes additional input from the user in the form of preferences, and uses the data collected to  performs automatic configuration and adjustment of your setup. It almost always leaves your system in a state that lets you enjoy it without constantly having to tune and reconfigure it (which is usually the case when trying to manage multi-display Nvidia / Xorg (pre-Wayland) setups with xrandr.)
For installation and (some) usage instructions, see here.


text:
Q: Django: Get list of model fields? I've defined a User class which (ultimately) inherits from models.Model. I want to get a list of all the fields defined for this model. For example, phone_number = CharField(max_length=20). Basically, I want to retrieve anything that inherits from the Field class.
I thought I'd be able to retrieve these by taking advantage of inspect.getmembers(model), but the list it returns doesn't contain any of these fields. It looks like Django has already gotten a hold of the class and added all its magic attributes and stripped out what's actually been defined. So... how can I get these fields? They probably have a function for retrieving them for their own internal purposes?

A: The get_all_related_fields() method mentioned herein has been deprecated in 1.8. From now on it's get_fields().
>> from django.contrib.auth.models import User
>> User._meta.get_fields()

A: MyModel._meta.get_all_field_names() was deprecated several versions back and removed in Django 1.10.
Here's the backwards-compatible suggestion from the docs:
from itertools import chain

list(set(chain.from_iterable(
    (field.name, field.attname) if hasattr(field, 'attname') else (field.name,)
    for field in MyModel._meta.get_fields()
    # For complete backwards compatibility, you may want to exclude
    # GenericForeignKey from the results.
    if not (field.many_to_one and field.related_model is None)
)))

A: Just to add, I am using self object, this worked for me:
[f.name for f in self.model._meta.get_fields()]

A: At least with Django 1.9.9 -- the version I'm currently using --, note that .get_fields() actually also "considers" any foreign model as a field, which may be problematic. Say you have:
class Parent(models.Model):
    id = UUIDField(primary_key=True)

class Child(models.Model):
    parent = models.ForeignKey(Parent)

It follows that
>>> map(lambda field:field.name, Parent._model._meta.get_fields())
['id', 'child']

while, as shown by @Rockallite
>>> map(lambda field:field.name, Parent._model._meta.local_fields)
['id']

A: So before I found this post, I successfully found this to work.
Model._meta.fields

It works equally as
Model._meta.get_fields()

I'm not sure what the difference is in the results, if there is one. I ran this loop and got the same output.
for field in Model._meta.fields:
    print(field.name)

A: I find adding this to django models quite helpful:
def __iter__(self):
    for field_name in self._meta.get_all_field_names():
        value = getattr(self, field_name, None)
        yield (field_name, value)

This lets you do:
for field, val in object:
    print field, val

A: Django versions 1.8 and later:
You should use get_fields():
[f.name for f in MyModel._meta.get_fields()]

The get_all_field_names() method is deprecated starting from Django
1.8 and will be removed in 1.10.
The documentation page linked above provides a fully backwards-compatible implementation of get_all_field_names(), but for most purposes the previous example should work just fine.

Django versions before 1.8:
model._meta.get_all_field_names()

That should do the trick.
That requires an actual model instance. If all you have is a subclass of django.db.models.Model, then you should call myproject.myapp.models.MyModel._meta.get_all_field_names()

A: This does the trick. I only test it in Django 1.7.
your_fields = YourModel._meta.local_fields
your_field_names = [f.name for f in your_fields]

Model._meta.local_fields does not contain many-to-many fields. You should get them using Model._meta.local_many_to_many.

A: It is not clear whether you have an instance of the class or the class itself and trying to retrieve the fields, but either way, consider the following code
Using an instance
instance = User.objects.get(username="foo")
instance.__dict__ # returns a dictionary with all fields and their values
instance.__dict__.keys() # returns a dictionary with all fields
list(instance.__dict__.keys()) # returns list with all fields

Using a class
User._meta.__dict__.get("fields") # returns the fields

# to get the field names consider looping over the fields and calling __str__()
for field in User._meta.__dict__.get("fields"):
    field.__str__() # e.g. 'auth.User.id'

A: def __iter__(self):
    field_names = [f.name for f in self._meta.fields]
    for field_name in field_names:
        value = getattr(self, field_name, None)
        yield (field_name, value)

This worked for me in django==1.11.8

A: A detail not mentioned by others:
[f.name for f in MyModel._meta.get_fields()]

get, for example
['id', 'name', 'occupation']

and
[f.get_attname() for f in MyModel._meta.get_fields()]

get
['id', 'name', 'occupation_id']

If
reg = MyModel.objects.first()

then
reg.occupation

get, for example
<Occupation: Dev>

and
reg.occupation_id

get
1

A: As most of answers are outdated I'll try to update you on Django 2.2
Here posts- your app (posts, blog, shop, etc.)
1) From model link: https://docs.djangoproject.com/en/stable/ref/models/meta/
from posts.model import BlogPost

all_fields = BlogPost._meta.fields
#or
all_fields = BlogPost._meta.get_fields()

Note that:
all_fields=BlogPost._meta.get_fields()

Will also get some relationships, which, for ex: you can not display in a view.
As in my case:
Organisation._meta.fields
(<django.db.models.fields.AutoField: id>, <django.db.models.fields.DateField: created>...

and
Organisation._meta.get_fields()
(<ManyToOneRel: crm.activity>, <django.db.models.fields.AutoField: id>, <django.db.models.fields.DateField: created>...

2) From instance
from posts.model import BlogPost

bp = BlogPost()
all_fields = bp._meta.fields

3) From parent model
Let's suppose that we have Post as the parent model and you want to see all the fields in a list, and have the parent fields to be read-only in Edit mode.
from django.contrib import admin
from posts.model import BlogPost

@admin.register(BlogPost)
class BlogPost(admin.ModelAdmin):
    all_fields = [f.name for f in Organisation._meta.fields]
    parent_fields = BlogPost.get_deferred_fields(BlogPost)

    list_display = all_fields
    read_only = parent_fields

A:
In sometimes we need the db columns as well:

def get_db_field_names(instance):
   your_fields = instance._meta.local_fields
   db_field_names=[f.name+'_id' if f.related_model is not None else f.name  for f in your_fields]
   model_field_names = [f.name for f in your_fields]
   return db_field_names,model_field_names

Call the method to get the fields:
db_field_names,model_field_names=get_db_field_names(Mymodel)

A: Combined multiple answers of the given thread (thanks!) and came up with the following generic solution:
class ReadOnlyBaseModelAdmin(ModelAdmin):
    def has_add_permission(self, request):
        return request.user.is_superuser

    def has_delete_permission(self, request, obj=None):
        return request.user.is_superuser

    def get_readonly_fields(self, request, obj=None):
        return [f.name for f in self.model._meta.get_fields()]

A: Why not just use that:
manage.py inspectdb

Example output:
class GuardianUserobjectpermission(models.Model):
    id = models.IntegerField(primary_key=True)  # AutoField?
    object_pk = models.CharField(max_length=255)
    content_type = models.ForeignKey(DjangoContentType, models.DO_NOTHING)
    permission = models.ForeignKey(AuthPermission, models.DO_NOTHING)
    user = models.ForeignKey(CustomUsers, models.DO_NOTHING)

    class Meta:
        managed = False
        db_table = 'guardian_userobjectpermission'
        unique_together = (('user', 'permission', 'object_pk'),)


text:
Q: returns x with the n bits that begin at position p set to the rightmost n bits of y, leaving other bits unchanged my solution
get the rightmost n bits of y
a = ~(~0 << n) & y

clean the n bits of x beginning from p
c = ( ~0 << p | ~(~0 << (p-n+1))) & x

set the cleaned n bits to the n rightmost bits of y
c | (a << (p-n+1))

it is rather long statements. do we have a better one?
 i.e
x = 0 1 1 1 0 1 1 0 1 1 1 0
p = 4
y = 0 1 0 1 1 0 1 0 1 0
n = 3

the 3 rightmost bits of y is 0 1 0
it will replace x from bits 4 to bits 2 which is 1 1 1

A: I wrote similar one:
 unsigned setbits (unsigned x, int p, int n, unsigned y)
{
  return (x & ~(~(~0<<n)<<(p+1-n)))|((y & ~(~0<<n))<<(p+1-n));
}

A: There are two reasonable approaches.
One is yours:  Grab the low n bits of y, nuke the middle n bits of x, and "or" them into place.
The other is to build the answer from three parts:  Low bits "or" middle bits "or" high bits.
I think I actually like your version better, because I bet n and p are more likely to be compile-time constants than x and y.  So your answer becomes two masking operations with constants and one "or"; I doubt you will do better.
I might modify it slightly to make it easier to read:
mask = (~0 << p | ~(~0 << (p-n+1)))
result = (mask & a) | (~mask & (y << (p-n+1)))

...but this is the same speed (indeed, code) as yours when mask is a constant, and quite possibly slower when mask is a variable.
Finally, make sure you have a good reason to worry about this in the first place.  Clean code is good, but for something this short, put it in a well-documented function and it does not matter that much.  Fast code is good, but do not attempt to micro-optimize something like this until your profiler tells you do.  (Modern CPUs do this stuff very fast; it is unlikely your application's performance is bounded by this sort of function.  At the very least it is "innocent until proven guilty".)

A: Have a look at the following descriptive code:
int setbitsKR(int x, int p, int n, int y){
    int shiftingDistance = p - n + 1,
        bitmask = (1 << n) - 1, // example, 11
        digitsOfY = (y & bitmask) << shiftingDistance, // whatever
        bitmaskShiftedToLeft = bitmask << shiftingDistance, // 001100
        invertedBitmaskShiftedToLeft = ~bitmaskShiftedToLeft; // 110011

    // erase those middle bits of x
    x &= invertedBitmaskShiftedToLeft;

    // add those bits from y into x
    x |= digitsOfY;

    return x;
}

In short, it creates a bitmask (string of 1s), shifts them to get to that middle position of x, nukes those bits of x by &ing with a string of 0s (inverted bitmask), and finally |s that position with the right digits of y.


text:
Q: How to stop a MutationObserver observing a single target? To move this old mutation event jQuery code
$('#container .class').on('DOMNodeInserted.mynamespace', 'input[type="number"]', function (e) {
  ...
  $(this).closest('#container .class').off('DOMNodeInserted.mynamespace');
});

to MutationObserver, I have to add the observer to multiple elements at once:
var observer = new MutationObserver(function (mutations, observer) {
  ...
});
var config = {
  subtree: true,
  childList: true
};
$("#container .class").each(function () {
  observer.observe(this, config);
});

But how can I similarly remove the observer from a single element at a time (after the first time the event/observer runs successfully) to retain the behaviour of the pre-MutationObserver version?


text:
Q: MongoDB Java get Schema of existing collection using aggregation I am looking for solutions to get field name and type for all nested fields including array of documents using $project $mergeobjects, $objectToArray , $unwind.
collection.aggregate(Arrays.asList(
                new Document("$limit",100),
                new Document("$project", new Document("fields", new Document("$objectToArray", "$ROOT" ))),
                new Document("$unwind", "$fields"),
                new Document("$project", new Document("fields", new Document("k", "$fields.k").append("v",new Document("$type", "$fields.v")))),
                new Document("$group", new Document("_id", "$fields.k").append("fields", new Document("$first", "$fields"))),
                new Document("$group", new Document("_id", null).append("fields", new Document("$push", "$fields"))),
                new Document("$project", new Document("fields", new Document("$arrayToObject", "$fields" )))
                ));

I have tried implementing but could not process array of documents yet. I am trying to learn how to use $mergeObjects to achieve the output


text:
Q: How to fix SQL Server Management Studio 2014 IntelliSense when intermittent Our remote SQL Server was recently upgraded to 2014. I installed SQL Server Management Studio 2014 on my Windows 10 client computer.
At first, everything seemed to be going great, until I noticed that IntelliSense is intermittent. By "intermittent" I mean that on the same computer, while working on the same script, IntelliSense might appear some times and not appear at other times. Before the upgrade to 2014, this never happened. Now it happens all the time.
Here's a specific example. Suppose I'm typing SELECT DISTINCT * from dbo. The moment I type the period, I expect IntelliSense to list the available tables, as it always does. So by intermittent I mean that sometimes I see the list of tables, and sometimes I don't.  This just a specific example of how the symptom manifests. This is not restrictive to table names. I mean that whenever I expect Intellisense to appear,  it doesn't always appear.
I checked the obvious: Troubleshooting IntelliSense (SQL Server Management Studio) reconfirmed what I already knew and didn't help. I've tried these things.

*

*Closing the remote database connection and reconnecting

*Refreshing the IntelliSense cache, both by Ctrl-R and through the menu Edit > IntelliSense > Refresh Local Cache

*Making sure all Windows Updates were applied

*Checking server connectivity with Ping (average 9 milliseconds)

This is not a duplicate because while other forum posts list the above steps as "answers" they are not answers for me. They do not solve the problem of intermittent IntelliSense.
Is there anything else i can do to fix this problem?

A: If possible, I'd suggest trying SSMS 2016 instead. It's still supported to use it against SQL Server 2014 (in fact, it's supported to use it against instances as old as SQL Server 2008). With 2016, SSMS is now free, and the installer for it is separate from the installer for the SQL Server server components (Database Engine, Integration Services, etc.). Plus, Microsoft is now releasing updates and improvements for it on a roughly monthly basis.
You can download SSMS 2016 from https://msdn.microsoft.com/en-us/library/mt238290.aspx.
I've personally found IntelliSense to work more reliably with SSMS 2016 than what I was used to with 2014, especially when working over slower or less reliable network connections.

A: This doesn't fix all intellisense problems, but if the database schema changes you can force it to stay up to date by going to Edit > IntelliSense > Refresh Local Cache (Ctrl+Shift+R is the corresponding shortcut).


text:
Q: apt-get does not always ask for confirmation I have noticed that when installing software through sudo apt-get install <packagename> it does not always give me the:
Do you want to continue? [Y/n]

Why is this so? I don't think that this has got anything to do with the size of the package as it has sometimes prompted me for a really small package, and then has not for a really large one.

OS Information:
Description:    Ubuntu 14.10
Release:    14.10

Package Information:
apt:
  Installed: 1.0.9.2ubuntu2
  Candidate: 1.0.9.2ubuntu2
  Version table:
 *** 1.0.9.2ubuntu2 0
        500 http://gb.archive.ubuntu.com/ubuntu/ utopic/main amd64 Packages
        100 /var/lib/dpkg/status


text:
Q: Interpreting estimates from generalized models in R I'm using R to run some generalized linear models (GLM) and I want to interpret the estimates.
If I use a GLM assuming Gaussian distribution with identity link, interpretation is easy: if the estimate for factor $x$ is $y$ then an increase of 1 of factor $x$ (if all other factors remain constant) will be estimated to result in a change in the response variable by $y$ units.
Now, if I run a GLM assuming Poisson distribution with log link, in the example above, will the response variable be expected to change by $y$ units, or by $\exp(y)$ units?
note: I'm getting the estimates from summary(model object)

A: For a unit change in $x$ you expect the response to change by a factor of $\exp(y)$. So say $\exp(y)=1.5$, then a unit change in $x$ is associated with a $(1.5-1)\times 100\% = 50\%$ increase in the response.


text:
Q: To give less weight-age to repetitive words in result of Full Text Search I have implemented Full Text Search on one of Sql Server 2008 Table. I am using containstable query to get the result and sorting it on the basis of Rank.
Example
SELECT Ad_text.*, k.rank
FROM Ad_text
INNER JOIN CONTAINSTABLE(Ad_text, text, 'Wanted or Engineers or bride') k
ON Ad_text.id = k.[KEY] order by rank desc

Now when query returns result, it  rank those rows higher which have high number of frequency of any of these words where as i want those rows to be ranked higher which has all these words.
Like  query will return result in this way

*

*Wanted Wanted Wanted Groom (Rank 200)

*Wanted Engineers For (Rank 180)

*Wanted Bride for Engineers Rank(190)

where as i want third one to be ranked higher. Is there is any to tell containstable that not increase weight for repetitive text.

A: Found a workaround has used FreeTextSearch with its number of records feature. It solve the purpose

A: Most of the search engine oriended sites are use FULL-TEXT-SEARCH.
    It will be very faster compare to select and LIKE...
    I have added one example and some links ...
    I think it will be useful for you...
    In this full text search have some conditions also...
STEP:1
CREATE TABLE articles (
    id INT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY,
    title VARCHAR(200),
    body TEXT,
    FULLTEXT (title,body)
);

STEP:2
INSERT INTO articles (title,body) VALUES
    ('MySQL Tutorial','DBMS stands for DataBase ...'),
    ('How To Use MySQL Well','After you went through a ...'),
    ('Optimizing MySQL','In this tutorial we will show ...'),
    ('1001 MySQL Tricks','1. Never run mysqld as root. 2. ...'),
    ('MySQL vs. YourSQL','In the following database comparison ...'),
    ('MySQL Security','When configured properly, MySQL ...');

STEP:3
Natural Language Full-Text Searches:
SELECT * FROM articles
    WHERE MATCH (title,body) AGAINST ('database');

Boolean Full-Text Searches
SELECT * FROM articles WHERE MATCH (title,body)
     AGAINST ('+MySQL -YourSQL' IN BOOLEAN MODE);

Go through this links
viralpatel.net,devzone.zend.com,sqlmag.com,colorado.edu,en.wikipedia.org


text:
Q: Explode php array and store variable value to DB Transaction initiated for payment and Got the revert form a transaction and want to display result on page ans save to my DB
    if (!($data = curl_exec($ch))) {
        return ERROR;
    }
    curl_close($ch);
    unset($ch);
    print "\n$data\n";
    $data = explode("&",$data);
    for($i=0;$i<count($data);$i++) {
        $rdata = explode("=",$data[$i]);
        $this->responses[$rdata[0]] = $rdata[1];
    }
    return $this->responses['response'];
  }

Result
response=1&responsetext=SUCCESS&authcode=123456&transactionid=2766128623&avsresponse=N&cvvresponse=M&orderid=1123400&type=sale&response_code=100

now i want to display each items on page like
Responce = 1
Responce Text = Success

A: it is called query string. You can do
parse_str ('response=1&responsetext=SUCCESS&authcode=123456&transactionid=2766128623&avsresponse=N&cvvresponse=M&orderid=1123400&type=sale&response_code=100', $resp);
print_r($resp);

and give the result array
Array
(
    [response] => 1
    [responsetext] => SUCCESS
    [authcode] => 123456
    [transactionid] => 2766128623
    [avsresponse] => N
    [cvvresponse] => M
    [orderid] => 1123400
    [type] => sale
    [response_code] => 100
)

Or don't say the 2nd argument, and then you will give variables with names as array keys

A: Do it normally as follows -
$data = "response=1&responsetext=SUCCESS&authcode=123456&transactionid=2766128623&avsresponse=N&cvvresponse=M&orderid=1123400&type=sale&response_code=100";

$data = explode("&",$data);

// use print_r if needed
//print_r($data);

foreach($data as $d) {
  echo $d .'<br/>';
}

And For Key/ Label you have to do some pregmatch trick to achieve something like -
Response Text or Response or Auth Code

A: you can try str_replace() for replacing '&' with ' ', and you can use ucwords() for capitalization
like this
ucwords(str_replace('&',$this->responses['response'];))


text:
Q: ModalDialog created in a function closes in a flash at second / fourth / sixth etc. call I am building a big and (for me) complicated r shiny app where I am allowing people to categorize a long list of texts.
Whenever they want to add a previously non-existent label to a category, a modalDialog pops up. Not important now what all needs to be done in that dialog. That is under control. (I want to thank the entire Stackoverflow community: with the help of questions and answers posted earlier I pieced together my solution - this is an awesome platform).
However, here is the problem: first text that gets a new category, the modalDialog pops up, allows for all the necessary actions and performs what is needed when the 'save' button is hit. Same for the cancel button.
Then the second time the modalDialog should be called, it briefly appears, but then immediately closes of its own accord (via the same event as was used to close the dialog the first time). The third time everything is fine again. The fourth time I get the flash-situation, etc. Also, the amount of times that that closing event is executed increases with each trial?
I reproduced the situation in the simplified code below. Click on Button 1, it opens and shows the appropriate information. Click on Save, it closes (and shows the debugging message just once). Click on Button 2: flash! (and two times the debugging message). Click on Button 2 again (or 1, whatever): all is fine.
I tried making the code in the observeEvents conditional. I tried passing the session to the removeModal-function. Did not work. Tried using modalButtons instead of actionButtons, but they don't have an id and then I cannot catch the click. And save and cancel should not just close the modal.They need to execute some code (in the real version) so i need to be able to distinguish between them.
Could someone give me a hint? It would be so much appreciated! This code gets itself in a loop somehow and would like to get it out of there.
library(shiny)

ui <- (fluidPage(
  actionButton(inputId = "button1", label = "Button 1"),
  actionButton(inputId = "button2", label = "Button 2")
))

server <- function(session, input, output) {
  observeEvent(input$button1, {
    session = session
    modalId = 'newLabel'
    label = "button1"
    text = "This is text 1"
    myToggleModal(session, modalId, label, text)
  })

  observeEvent(input$button2, {
    session = session
    modalId = 'newLabel'
    label = "button2"
    text = "This is text 2"
    myToggleModal(session, modalId, label, text)
  })

  myToggleModal <- function(session, modalId, label, text){
    varLabel <- label
    varText <- text

    showModal(
      tagList(
        modalDialog(
          title = '',
          htmlOutput(outputId = "output1"),
          hr(),
          htmlOutput("output2"),
          br(),br(),
          footer = tagList(
            actionButton("cancel", "Cancel"),
            actionButton("save", "Save")
          )
        )
      )
    )

    output$output1 <- renderUI({
      varLabel
    })

    output$output2 <- renderUI({ # display the marked-up text
      text
    })

    observeEvent(input$save,{
      ##do something

      #print the debugging message
      print("you are passing the save event")
      removeModal()
    })

    observeEvent(input$cancel,{
      ##don't do that something

      #print the debugging message
      print("you are passing the cancel event")
      removeModal()
    })
  }
}

shinyApp(ui, server)

A: Here is part of the answer: I should have identified the namespace for the actionbuttons in the module. I adapted using modal window in Shiny module for my code and that works.
Still need to find a new way to pass information to the module now, but that was not pertinent to this particular question.
modalModuleUI <- function(id, label) {
  ns <- NS(id)
  actionButton(ns(label), gsub(pattern = "button", x = label, replacement = "Button "))
}

modalModule <- function(input, output, session) {

  myModal <- function() {
    ns <- session$ns
      modalDialog(
        title = '',
        htmlOutput(outputId = ns("output1")),
        hr(),
        htmlOutput(ns("output2")),
        br(),br(),
        footer = tagList(
          actionButton(ns("cancel"), "Cancel"),
          actionButton(ns("save"), "Save")
        )
      )
  }

  # open modal on button click
  observeEvent(input$button1,
               ignoreNULL = TRUE, {
                 showModal(myModal())
               }
  )

  observeEvent(input$button2,
               ignoreNULL = TRUE, {
                 showModal(myModal())
               }
  )

  # close modal on button click
  observeEvent(input$save, {
    print("save")
    removeModal()
  })

  observeEvent(input$cancel, {
    print("cancel")
    removeModal()
  })
}

ui <- fluidPage(
  modalModuleUI("foo", "button1"),
  modalModuleUI("foo", "button2")
  )

server <- function(input, output, session) {
  callModule(modalModule, "foo")
}

shinyApp(ui, server)


text:
Q: Login failed for user ''. error I know that this is a duplicate post but I couldn't find my solution on that topics. I want to connect my sql file in debug folder but I got error that Login failed for user ''.
    Dim connectionString As String = String.Format("Data Source=.\SQLEXPRESS;AttachDbFilename={0}\Word.mdf;Integrated Security=False;Connect Timeout=30;User Instance=True", My.Application.Info.DirectoryPath)

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Dim sql As String = "SELECT * FROM test"
    Dim connection As New SqlConnection(connectionString)
    Dim dataadapter As New SqlDataAdapter(sql, connection)
    Dim ds As New DataSet()
    connection.Open()
    dataadapter.Fill(ds, "test_table")
    connection.Close()
    DataGridView1.DataSource = ds
    DataGridView1.DataMember = "test_table"
    MakePivot()
    connection.Close()
    DataGridView2.ClearSelection()

End Sub

Could you tell me my mistake please?

A:  Dim ds As New DataSet()
 Using connection As New SqlConnection(String.Format("Data Source=.\SQLEXPRESS;AttachDbFilename={0}\Word.mdf;Integrated Security=true;Connect Timeout=30;User Instance=True", My.Application.Info.DirectoryPath))
       connection.Open()
       Using command As New SqlCommand("SELECT * FROM test", connection)
             command.CommandTimeout = 0
             Using da As New SqlDataAdapter(command)
                   da.Fill(ds)
             End Using
       End Using
 End Using

 DataGridView1.DataSource = ds
 MakePivot()
 DataGridView2.ClearSelection()

Try this code, need to set "integrated security=true"


text:
Q: Python3: How to dynamically reference the name of a dictionary I'm still learning python and I'd appreciate any direction for the problem that I'm having.
I have menu options set up in two separate dictionaries in the following structure
menu0000 = {
    1 : {
        "label" : "Library"
    },

    2 : {
        "label" : "Listen Now"
    }
}

menu0001 = {
    1 : {
        "label" : "Shuffle Songs"
    },

    2 : {
        "label" : "Playlists"
    }

}

A variable has been set up to keep track of the name of which dictionary I am currently accessing
menuName = "menu0000"

Without hard-coding the name, I'd like to access the dictionary dynamically based on the contents of the menuName variable, eg:
for key in menuName:
    print(menuName[key]["label"])

How do I call menuName in a way that invokes a dictionary? The idea is to update menuName at a later stage so that I can access different dictionaries.


text:
Q: How to escape a URL for Elasticsearch? In one of my fields in Elasticsearch I'm storing the URL of my documents (e.g. http://techcrunch.com/something-great)
When I don't escape the URL, the document is found correctly - but I get the EOF error on some URLs.
When I escape the URL with:
String escapedString = QueryParser.escape(e.getKey().getUrl());

The document is not found - I get zero hits.
So how to do it?

    {
    _index: "crawlbot",
    _type: "article",
    _id: "AVFaaFu4w49jUzVInKS5",
    _score: 1,
    _source: {
        job: {
            id: 65,
            name: "wikipedia_en",
            max_pages: 300000,
            crawl_depth: 0,
            processing_patterns: "-Category,-User,-Wikipedia:,-Topic,-Special:,-Talk:,-Portal:,-MOS",
            status: 0,
            days: 0,
            url: [
                "https://en.wikipedia.org"
            ],
            ajax: false,
            min_description: 0
        },
        article: {
            url: "https://en.wikipedia.org/w/index.php?action=history&feed=atom&title=Parliament_of_Romania",
            provider_url: "https://en.wikipedia.org",
            provider_name: "",
            provider_display: "en.wikipedia.org",
            favicon_url: "http://www.google.com/s2/u/0/favicons?domain=https://en.wikipedia.org",
            language: "en",
            metadata: {
                authors: []
            },
            entities: [],
            keywords: [],
            videos: [],
            unfilteredKeywords: [],
            published: "",
            published_long: 0
        }
    }
}

And i would like the to retrieve the document per article.url
This is the query:
 SearchRequestBuilder requestBuilder = client.prepareSearch("crawlbot").setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
            BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
            String escapedString = QueryParser.escape(e.getKey().getUrl());
            queryBuilder.must(QueryBuilders.queryStringQuery(escapedString).defaultField("article.url"));
            queryBuilder.must(QueryBuilders.queryStringQuery(e.getKey().getJob().getId() + "").defaultField("job.id"));

Error if i don't escape:
Exception in thread "main" org.elasticsearch.action.search.SearchPhaseExecutionException: Failed to execute phase [query], all shards failed; shardFailures {[9_T8APppReyWKppSNZWmXw][crawlbot][0]: SearchParseException[[crawlbot][0]: from[-1],size[-1]: Parse Failure [Failed to parse source [{"query":{"bool":{"must":[{"query_string":{"query":"http://www.zeit.de/wirtschaft/2015-11/griechenland-reparationszahlung-bayern-rentner-jahresrueckblick-2?page=4","default_field":"article.url"}},{"query_string":{"query":"70","default_field":"job.id"}}]}}}]]]; nested: QueryParsingException[[crawlbot] Failed to parse query [http://www.zeit.de/wirtschaft/2015-11/griechenland-reparationszahlung-bayern-rentner-jahresrueckblick-2?page=4]]; nested: ParseException[Cannot parse 'http://www.zeit.de/wirtschaft/2015-11/griechenland-reparationszahlung-bayern-rentner-jahresrueckblick-2?page=4': Lexical error at line 1, column 111.  Encountered: <EOF> after : "/griechenland-reparationszahlung-bayern-rentner-jahresrueckblick-2?page=4"]; nested: TokenMgrError[Lexical error at line 1, column 111.  Encountered: <EOF> after : "/griechenland-reparationszahlung-bayern-rentner-jahresrueckblick-2?page=4"]; }{[9_T8APppReyWKppSNZWmXw][crawlbot][1]: SearchParseException[[crawlbot][1]: from[-1],size[-1]: Parse Failure [Failed to parse source [{"query":{"bool":{"must":[{"query_string":{"query":"http://www.zeit.de/wirtschaft/2015-11/griechenland-reparationszahlung-bayern-rentner-jahresrueckblick-2?page=4","default_field":"article.url"}},{"query_string":{"query":"70","default_field":"job.id"}}]}}}]]]; nested: QueryParsingException[[crawlbot] Failed to parse query [http://www.zeit.de/wirtschaft/2015-11/griechenland-reparationszahlung-bayern-rentner-jahresrueckblick-2?page=4]]; nested: ParseException[Cannot parse 'http://www.zeit.de/wirtschaft/2015-11/griechenland-reparationszahlung-bayern-rentner-jahresrueckblick-2?page=4': Lexical error at line 1, column 111.  Encountered: <EOF> after : "/griechenland-reparationszahlung-bayern-rentner-jahresrueckblick-2?page=4"]; nested: TokenMgrError[Lexical error at line 1, column 111.  Encountered: <EOF> after : "/griechenland-reparationszahlung-bayern-rentner-jahresrueckblick-2?page=4"]; }{[9_T8APppReyWKppSNZWmXw][crawlbot][2]: SearchParseException[[crawlbot][2]: from[-1],size[-1]: Parse Failure [Failed to parse source [{"query":{"bool":{"must":[{"query_string":{"query":"http://www.zeit.de/wirtschaft/2015-11/griechenland-reparationszahlung-bayern-rentner-jahresrueckblick-2?page=4","default_field":"article.url"}},{"query_string":{"query":"70","default_field":"job.id"}}]}}}]]]; nested: QueryParsingException[[crawlbot] Failed to parse query [http://www.zeit.de/wirtschaft/2015-11/griechenland-reparationszahlung-bayern-rentner-jahresrueckblick-2?page=4]]; nested: ParseException[Cannot parse 'http://www.zeit.de/wirtschaft/2015-11/griechenland-reparationszahlung-bayern-rentner-jahresrueckblick-2?page=4': Lexical error at line 1, column 111.  Encountered: <EOF> after : "/griechenland-reparationszahlung-bayern-rentner-jahresrueckblick-2?page=4"]; nested: TokenMgrError[Lexical error at line 1, column 111.  Encountered: <EOF> after : "/griechenland-reparationszahlung-bayern-rentner-jahresrueckblick-2?page=4"]; }{[9_T8APppReyWKppSNZWmXw][crawlbot][3]: SearchParseException[[crawlbot][3]: from[-1],size[-1]: Parse Failure [Failed to parse source [{"query":{"bool":{"must":[{"query_string":{"query":"http://www.zeit.de/wirtschaft/2015-11/griechenland-reparationszahlung-bayern-rentner-jahresrueckblick-2?page=4","default_field":"article.url"}},{"query_string":{"query":"70","default_field":"job.id"}}]}}}]]]; nested: QueryParsingException[[crawlbot] Failed to parse query [http://www.zeit.de/wirtschaft/2015-11/griechenland-reparationszahlung-bayern-rentner-jahresrueckblick-2?page=4]]; nested: ParseException[Cannot parse 'http://www.zeit.de/wirtschaft/2015-11/griechenland-reparationszahlung-bayern-rentner-jahresrueckblick-2?page=4': Lexical error at line 1, column 111.  Encountered: <EOF> after : "/griechenland-reparationszahlung-bayern-rentner-jahresrueckblick-2?page=4"]; nested: TokenMgrError[Lexical error at line 1, column 111.  Encountered: <EOF> after : "/griechenland-reparationszahlung-bayern-rentner-jahresrueckblick-2?page=4"]; }{[9_T8APppReyWKppSNZWmXw][crawlbot][4]: SearchParseException[[crawlbot][4]: from[-1],size[-1]: Parse Failure [Failed to parse source [{"query":{"bool":{"must":[{"query_string":{"query":"http://www.zeit.de/wirtschaft/2015-11/griechenland-reparationszahlung-bayern-rentner-jahresrueckblick-2?page=4","default_field":"article.url"}},{"query_string":{"query":"70","default_field":"job.id"}}]}}}]]]; nested: QueryParsingException[[crawlbot] Failed to parse query [http://www.zeit.de/wirtschaft/2015-11/griechenland-reparationszahlung-bayern-rentner-jahresrueckblick-2?page=4]]; nested: ParseException[Cannot parse 'http://www.zeit.de/wirtschaft/2015-11/griechenland-reparationszahlung-bayern-rentner-jahresrueckblick-2?page=4': Lexical error at line 1, column 111.  Encountered: <EOF> after : "/griechenland-reparationszahlung-bayern-rentner-jahresrueckblick-2?page=4"]; nested: TokenMgrError[Lexical error at line 1, column 111.  Encountered: <EOF> after : "/griechenland-reparationszahlung-bayern-rentner-jahresrueckblick-2?page=4"]; }
    at org.elasticsearch.action.search.type.TransportSearchTypeAction$BaseAsyncAction.onFirstPhaseResult(TransportSearchTypeAction.java:237)
    at org.elasticsearch.action.search.type.TransportSearchTypeAction$BaseAsyncAction$1.onFailure(TransportSearchTypeAction.java:183)
    at org.elasticsearch.search.action.SearchServiceTransportAction$23.run(SearchServiceTransportAction.java:565)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

A: I suggest you change the mapping of your article.url field to:
url: {
    "type": "string",
    "index": "not_analyzed"
}

Failing to do so will make your field analyzed and very hard to query given the way the standard analyzer will break up the URL into several tokens.
Then, instead of using a query_string query, you can use a term query in order to query your documents.
SearchRequestBuilder requestBuilder = client.prepareSearch("crawlbot").setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
queryBuilder.must(QueryBuilders.termQuery("article.url", e.getKey().getUrl()));
...                                 ^
                                    |
                        use a term query instead

UPDATE
Following up on Evaldas' comment (kudos Evaldas!), in the end the idea is to create a custom analyzer in order to make sure that the URL will be lowercased as well.
When creating your index, you can add a new analyzer in the settings and then use it as the analyzer of your article.url field:
PUT /crawlbot
{
    "settings": {
        "analysis": {
            "analyzer": {
                "url_analyzer": {
                    "type":         "custom",
                    "tokenizer":    "keyword",
                    "filter":       [ "lowercase" ]
                }
            }
        }
    },
    "mappings": {
        "article": {
            "properties": {
                "article": {
                    "url": {
                        "type": "string",
                        "analyzer": "url_analyzer"
                    }
                }
            }
        }
    }
}


text:
Q: Unable to download a PDF file - browser keep loading For some reasons, some of the PDF files on my website is unable to download through the browser.  When I copy the full path to the file on the Server and paste to the browser, the browser keep loading forever.  There's no error on the Server log / Apache log / PHP log
This problem is only happen to some of the PDF files, some of them are fine - I just click and download straightaway.
I also take the problem PDF files and upload to a different Server, and the same problem again.
I'm now thinking about the problem is something inside the PDF file but not the Server.
I did check the PDF file and see if there's any security that caused the problem but there's no security at all.
Did you guys ever come across a problem like this before?

A: I've found the problem was caused by our network, when I access from an outside network, I can download all PDF files without any issue.


text:
Q: MariaDB shows no results when I use INNER JOIN There are two tables. The IDs of Table B was created by Table A. ID. So, the IDs of both tables are identical.
This is my question and real table structures.
I have tried to merge two tables into one table, but the query shows no result.
This is my query.
SELECT A.ID, A.type, B.ID, B.result
FROM A
INNER JOIN B
ON A.ID = B.ID;

I don't know what I did wrong. I thought it is quite simple JOIN syntax.
Can you explain what I did wrong?

A: Dear titans of the stack overflow.
I've solved this problem.
I had tried to join the two tables using admno column.
It looked same, and the data types are same. but After checking the length of that data, I found out that there is something, an invisible byte in one column.
(The trim() function was not able to remove that byte)
I used char_length() function at each key column. It revealed that one is 14, and another is 15.
I don't know what is the invisible. But it worked!
Thank you all!


text:
Q: VS2015 inside ESXi VM / no SLAT available? I've set up a Windows 10 VM on my ESXi 6 machine and installed VS2015 in order to develop Windows Phone / Android apps. As the device emulator is build around   HyperV, I've added the following lines to my VMX files:
monitor.virtual_exec = "hardware"
vhv.enable = "TRUE"
hypervisor.cpuid.v0 = "FALSE"

The Guest OS is set to either "Windows 10 64-bit" or "Windows Server Threshold (64-bit)". But if I'm trying to run a debug session, VS complains about missing SLAT support. My host CPU definitely supports SLAT (Xeon E5-v3) and it is enabled in the BIOS. If I query the vSphere host capabilities, it clearly states that "NestedHV" is available.
I can even launch the HV Management application and start the debugging target manually... but it seems that VS2015 won't connect to it and still complains about missing SLAT support.
Is there anything I can try?

A: Has the same issue.
Found out, that enabling of Hyper-V disables SLAT.


text:
Q: Modify variable just in the Django admin but not in database I want to modify a single value when I open an instance of a model in the Django admin.
Basically I want to display a value that is the opposite of the one stored in the database. So here is what I did in admin.py :
class MyModelAdminForm(forms.ModelForm):
    import_file = forms.FileField(required=False)

    class Meta:
        model = MyModel

    def __init__(self, *args, **kwargs):
        super(MyModelAdminForm, self).__init__(*args, **kwargs)
        print(self.instance.value)
        self.instance.value = self.instance.get_reverted_value()
        print(self.instance.value)

I works I can see it with the prints, but the admin still displays the original value that is stored in database.
Any idea ?
Thanks in advance

A: What about:
def __init__(self, *args, **kwargs):
    super(MyModelAdminForm, self).__init__(*args, **kwargs)
    self.fields['value'].value = self.instance.get_reverted_value()


text:
Q: Trying to pass a random string to SHA in Haskell I'm trying to pass a random string (which happens to be a number) "4176730.5" to SHA in Haskell to get a larger random string like "2d711642b726b04401627ca9fbac32f5c8530fb1903cc4db02258717921a4881".
I have this code to generate a random number and cast it to a string
  num <- randomIO :: IO Float

  let x = C.pack (show (num*10000000))

  print x

but when I pass it to SHA with
  let a = sha256 x

I get the error
Couldn't match expected type 'Data.ByteString.Lazy.Internal.ByteString'
            with actual type 'C.ByteString'

I've tried casting my number to C.ByteString, but I think there are two types of Bytestring, according to the Haskell compiler.
The full code is:
import Data.Digest.Pure.SHA
import System.Random
import qualified Data.ByteString.Char8 as C

main :: IO ()

main = do
  num <- randomIO :: IO Float

  let x = C.pack (show (num*10000000))

  print x

  let a = sha256 x

      b = hmacSha256 "key" "some test message"
  mapM_ print [showDigest a, showDigest b]

Seeing as how there are apparently two types of Bytestring, and I'm casting to the wrong one, how do I cast my random string correctly?
Further to @Cubic's answer below if I replace
    import qualified Data.ByteString.Char8 as C
with
import qualified Data.ByteString.Lazy as C

I just get these errors
Couldn't match type 'Char' with 'GHC.Word.Word8'
Expected type: [GHC.Word.Word8]
  Actual type: String

and
Couldn't match expected type 'C.ByteString'
            with actual type '[Char]'

A: The issue is that a ByteString is a sequence of bytes, while a String is a sequence of chars. There are many ways to turn chars into bytes, so you need to specify which encoding you want. Most likely, you want an ASCII or UTF8 encoding. If so, you can use this solution below, which converts strings into "UTF8 bytes" as needed.
import Data.Digest.Pure.SHA
import System.Random
import qualified Data.ByteString.Lazy as C
import qualified Data.ByteString.Lazy.UTF8 as U

main :: IO ()

main = do
  num <- randomIO :: IO Float

  let x = U.fromString (show (num*10000000))

  print x

  let a = sha256 x

      b = hmacSha256 (U.fromString "key") (U.fromString "some test message")
  mapM_ print [showDigest a, showDigest b]

A: You need Data.ByteString.Lazy, not Data.ByteString.Char8.
In general, you almost never want Data.ByteString.Char8.

A: Just use the lazy bytestrings as @leftaroundabout mentioned.  Your try didn't work because you want to pack from Strings, so you need to import the .Char8 module to achieve that:
import Data.ByteString.Lazy.Char8 as C


text:
Q: Getting Current Item of Higher Scope While Loop I have a nested switch statement inside a switch statement. I am wondering if it is possible to grab the un-nested current item within the scope of the nested switch statement. I know I can accomplish this with a for loop with moderate difficulty but I am hoping there is some elegance I am missing to accomplishing this with switch statements. Below I am try to build some argument processing for one of my scripts.
# Process Args
$currentArg
$recurseOn = $false

:ListArgs switch -regex ($args)
{
    "-ou?" { $currentArg = "Organizational Unit"; write-host "Noticed ou switch"}
    "-li?k?e?" { $currentArg = "Compare To"; write-host "Noticed like switch"}
    "^-re?c?u?r?s?e?$" { $recurseOn = $true; write-host "Recurse switched on..."}
    default {
        :CurrentSwitch switch ($currentArg)
        {
            "Organizational Unit" { $OU = $_.$_ ; write-host "OU changed to '$($OU)'..."}
            "Compare To" { $Match = $_.$_ ; write-host "Lookup changed to '$($Match)'..."}
        }
    }
}

I know the present model of $.$ does not work but I am looking for something that could refer to the current item. I am thinking I could have a filler variable that I just fill with the current item regardless of condition and use that within the scope, but maybe there is something more elegant. I have also tried labeling my switch statements and attempted 'ListArgs.$_' to no avail.
Any input would be much appreciated. Thanks in advance!
I did this after posting:
    # Process Args
$currentArg
$recurseOn = $false

:ListArgs switch -regex ($args)
{
    "-ou?" { $currentArg = "Organizational Unit"; write-host "Noticed ou switch"}
    "-li?k?e?" { $currentArg = "Compare To"; write-host "Noticed like switch"}
    "^-re?c?u?r?s?e?$" { $recurseOn = $true; write-host "Recurse switched on..."}
    default {
        $item = $_
        :CurrentSwitch switch ($currentArg)
        {
            "Organizational Unit" { $OU = $item; write-host "OU changed to '$($OU)'..."}
            "Compare To" { $Match = $item; write-host "Lookup changed to '$($Match)'..."}
        }
    }
}

And was able to get it working, but any input on $_ or loop labels would be appreciated. Or is there a better way to do arg processing in PowerShell?

A: I guess since there are no better suggestions out there for argument processing, I answered my own question.
    $item = $_

A:
I am thinking I could have a filler
  variable that I just fill with the
  current item regardless of condition
  and use that within the scope

Usually I do this and I do not know a better way. Thus, your code would be:
...
default {
    $filler = $_
    :CurrentSwitch switch ($currentArg)
    {
        "Organizational Unit" { use $filler in here }
        "Compare To" { use $filler in here }
    }
}


text:
Q: ASP.NET web application create txt file on users computer I have a asp.net c# web application. On one of the pages i have a button and when pressed I want it to create a text file with certain text and save it to the users PC. I do not want to save it on the server or anything.
I Currently have this which writes 'test' to a file:
string fileLoc = "filePath";
            FileStream fs = null;
            fs = File.Create(fileLoc);

            StreamWriter sw = new StreamWriter(fileLoc);
            sw.WriteLine("test");

            fs.Close();
            sw.Close();

How do I get it to save to the users computer.
Thanks for the help!.

A: ASP.NET run on the server. If you would like to work with the client's computer you'll do it in Java Script. I recommend you to use any open source project written in javascript like this one https://github.com/eligrey/FileSaver.js.

A: You have to return it trough an action method.
public ActionResult DownloadFile(){
 return File(filePath, "text/plain", "MyFileName");
}

You cannot explicitly save it to the users PC because you simply don't have access to that. Returning it as an ActionResult (more specifically: FileResult) will return it as a download.

A: You can't save the file directly in the client. You must write it into a Response, and then send it back to the client as a Download. There's a lot of ways, one of those include write the file stream directly into the Response like:
Response.ContentType = "text/plain";
Response.OutputStream.Write(buffer, 0, buffer.Length);
Response.AddHeader("Content-Disposition", "attachment;filename=yourfile.txt");

Reference: C# Asp.net write file to client


text:
Q: IE11 issue with Embedded PDF I have an HTML page that loads an embedded pdf on the page dynamically via an ajax call.
The below iframe code is pasted onto the Html page from the ajax method
<iframe src="${pdfpath}" width="1000" height="500">

It works well the first time it is called, however in subsequent calls there is an issue. The PDF loads fine, its the other contents on the page that disappears. This issue only happens in IE11, works fine in Chrome, Firefox and even IE9.
One thing odd I noticed is, when I open up the F12 developer tools, the remaining contents of the page appears again. Keep in mind that these contents have already been loaded the first time the page was loaded, the ajax method just inserts the iframe element onto the html page.
Below is a sample of how the ajax method inserts the data
$("#pdfDiv").empty().html(data);

Any help is appreciated on how to resolve this issue.
Thanks.

A: I was able to resolve this issue by replacing the iframe element with an object element
<object data="${pdfpath}" type="application/pdf">
       <embed src="${pdfpath}" type="application/pdf" />
</object>

Thanks.

A: Since internet explorer 11 came up, everyone seems to have troubles when wanting to display or download pdf files, and me too. Personnaly, i just stopped using pdf. But, here is something for you, i don't know if it will help :
http://answers.microsoft.com/en-us/ie/forum/ie11-windows_7/internet-explorer-11-windows-7-pdf-files-will-not/3882b9cb-05ff-45de-acc6-0f6b8b752ed6?auth=1


text:
Q: Is there a format to set thousand separator and also set two decimal places using Apache poi? I can either set thousand operator like this:
cell.getCellStyle().setDataFormat(HSSFDataFormat.getBuiltinFormat("#,#00"));

Or set two decimal places:
cell.getCellStyle().setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));

Is there an option to set both?

A: This worked for me:
cell.getCellStyle().setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00"));

Found solution based on @Fullslack.dev comment https://poi.apache.org/apidocs/dev/org/apache/poi/ss/usermodel/BuiltinFormats.html


text:
Q: Dynamically import a module How do I keep a import without restarting the program and manually doing it?
I have tried this:
class runProgram:
    def cmdEval(self,data):
        try:
            return str(repr(eval(data)))
        except Exception as e:
            return e
    def cmdImport(self,data):
        try:
            __import__(data)
            return "Imported."
        except:
                return "Error to import"
    def run(self):
        while True:
            command = input("Command: ")
            command,data = command.split(" ",1)
            if command == "ev": print(self.cmdEval(data))
            elif command == "imp": print(self.cmdImport(data))

Then I did the following:
>>> runProgram().run()
Command: imp time
Imported.
Command: ev time.time()
name 'time' is not defined

The result did not work, as I expected it not to but is their away to dynamically import without the use of saving the data? I mean I want to be able to use it but I don't want it their after I restart I just want to be able to have it there incase I need to import something for that particular session So for example this would be the desired results I want,
imp time
ev time.time()
>1383535034.20894
>>> ================================ RESTART ================================
>>> time.time()
Traceback (most recent call last):
  File "<pyshell#238>", line 1, in <module>
    time.time()
NameError: name 'time' is not defined

Is this possible?

A: __import__ returns the imported module, and does not change the global namespace.
Replace following line:
__import__(data)

with:
globals()[data] = __import__(data)