text:
Q: Hash computation in Google safe browsing V2 implementation I am trying to test my implementation of the google safe browsing api version 2.
To test a part of my code that sends requests for full hashes for a given prefix, I captured a short session of traffic where I visited a known currently blacklisted url "utfvq.portrelay.com" and firefox sent a request to google for full hashes and google responded with a list of hashes.
The prefixes firefox sent are(Hex encoded) : 2e2e372e,2e26382e,2e2e382e,6545382e
The 4 matching full hashes it received are :
2e26382e2e2e436d2e2e2e2e322e3b2e2e2e2e2e4a2e2e2e7b2e2e2e6a492e2e
6545382e2e2a5b792e652e2e2e2e2e2e2e2e70442e7d2e2e2e222e2e502e2e2e
2e2e382e6c36252e2e522e2e592e2e2e2e2e3f592e2e2e782e2e572e4e2e2e2e
2e2e372e2e2e2e2e55682e542e51622e552e2e68352e2e2e2e2e2e2e2ed2755

In my implementation however, the hash prefixes I generate do not seem to match the hash prefixes that firefox sent. Hence, I am not getting any full hash matches in my client.
I have followed googles description of the API closely and made sure the previous steps such as url canonicalization are implemented properly.
The url, SHA256 hashes I get are
utfvq.portrelay.com/  : 5c2383012676e63656c13167e1cc4f55309c4e1b73c22556e36ec1487e8b8697
portrelay.com/ : 842638fe92ee436da7808d0232d03bcaa0f5c8b64ad5eee97bf28dbb6a49f8ae
Can some one point out why the hashes do not match. I have followed the API guide to the best of my knowledge. Is there some implementation detail I am missing ?

A: It turned out to be a basic character encoding error on my part.
The SHA hashes I compute in my code are correct. The way I looked at the hashes that firefox sent was wrong. I copied the characters from a text file where it stored any byte not with in regular ascii range as a dot(.). Then I converted these to Hex values which is a kind of "lossy" encoding. This is why there were so many "2e" hex chars in the hashes. Now I am using just the original bytes and they match.


text:
Q: Is it impossible to tell if a function is a generator function if .bind() has been called on it? Looks like calling .bind(this) on any generator function breaks my ability to see if the function is a generator. Any ideas on how to fix this?
var isGenerator = function(fn) {
    if(!fn) {
        return false;
    }

    var isGenerator = false;

    // Faster method first
    // Calling .bind(this) causes fn.constructor.name to be 'Function'
    if(fn.constructor.name === 'GeneratorFunction') {
        isGenerator = true;
    }
    // Slower method second
    // Calling .bind(this) causes this test to fail
    else if(/^function\s*\*/.test(fn.toString())) {
        isGenerator = true;
    }

    return isGenerator;
}

var myGenerator = function*() {
}

var myBoundGenerator = myGenerator.bind(this);

isGenerator(myBoundGenerator); // false, should be true

A: Since .bind() returns a new (stub) function that only just calls the original with .apply() in order to attach the proper this value, it is obviously no longer your generator and that is the source of your issue.
There is a solution in this node module: https://www.npmjs.org/package/generator-bind.
You can either use that module as is or see how they solve it (basically they make the new function that .bind() returns also be a generator).

A: Yes, it is possible to tell if a function is a generator even if .bind() has been called on it:
function testIsGen(f) {
  return Object.getPrototypeOf(f) === Object.getPrototypeOf(function*() {});
}

A: This package has the solution:
https://www.npmjs.org/package/generator-bind
Basically, in order to get it to work you either need to polyfill Function.prototype.bind or call a custom bind() method.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to load a CSV file located on the local server into MySQL table? I am trying to upload data from a CSV file located on the local server where MySQL is hosted. So I tried using the "Data Load" command in mysql but I get the following fatal error
MySQL Database Error: Fatal error encountered during command execution

This is this my query
TRUNCATE TABLE setup_new_campaign;
LOAD DATA LOCAL infile 'D:\\Uploads\setup_new_campaign.csv'
into table setup_new_campaign
fields terminated by ','
lines terminated by '\r\n';

The hosted server is a Windows.

A: I'm not sure if this help but the problem seems to be related to your servers binary log format.
Try changing your binary log format in your my.cnf file to:
binlog_format=ROW

and restart your server, you could also try setting the binlog_format configuration to MIXED
You can also change the format only for the current session:
SET SESSION binlog_format = ROW;
TRUNCATE TABLE setup_new_campaign;
LOAD DATA LOCAL INFILE 'D:\\Uploads\setup_new_campaign.csv'
INTO table setup_new_campaign
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n';

The line-endings is probably terminated by \n and not \r\n


text:
Q: XSD elements to a Form in ASP.NET Is there a standard way to convert an XSD to an input form (ASP.NET C#) so that later on whenever a new field is added / removed from the XSD the field on the page automatically shows up or goes away respectively, is this something which needs to be developed in-house I assume there must be a way to serializes / deserializes and generates a form? Any hel would be appreciated..

A: I don't think there's anything built in to make this fully automatic.  However, you can get pretty close.  Visual Studio includes a command line program called xsd.exe that you can use to automatically create a class definition from an xsd document.  Once you have that class definition you can connect it to a form via an ObjectDataSource component and a DetailsView control.

A: Assumption: You're using XML because it is simpler for you at the moment.
Idea: Since you want to create a form to manipulate the data, I'm guessing you might be open to SQL instead of XML. This may not be the case, but you will probably find more tools to help you if you have a database backend instead of an XML/XSD backend. (Plus there are ways you can convert your data from one to another).
There are tools that create forms from databases in ASP.NET. SubSonic, for example, has a auto-scaffolding module that lets you create a database manager knowing only its schema. If the schema changes, just have SubSonic regenerate its files and your forms will have been modified. It isn't perfect, but it may go a long way, depending on your needs.
Option 1) You can create the database schema from the XSD (How can I create database tables from XSD files?) and use SubSonic from that point on. This may be even more of a pain than you original question... only you know.
Option 2) Hack the SubSonic scaffolding so that it supports your underlying XSD/XML instead of a database. You can probably re-use lots of their infrastructure (SubSonic is open source) to generate the form from an XSD.
Good luck!

A: Well, I have to say that the ObjectDataSource is not a bad idea, but this does not work if you have nested elements. On top of this, for nested elements you will have all the "..FieldSpecified" boolean fields in the DetailsView as well.
I'm still trying to figure out how to generate a ASP.NET form using an XSD file, without having to type in everything, which is monkey work.
Anyone already ran into that issue?
PS: An other approach would be to use InfoPath, but this requires licensed software to run as webforms...


text:
Q: Exclude jQuery from vendor.js in ember-cli Is it possible to exclude jQuery dependency from vendor.js in ember-cli when building for production only? I want to include it separately in my site.

A: You can control which files will be used in development or production using a hash like configuration. In your case you should use:
var app = new EmberApp({
  vendorFiles: {
    'jquery.js': {
      development: 'bower_components/jquery/dist/jquery.js',
      production: false
    }
  }
});

Refer to Customizing a built-in asset section for further info.

A: At the end the only thing worked for me was this:
var app = new EmberApp({
 vendorFiles: {
    production: false,
    development: 'bower_components/jquery/dist/jquery.js'
  }
});

This will exclude it in production but not in development.

A: This is a rather simple matter, check the bower.json file in your directory and remove the jquery entry, or simply run bower uninstall jquery --save in the cli.
Oups missed the in production only, well you can save it as a dev-dependency that way it's not included in the build.
So remove jquery and then run bower install --save-dev jquery


text:
Q: Issue while handling back button event in ionic2 application with custom routes I've implemented back button code in my ionic 2 application as suggested here. but it is not working as expected.
However i'm getting console.log() while back button tapped.
Below is my code for reference.
1) app.routes.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { Login } from '../pages/Login/Login';
import { Orders } from '../pages/Orders/Orders';
import { OrderDetails } from '../pages/Orders/OrderDetails';
import { AssignOrder } from '../pages/Orders/AssignOrder';

const routes: Routes = [
    {
        path: '', redirectTo: '/Orders',
        pathMatch: 'full'
    },
    {
        path: 'Login',
        component: Login
    },
    {
        path: 'Orders',
        component: Orders
    },
    {
        path: 'OrderDetails/:orderid',
        component: OrderDetails
    },
    {
        path: 'AssignOrder',
        component: AssignOrder
    }
];

@NgModule({
    imports: [
        RouterModule.forRoot(routes)
    ],
    exports: [
        RouterModule
    ]
})
export class AppRoutingModule { }
export const routedComponents = [Login, Orders, OrderDetails, AssignOrder];

2) app.component.ts
import { Component } from '@angular/core';
import { App, Platform, ViewController } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
@Component({
  templateUrl: 'app.html'
})

export class MyApp {

  constructor(app: App, platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      statusBar.styleDefault();
      if (splashScreen) {
        setTimeout(() => {
          splashScreen.hide();
        }, 100);
      }
    });

    platform.registerBackButtonAction(() => {
      let nav = app.getActiveNav();
      console.log(nav);
      let activeView = nav.getActive();
      if (activeView != null) {
        console.log('activeView:' + activeView);
        if (nav.canGoBack()) {
          nav.pop();
        } else if (typeof activeView.instance.backButtonAction === 'function')
          activeView.instance.backButtonAction();
        else nav.parent.select(0); // goes to the first tab
      }
      else {
        console.log('activeView is null');
      }
    });
  }
}

3) Orders.ts
In Orders page, if i click back button it will call function in app.component.ts in which i'm getting "activeView" as undefined in let activeView = nav.getActive(); line. So, i get "activeView is null" is printed in console.(as mentioned in first solution here). Please see this image.
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Platform, AlertController, LoadingController } from 'ionic-angular';
import { User } from '../../models/User';
import { Order } from '../../models/Order';
import { UserService } from '../../providers/UserService';
import { OrderService } from '../../providers/OrderService';

@Component({
  selector: 'page-Orders',
  templateUrl: 'Orders.html'
  // providers: [UserService, OrderService],
})
export class Orders implements OnInit {
  orders: Order[];
  selectedOrder: Order;
  user: User;
  error: any;
  showFilter: boolean;
  Search: any;
  loading: any;

  constructor(public router: Router,
    public userService: UserService,
    public orderService: OrderService,
    public platform: Platform,
    public alertCtrl: AlertController,
    public loadingCtrl: LoadingController) {
    this.showFilter = false;
    this.Search = '';
  }

  ngOnInit() {
    if (localStorage.getItem('User') == null) {
      this.router.navigate(['/Login']);
    }
    else {
      this.userService.user = JSON.parse(localStorage.getItem('User'));
      this.getOrders();
    }
  }

  backButtonAction() {

  }
}

4) OrderDetails.ts
In OrderDetails page, if i click back button it will call function in OrderDetails.ts because i'm overriding method of app.component.ts by
this.platform.registerBackButtonAction(this.backButtonAction, 10); (as mentioned in second solution here). I'm getting "backButtonAction called" in console log too. but it gives me error at this.gotoOrders(); line. It can't find gotoOrders() function in 'this'. In debug window, i've expand 'this' and i can't see gotoOrders() function there.  Please see this image.
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { Platform, AlertController, LoadingController } from 'ionic-angular';
import { User } from '../../models/User';
import { Order } from '../../models/Order';
import { UserService } from '../../providers/UserService';
import { OrderService } from '../../providers/OrderService';

@Component({
  selector: 'page-OrderDetails',
  templateUrl: 'OrderDetails.html'
})
export class OrderDetails implements OnInit {
  modal: any;
  @Input() order: Order;
  @Output() close = new EventEmitter();
  user: User;
  loading: any;
  isStaff = this.userService.user.Role == "STAFF";
  navigated = false; // true if navigated here

  constructor(public router: Router,
    private route: ActivatedRoute,
    public userService: UserService,
    public platform: Platform,
    public orderService: OrderService,
    public alertCtrl: AlertController,
    public loadingCtrl: LoadingController) {
    this.platform.registerBackButtonAction(this.backButtonAction, 10);
  }

  ngOnInit() {
    if (this.userService.user == null) {
      this.userService.logout();
    }
    else {
      this.route.params.forEach((params: Params) => {
        if (params['orderid'] !== undefined) {
          let orderid = params['orderid'];
          this.navigated = true;
        }
      });
    }
  }

  backButtonAction() {
    console.log('backButtonAction called');
    this.gotoOrders();
    // if (this.modal && this.modal.index === 0) {
    //   this.modal.dismiss();
    // } else {
    //   /* exits the app, since this is the main/first tab */
    //   this.platform.exitApp();
    //   // this.navCtrl.setRoot(AnotherPage);  <-- if you wanted to go to another page
    // }
  }

  gotoOrders(): void {
    this.router.navigate(['/Orders']);
  }
}


text:
Q: AWS CloudFormation: Creating Security Group fails while it is referencing another security I am deploying an AWS CloudFormation template. In my template, I am referencing another security group from one security group. But the deployment is failing.
This is my template.
AWSTemplateFormatVersion: '2010-09-09'
Description: "Simple 3 tier web application template"
Parameters:
  KeyName:
    Default: 'MyanEat'
    Type: String
  VpcCidr:
    Default: '10.1.0.0/16'
    Type: String
    AllowedPattern: '(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/(\d{1,2})'
  InstanceType:
    Default: 't2.micro'
    Type: String
  SSHLocation:
    Description: The IP address range that can be used to SSH to the EC2 instances
    Type: String
    MinLength: '9'
    MaxLength: '18'
    Default: 0.0.0.0/0
    AllowedPattern: "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})"
    ConstraintDescription: Must be a valid IP CIDR range of the form x.x.x.x/x
Mappings:
  AWSInstanceType2Arch:
    t1.micro:
      Arch: HVM64
    t2.nano:
      Arch: HVM64
    t2.micro:
      Arch: HVM64
    t2.small:
      Arch: HVM64
    t2.medium:
      Arch: HVM64
    t2.large:
      Arch: HVM64
    m1.small:
      Arch: HVM64
    m1.medium:
      Arch: HVM64
    m1.large:
      Arch: HVM64
    m1.xlarge:
      Arch: HVM64
    m2.xlarge:
      Arch: HVM64
    m2.2xlarge:
      Arch: HVM64
    m2.4xlarge:
      Arch: HVM64
    m3.medium:
      Arch: HVM64
    m3.large:
      Arch: HVM64
    m3.xlarge:
      Arch: HVM64
    m3.2xlarge:
      Arch: HVM64
    m4.large:
      Arch: HVM64
    m4.xlarge:
      Arch: HVM64
    m4.2xlarge:
      Arch: HVM64
    m4.4xlarge:
      Arch: HVM64
    m4.10xlarge:
      Arch: HVM64
    c1.medium:
      Arch: HVM64
    c1.xlarge:
      Arch: HVM64
    c3.large:
      Arch: HVM64
    c3.xlarge:
      Arch: HVM64
    c3.2xlarge:
      Arch: HVM64
    c3.4xlarge:
      Arch: HVM64
    c3.8xlarge:
      Arch: HVM64
    c4.large:
      Arch: HVM64
    c4.xlarge:
      Arch: HVM64
    c4.2xlarge:
      Arch: HVM64
    c4.4xlarge:
      Arch: HVM64
    c4.8xlarge:
      Arch: HVM64
    g2.2xlarge:
      Arch: HVMG2
    g2.8xlarge:
      Arch: HVMG2
    r3.large:
      Arch: HVM64
    r3.xlarge:
      Arch: HVM64
    r3.2xlarge:
      Arch: HVM64
    r3.4xlarge:
      Arch: HVM64
    r3.8xlarge:
      Arch: HVM64
    i2.xlarge:
      Arch: HVM64
    i2.2xlarge:
      Arch: HVM64
    i2.4xlarge:
      Arch: HVM64
    i2.8xlarge:
      Arch: HVM64
    d2.xlarge:
      Arch: HVM64
    d2.2xlarge:
      Arch: HVM64
    d2.4xlarge:
      Arch: HVM64
    d2.8xlarge:
      Arch: HVM64
    hi1.4xlarge:
      Arch: HVM64
    hs1.8xlarge:
      Arch: HVM64
    cr1.8xlarge:
      Arch: HVM64
    cc2.8xlarge:
      Arch: HVM64
  AWSRegionArch2AMI:
    us-east-1:
      HVM64: ami-0ff8a91507f77f867
      HVMG2: ami-0a584ac55a7631c0c
    us-west-2:
      HVM64: ami-a0cfeed8
      HVMG2: ami-0e09505bc235aa82d
    us-west-1:
      HVM64: ami-0bdb828fd58c52235
      HVMG2: ami-066ee5fd4a9ef77f1
    eu-west-1:
      HVM64: ami-047bb4163c506cd98
      HVMG2: ami-0a7c483d527806435
    eu-west-2:
      HVM64: ami-f976839e
      HVMG2: NOT_SUPPORTED
    eu-west-3:
      HVM64: ami-0ebc281c20e89ba4b
      HVMG2: NOT_SUPPORTED
    eu-central-1:
      HVM64: ami-0233214e13e500f77
      HVMG2: ami-06223d46a6d0661c7
    ap-northeast-1:
      HVM64: ami-06cd52961ce9f0d85
      HVMG2: ami-053cdd503598e4a9d
    ap-northeast-2:
      HVM64: ami-0a10b2721688ce9d2
      HVMG2: NOT_SUPPORTED
    ap-northeast-3:
      HVM64: ami-0d98120a9fb693f07
      HVMG2: NOT_SUPPORTED
    ap-southeast-1:
      HVM64: ami-08569b978cc4dfa10
      HVMG2: ami-0be9df32ae9f92309
    ap-southeast-2:
      HVM64: ami-09b42976632b27e9b
      HVMG2: ami-0a9ce9fecc3d1daf8
    ap-south-1:
      HVM64: ami-0912f71e06545ad88
      HVMG2: ami-097b15e89dbdcfcf4
    us-east-2:
      HVM64: ami-0b59bfac6be064b78
      HVMG2: NOT_SUPPORTED
    ca-central-1:
      HVM64: ami-0b18956f
      HVMG2: NOT_SUPPORTED
    sa-east-1:
      HVM64: ami-07b14488da8ea02a0
      HVMG2: NOT_SUPPORTED
    cn-north-1:
      HVM64: ami-0a4eaf6c4454eda75
      HVMG2: NOT_SUPPORTED
    cn-northwest-1:
      HVM64: ami-6b6a7d09
      HVMG2: NOT_SUPPORTED
Resources:
  Vpc:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: !Ref VpcCidr
      EnableDnsHostnames: True
      EnableDnsSupport: True
  PublicSubnet1:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref Vpc
      CidrBlock: !Select [ 0, !Cidr [ !Ref VpcCidr, 12, 8 ] ]
      MapPublicIpOnLaunch: True
      AvailabilityZone: !Select
        - 0
        - Fn::GetAZs: !Ref "AWS::Region"
  DatabaseSubnet1:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref Vpc
      CidrBlock: !Select [ 2, !Cidr [ !Ref VpcCidr, 12, 8 ] ]
      AvailabilityZone: !Select
        - 0
        - Fn::GetAZs: !Ref "AWS::Region"
  WebServerInstance:
    Type: AWS::EC2::Instance
    Properties:
      InstanceType: !Ref InstanceType
      KeyName: !Ref KeyName
      SubnetId: !Ref PublicSubnet1
      ImageId:
        Fn::FindInMap:
          - AWSRegionArch2AMI
          - Ref: AWS::Region
          - Fn::FindInMap:
              - AWSInstanceType2Arch
              - Ref: InstanceType
              - Arch
      AvailabilityZone: !Select
        - 0
        - Fn::GetAZs: !Ref "AWS::Region"
  WebServerSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Enable HTTP access via port 80
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: '80'
          ToPort: '80'
          CidrIp: 0.0.0.0/0
        - IpProtocol: tcp
          FromPort: '22'
          ToPort: '22'
          CidrIp:
            Ref: SSHLocation
  DBSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Enable TCP connection on port 3306 for database connection
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: '0'
          ToPort: '3306'
          SourceSecurityGroupId:
            Ref: WebServerSecurityGroup

When I deployed the template it was failing. When I print out the event logs. It is saying that creating DBSecurityGroup is failing. What is wrong with my template and how can I fix it?

A: The Last line in your template should be
SourceSecurityGroupId: !GetAtt WebServerSecurityGroup.GroupId .
Also i noted inside both AWS::EC2::Subnet  the CidrBlock property should be
CidrBlock: !Select [ 0, !Cidr [ !GetAtt Vpc.CidrBlock, 12, 8 ] ]
and
CidrBlock: !Select [ 2, !Cidr [ !GetAtt Vpc.CidrBlock, 12, 8 ] ]

A: I launched your template in my sandbox environment (us-east-1) in an attempt to identify all issues.
Your template has only one issue preventing it from deployment. Namely in your DBSecurityGroup you should have:
SourceSecurityGroupId:
 !GetAtt WebServerSecurityGroup.GroupId

Fixing that, resulted in successful deployment.


text:
Q: BCC or CC in Reply - Sender Profile How Do I add BCC or CC in Sender Profile Under Reply section?
For example currently I am using %%AgentEmail%% in Reply of Sender Profile, So I want when receiver reply the email one reply goes to Agent (which is working) and the same reply should be CC to lets say xyz@gmail.com?

A: The CC and BCC options have to be enabled by SFMC Support.
Reference: Email Messages


text:
Q: Access 2003 FORMS: when I set at runtime with VBA the "RowSource" for a ListBox persist even if I close and then open Access 2003 FORMS: when I set at runtime with VBA the "RowSource" for a ListBox persist even if I close and then open...
How to fix this, I would like to have clean "RowSource" when I open a new form...

A: You can set the RowSource during form load.
Private Sub Form_Load()
    Dim strSql As String
    strSql = "SELECT f.id, f.fname FROM foo AS f ORDER BY f.fname;"
    Me.lstNames.RowSource = strSql
End Sub

A: Setting the RowSource of the List Box changes the Form's design. Access wants to save those changes for you (actually, I think the default behavior is to ask). If you want to close the form without changes, put this code in a Command Button's OnClick:
DoCmd.Close acForm, Me.Name, acSaveNo

The last parameter tells Access to not save the changes. Another alternative is what HansUp gave you in his second comment to his answer--just disable the List Box. Then when you figure out what its RowSource should be (on user input), set the RowSource & the Enabled property.


text:
Q: Bolt CMS with Angular - how to create Angular theme I've created a custom JSON API extension for bolt and want to have a bolt theme that uses Angular, but am unsure of the best way to go about this.
Bolt would simply serve the API and a single template via a custom theme.
As far as I can see, the main issue is routing/templating. All routes other than /bolt need to use a single template, say index.twig as this will be the only template available.
Is this possible with Bolt?

A: Have you tried to treat AngularJS vars as Twig/PHP strings ?
Like:
{{ "{{Angular.var}}" }}

You could write a Macro to smplify the process
Check the Twig docs to see how to write Macros in twig files.
http://twig.sensiolabs.org/doc/templates.html#macros


text:
Q: How to initialize static member when = operator is overridden in c++ Please excuse my English.
I did override operator= in my class. Now I am struggling to initialize a static member.
I get:
error: conversion from 'int' to non-scalar type 'TObj' requested
My Header File:
#include <mutex>

template<typename T>
class TObj{
private:
    std::mutex m;
public:
    T val;
    // = coperation
     TObj& operator=(const T& rhs){
       m.lock();
       val = rhs;
       m.unlock();
       return *this;
    }

    operator T(){
        m.lock();     // THIS IS A BUG. Thank you Praetorian
        return val;   // RETURNS AND NEVER UNLOCKS
        m.unlock();   // DO NOT USE. Use lock_guard
    }

    ~TObj(){}

};

class OJThread
{
private:

public:
    OJThread();
    virtual void run() = 0;
    void start();
};

My ugly cpp file:
#include <iostream>
#include "ojthread.h"

using namespace std;

class testThread: OJThread{

public:
    static TObj<int> x;
    int localX;
    testThread(){
        localX = x;
    }

    void run(){
        cout<<"Hello World. This is "<<localX<<"\n";
    }

};

TObj<int> testThread::x = 0;

int main()
{

    testThread myThread;
    testThread myThread2;

    myThread.run();
    myThread2.run();
    return 0;
}

I haven't implemented threads yet so please don't worry about that.
I get error at the line:
TObj<int> testThread::x = 0;

If this member is public and not static, it is no problem to do:
myThread1.x = 0;
Thank you

A: You have to implement a constructor which takes T as parameter for TObj. When you perform a assignment during a object initialization it calls the constructor of the initializing object rather than the operator=.
So this
TObj<int> testThread::x = 0;

is basically the same as
TObj<int> testThread::x(0);


text:
Q: Cannot cast from generic to get LINQ where clause OK so I've written the following function:
private IQueryable<LogEntry> SelectAll<T>(IEnumerable<LogEntry> logEntries, List<Expression<Func<LogEntry, bool>>> whereClause)
{
    var selectAllQuery = from l in logEntries select l;
    if (whereClause != null)
    {
        foreach (Expression<Func<LogEntry, bool>> whereStatement in whereClause)
        {
            selectAllQuery = selectAllQuery.Where(whereClause);
        }
    }
}

But it won't compile. It throws an error when it tries to return something at "selectAllQuery" as follows:

System.Collections.Generic.IEnumerable' does not contain a definition for 'Where' and the best extension method overload
  System.Linq.Enumerable.Where(System.Collections.Generic.IEnumerable, System.Func)' has some invalid arguments

I've tried casting this every which way I can think of to no avail. In the above code, running the initial select statement returns selectAllQuery of type System.Linq.Enumerable.WhereSelectEnumerableIterator<LogEntry,LogEntry>
Clearly I'm missing something fundamental about LINQ. But what?
Cheers.

A: The problem is that selectAllQuery is an IEnumerable<LogEntry> and you need it to be an IQueryable<LogEntry> in order to use expression trees. Try just changing the first line of the method:
var selectAllQuery = logEntries.AsQueryable();

Alternatively, compile the predicates as you go to get them into delegate form:
foreach (Expression<Func<LogEntry, bool>> whereStatement in whereClause)
{
    selectAllQuery = selectAllQuery.Where(whereStatement.Compile());
}

EDIT: Okay, the problems weren't just because of Queryable, but because of your naming. Let's look at this foreach statement:
foreach (Expression<Func<LogEntry, bool>> whereStatement in whereClause)
{
    selectAllQuery = selectAllQuery.Where(whereClause);
}

You're not using whereStatement anywhere in the body of the loop. You're trying to call Where with the entire list of clauses on each iteration. This is where better naming would help. Try this, for example:
private IQueryable<LogEntry> SelectAll<T>(IEnumerable<LogEntry> logEntries,
    List<Expression<Func<LogEntry, bool>>> filters)
{
    var selectAllQuery = logEntries.AsQueryable();
    if (filters != null)
    {
        foreach (var filter in filters)
        {
            selectAllQuery = selectAllQuery.Where(filter);
        }
    }
    return selectAllQuery;
}

Because the parameter is now pluralized, it would look obviously wrong as the argument to the Where method - whereas the difference between whereStatement and whereClause isn't at all obvious as the former being singular and the latter being plural.

A: Some times these kind of errors would get away with simple solution like adding System.Linq to the project...and referring it in the class file. Very sad that VS IDE does not help us to resolve as part of the refactor menu...


text:
Q: How to formally state and prove vacuous truth? How to show in a proof that a statement is vacuously true because "if $\alpha$ then $\beta$", and also prove $\alpha$ is false, in a formal way? and also particularly, how to structure such proofs?

For example to vacuously prove $\forall A. \varnothing \subseteq A$.
Speaking in natural language (I'm new to mathematics), what I want to formally say is:
$\forall x.$ if $x \in \varnothing $ then $x \in A$.
$x \notin \varnothing $: etc. etc.
"if $x \in \varnothing $" is true because the condition is false, because $x \notin \varnothing $, therefore $x \in A$, vacuously.

A: Remember: when you have a sentence of the form
$$\forall x \in \emptyset \ \ \ \ p(x)$$
this is always true. Some examples:
$$\begin{matrix}
\forall x \in \emptyset \ \ \ \ x \notin \emptyset \\
\forall x \in \emptyset \ \ \ \ \exists y \in \emptyset : y >x \\
\forall x \in \emptyset \ \ \ \ x \mbox{ is a beautiful horse} \\
\forall x \in \emptyset \ \ \ \ x=1 \\
\forall x \in \emptyset \ \ \ \ \mbox{ my mother told me to go to school} \\
\forall x \in \emptyset \ \ \ \ \mbox{ Riemann's hypothesis is false}
\end{matrix}$$
are all true sentences.
This property allows you to prove some nice properties of the empty set. For example:

*

*$\forall x \in \emptyset \ \  x \in A$, means that $\emptyset \subseteq A$, whenever $A$ is a set.

*The empty set is an open set of $\mathbb{R}$. In fact it is true that $\forall x \in \emptyset \ \  \exists r >0 : B(x,r) \subseteq \emptyset$

*The empty set is totally ordered. In fact $\forall x,y \in \emptyset \ \ x \leq y$

*The supremum of the empty set is $- \infty$. In fact $\forall x \in \emptyset \ \ \forall y \in \mathbb{R} \ \ x \leq y$, so the set $\{ y \in \mathbb{R}: \forall x \in \emptyset \ \ x \leq y \}$ is $\mathbb{R}$, and its "minimum" is $- \infty$

A: "Vacuous Truth" refers to members of the empty set having some sort of characteristic; normally we do not talk about this in mathematics (it's somewhat useless, really).
For example, $P(x)$ could mean "All the beer in an Alcoholics Anonymous meeting" and $Q(x)$ could mean "is brewed in Mexico." The statement "All the beer in an AA meeting is brewed in Mexico" would be true, despite the fact that no one at an AA meeting drinks beer, and therefore, there's no beer at all in the meeting.
Written in mathematical/logical terms, I believe it would look something like this:
$$P(x) \implies Q(x), \space \space\forall x: \lnot P(x)$$
Another intuitive way to express it:
Let $P$ be the set of all beer at an AA meeting. (Hopefully) $P$ would be the empty set. $Q(x)$ denotes the beer $x$ brewed in Mexico. Thus, our statement would be expressed as:
$$\forall x \in P, \space \space Q(x), $$ where $P = \emptyset$.
I think you're more likely to see this logical structure in more classical/theoretical works in logic rather than mathematics. As far as my knowledge is concerned, the "null set" is a bit of a dead end: mathematicians don't talk about "elements in a null set" for the sake of pointing out "vacuous truth."
If you'd like more information, this site should be a good reference: http://www.abstractmath.org/MM/MMConditional.htm


text:
Q: teradata concatenating rows based on a column I have a table like below
Cstmr_ID | PPM | prepaid |home_phone|srvc_num
1        |Y    |N        |N         |0422222222
1        |Y    |N        |N         |0433333333
1        |N    |N        |Y         |0333333333
2        |y    |N        |N         |0455555555
2        |N    |N        |Y         |0355555555

Now I want a table like this.
Cstmr_id  | PPM_srvc_num         |prepaid_srvc_num|home_phone_srvc_num
1         |0422222222,0433333333 |                |0333333333
2         |0455555555            |                |0355555555

A: What you want to do is to transpose your table and then group concatenate records.  Since Teradata 14.10 there is TD_UNPIVOT function to transpose but I have not worked with that yet.
If you can live with fixed upper limit (N) on numbers the same column for one Cstmr_id in your result you can use case statements and row_number() to emulate transpose and group concatenate.
select Cstmr_id
, max(case when PPM='Y' and rn=1 then srvc_num else null end)
||  coalesce(max(case when PPM='Y' and rn=2 then ','||srvc_num else null end),'')
...
||  coalesce(max(case when PPM='Y' and rn=N then ','||srvc_num else null end),'')
as PPM_srvc_num
-- add the further lines for prepaid ='Y' and home_phone='Y'
from (
  select *
  , row_number() over (partition by Cstmr_ID, PPM, prepaid, home_phone) as rn
  from your_table
) dt
group by 1

I have not tested  the code above but I have actually done that type of transformation before for myself so it should work after writing it out completely for your actuall table


text:
Q: change div with with php or jquery I want to change div with either php or jquery the important is to change div width.
scenario:
I have div what i want if i click  tag click me to inlarge the div div must increase the width and when click the click me to default width div go back to the default width.

 my content here

click me to inlarge the div
click me to default width

A: Use .css() to change the width of the div.
Try this:
$('.inlarge').click(function () {
    $(".mydiv").css("width", "100%");
});
$('.default').click(function () {
    $(".mydiv").css("width", "50%");
});

JSFiddle Demo

A: you can use animate functyion or just css function to do this:-
$(function(){
$('.inlarge').click(function(){
    $('.mydiv').animate({'width':'100%'},1000);
});

 $('.default').click(function(){
     $('.mydiv').animate({'width':'80%'},1000);
  });
});

by css:-
$(function(){
  $('.inlarge').click(function(){
    $('.mydiv').css({'width':'100%'});
});

 $('.default').click(function(){
  $('.mydiv').css({'width':'80%'});
   });
});

Demo

A: You can use .css using jquery -
var width = $( ".mydiv" ).width(); // calculate default width
//alert(width);return false;
$('.inlarge').click(function(){
    $('.mydiv').css('width','100px'); // change 100px
});
$('.default').click(function(){
    $('.mydiv').css('width',width+'px');
});


text:
Q: Rails - date_select not allow to choose past date I am using the following code
<%= f.date_select 'event_date', selected: Date.today, :start_year => Date.today.year, :end_year => Date.today.year + 1 %>

I want to ban people from choosing data at a min of 5 days from now. and max of 1 year max. How can i set the date and month?
Or should i do this in model validation?

A: From this answer: Rails 4 date_field, min and max year?
You should be able to give the min and max dates:
f.date_select 'event_date', selected: Date.today, min: 5.days.ago, max: 1.year.from_now


text:
Q: todonotes: How to make multiple listoftodos? In this MWE, I made two commands to highlight parts of the text as a reviewer comment, while the comments are colored uniquely to indicate the author whose comment is typeset.
If I want to make two listoftodos, each has the comments entries of one author, how can it be done?
\documentclass{article}
\usepackage{hyperref,lipsum}

\usepackage[textwidth=2.5cm,colorinlistoftodos]{todonotes}
\setlength{\marginparwidth}{2.5cm}

\newcommand\stR[2]{% 1st reviewer comment
    \todo[%
    author=1st Reviewer,noline,caption={1st Reviewer #1 Comment},color=blue!20%
    ]%
    {#1 Comment}{\color{blue}{\bfseries#2}}}

\newcommand\ndR[2]{% 2nd reviewer comment
    \todo[%
    author=2nd Reviewer,noline,caption={2nd Reviewer #1 Comment},color=red!50!white%
    ]%
    {#1 Comment}{\color{red}{\bfseries#2}}}

\begin{document}
\listoftodos[Reviewers Comments]
\section{Section}
Text \stR{2nd}{2nd comment of the 1st reviewer} another text\vspace{\baselineskip}
\lipsum[1]\vspace{\baselineskip}
Some text \ndR{1st}{1st comment of the 2nd reviewer} continue text
\end{document}

A: A bit hackish but imho it should work. Be aware that it assumes that you use hyperref.
\documentclass{article}
\usepackage{hyperref}
\usepackage{lipsum}

\usepackage[textwidth=2.5cm]{todonotes}
\setlength{\marginparwidth}{2.5cm}

\usepackage{etoolbox}

\makeatletter
\newcommand\@todonotes@owner{default}
\define@key{todonotes}%
    {owner}{\def\@todonotes@owner{#1}}

\newtoggle{ownerdefault}
\newtoggle{ownerB}

\newcommand\stR[2]{% 1st reviewer comment
    \todo[%
    owner=default,
    author=1st Reviewer,noline,caption={1st Reviewer #1 Comment},color=blue!20%
    ]%
    {#1 Comment}{\color{blue}{\bfseries#2}}}

\newcommand\ndR[2]{% 2nd reviewer comment
    \todo[%
    owner=B,
    author=2nd Reviewer,noline,caption={2nd Reviewer #1 Comment},color=red!50!white%
    ]%
    {#1 Comment}{\color{red}{\bfseries#2}}}

\renewcommand{\@todonotes@addElementToListOfTodos}{%
    \if@todonotes@colorinlistoftodos%
     \addtocontents{tdo}
      {%
       \protect\iftoggle{owner\@todonotes@owner}
         {%
          \protect\contentsline {todo}
            {\protect\fcolorbox{\@todonotes@currentbordercolor}%
                {\@todonotes@currentbackgroundcolor}%
                {\protect\textcolor{\@todonotes@currentbackgroundcolor}{o}}%
            \ \@todonotes@caption
            }{\thepage}{\@currentHref}%
          }{}%
       }%
    \else%
      \addtocontents{tdo}
      {%
       \protect\iftoggle{owner\@todonotes@owner}
         {%
          \protect\contentsline {todo}
            {\@todonotes@caption
            }{\thepage}{\@currentHref}%
          }{}%
       }%
    \fi}%

\makeatother
\begin{document}
\toggletrue{ownerdefault}
\section*{Reviewers 1 Comments}
\InputIfFileExists{\jobname.tdo}{}

\toggletrue{ownerB}
\togglefalse{ownerdefault}
\section*{Reviewers 2 Comments}
\InputIfFileExists{\jobname.tdo}{}

\togglefalse{ownerB}
\makeatletter \@starttoc{tdo}\makeatother % to trigger the creation of the list

\section{Section}
Text \stR{2nd}{2nd comment of the 1st reviewer} another text\vspace{\baselineskip}
\lipsum[1]\vspace{\baselineskip}
Some text \ndR{1st}{1st comment of the 2nd reviewer} continue text
\end{document}


text:
Q: OnItemClick Listener and the visibility of the clicked View item I have a ListView that each item contains one Textview and ImageView which the imageView is invisible and by clicking the each listview item it will be visible my code is :
 @Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    ImageView acceptImageView= (ImageView) view.findViewById(R.id.iAccept);
    if (acceptImageView.getVisibility()==ImageView.INVISIBLE) {
        acceptImageView.setVisibility(ImageView.VISIBLE);
    } else {
        acceptImageView.setVisibility(ImageView.INVISIBLE);
    }
}

List View adapter :
public class ContentViewrAdaptor extends BaseAdapter implements Filterable {

private List<String>   originalData = null;
private List<String>   filteredData = null;
private LayoutInflater mInflater;
private Typeface       regular;
private ItemFilter     mFilter      = new ItemFilter();

public ContentViewrAdaptor(Context context, List<String> data, Typeface regular) {
    this.filteredData = data;
    this.originalData = data;
    this.regular = regular;
    mInflater = LayoutInflater.from(context);
}

public int getCount() {
    return filteredData.size();
}

public Object getItem(int position) {
    return filteredData.get(position);
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {

    ViewHolder holder;

    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.text_view, null);

        holder = new ViewHolder();
        holder.text = (TextView) convertView.findViewById(R.id.contentText);
        holder.text.setTypeface(regular);

        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    if (filteredData.get(position).contains("font"))
        holder.text.setText(Html.fromHtml(filteredData.get(position)));
    else
        holder.text.setText(filteredData.get(position));
    return convertView;
}

static class ViewHolder {

    TextView  text;
}

public Filter getFilter() {
    return mFilter;
}

private class ItemFilter extends Filter {

    @Override
    protected FilterResults performFiltering(CharSequence constraint) {

        String filterString = constraint.toString().toLowerCase();

        FilterResults results = new FilterResults();

        final List<String> list = originalData;

        int count = list.size();
        final ArrayList<String> nlist = new ArrayList<String>(count);

        String filterableString;

        for (int i = 0; i < count; i++) {
            filterableString = list.get(i);
            if (filterableString.toLowerCase().contains(filterString)) {
                filterableString = filterableString.replaceAll(filterString, "" + filterString + "");
                nlist.add(filterableString);
            }
        }

        results.values = nlist;
        results.count = nlist.size();

        return results;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        filteredData = (ArrayList<String>) results.values;
        notifyDataSetChanged();
    }

}
}

but the problem is that when i accept the first item , the third item will be acceped too , because it's the first item when scroll down
how can i solve this problem ?
Update(getView)
but still the same problem
public View getView(final int position, View convertView, ViewGroup parent) {

    ViewHolder holder;

    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.text_view, null);

        holder = new ViewHolder();
        holder.image = (ImageView) convertView.findViewById(R.id.iAccept);
        convertView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Toast.makeText(context,position,Toast.LENGTH_SHORT).show();
                if (v.findViewById(R.id.iAccept).getVisibility() == ImageView.VISIBLE)
                    v.findViewById(R.id.iAccept).setVisibility(ImageView.INVISIBLE);
                else
                    v.findViewById(R.id.iAccept).setVisibility(ImageView.VISIBLE);
            }
        });
        holder.text = (TextView) convertView.findViewById(R.id.contentText);
        holder.text.setTypeface(regular);

        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    if (filteredData.get(position).contains("font"))
        holder.text.setText(Html.fromHtml(filteredData.get(position)));
    else
        holder.text.setText(filteredData.get(position));
    return convertView;

}
Final Update
finally it solved with DIVA help ,
i changed Adapter to this :
public class ContentViewrAdaptor extends BaseAdapter implements Filterable {

private List<String> originalData = null;
private List<String> filteredData = null;
private ArrayList<Integer> visiblePositions;
private LayoutInflater mInflater;
private Typeface regular;
private Context context;
private ItemFilter mFilter = new ItemFilter();

public ContentViewrAdaptor(Context context, List<String> data, Typeface regular) {
    this.filteredData = data;
    this.originalData = data;
    visiblePositions = new ArrayList<Integer>();
    this.regular = regular;
    this.context = context;
    mInflater = LayoutInflater.from(context);
}

public int getCount() {
    return filteredData.size();
}

public Object getItem(int position) {
    return filteredData.get(position);
}

public long getItemId(int position) {
    return position;
}

public View getView(final int position, View convertView, ViewGroup parent) {

    final ViewHolder holder;

    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.text_view, null);

        holder = new ViewHolder();
        holder.image = (ImageView) convertView.findViewById(R.id.iAccept);
        holder.image.setTag(position);
        holder.text = (TextView) convertView.findViewById(R.id.contentText);
        holder.text.setTypeface(regular);

        convertView.setTag(holder);
    } else holder = (ViewHolder) convertView.getTag();

    adjustImageVisibility(holder.image, visiblePositions.contains(position));

    convertView.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            onViewClicked(holder, position);
        }
    });

    if (filteredData.get(position).contains("font")) holder.text.setText(Html.fromHtml(filteredData.get(position)));
    else holder.text.setText(filteredData.get(position));

    return convertView;
}

public void onViewClicked(ViewHolder viewHolder, Integer position) {
    if (visiblePositions.contains(position)) {
        adjustImageVisibility(viewHolder.image, false);
        visiblePositions.remove(position);
    } else {
        adjustImageVisibility(viewHolder.image, true);
        visiblePositions.add(position);
    }
}

public void adjustImageVisibility(ImageView imageView, boolean visible) {
    if (visible) imageView.setVisibility(View.VISIBLE);
    else imageView.setVisibility(View.INVISIBLE);
}

static class ViewHolder {
    ImageView image;
    TextView text;
}

public Filter getFilter() {
    return mFilter;
}

private class ItemFilter extends Filter {

    @Override
    protected FilterResults performFiltering(CharSequence constraint) {

        String filterString = constraint.toString().toLowerCase();

        FilterResults results = new FilterResults();

        final List<String> list = originalData;

        int count = list.size();
        final ArrayList<String> nlist = new ArrayList<String>(count);

        String filterableString;

        for (int i = 0; i < count; i++) {
            filterableString = list.get(i);
            if (filterableString.toLowerCase().contains(filterString)) {
                filterableString = filterableString.replaceAll(filterString, "" + filterString + "");
                nlist.add(filterableString);
            }
        }

        results.values = nlist;
        results.count = nlist.size();

        return results;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        filteredData = (ArrayList<String>) results.values;
        notifyDataSetChanged();
    }

}
}

A: There are few thing u need to make sure :

*

*plz use arraylist instead of static string[]

*use View.Visible or invisible instead of Imagview.Visible and
invisible while comparing visiblity here is code that works :

Adapter
public class ListAdapter extends BaseAdapter implements Filterable {

    private ArrayList<String> originalData = null;
    private ArrayList<String> filteredData = null;
    private LayoutInflater mInflater;
    private Context context;

    private ItemFilter mFilter = new ItemFilter();

    public ListAdapter(Context context, ArrayList<String> data) {
        this.filteredData = new ArrayList<>(data);
        this.originalData = new ArrayList<>(data);
        this.context = context;
        mInflater = LayoutInflater.from(context);
    }

    public int getCount() {
        return filteredData.size();
    }

    public Object getItem(int position) {
        return filteredData.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {

        ViewHolder holder = new ViewHolder();

        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.list_item, null);

            holder = new ViewHolder();
            holder.image = (ImageView) convertView.findViewById(R.id.image);
            // holder.image.setVisibility(View.INVISIBLE);

            holder.text = (TextView) convertView.findViewById(R.id.text);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        // holder.image.setTag(position);
        convertView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                if (v.findViewById(R.id.image).getVisibility() == View.VISIBLE) {
                    v.findViewById(R.id.image).setVisibility(View.INVISIBLE);
                } else {
                    v.findViewById(R.id.image).setVisibility(View.VISIBLE);
                }

            }
        });
        if (filteredData.get(position).contains("font"))
            holder.text.setText(Html.fromHtml(filteredData.get(position)));
        else
            holder.text.setText(filteredData.get(position));
        return convertView;
    }

    static class ViewHolder {
        ImageView image;
        TextView text;
    }

    @Override
    public Filter getFilter() {

        return mFilter;
    }

    private class ItemFilter extends Filter {

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {

            String filterString = constraint.toString().toLowerCase();

            FilterResults results = new FilterResults();

            final ArrayList<String> list = originalData;

            int count = list.size();
            final ArrayList<String> nlist = new ArrayList<String>(count);

            String filterableString;

            for (int i = 0; i < count; i++) {
                filterableString = list.get(i);
                if (filterableString.toLowerCase().contains(filterString)) {
                    filterableString = filterableString.replaceAll(
                            filterString, "" + filterString
                                    + "");
                    nlist.add(filterableString);
                }
            }

            results.values = nlist;
            results.count = nlist.size();

            return results;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint,
                FilterResults results) {
            filteredData = (ArrayList<String>) results.values;
            notifyDataSetChanged();
        }

    }
}

Activity
public class MyActivity extends Activity {

    private ListView listView;
    private ListAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        listView = (ListView) findViewById(R.id.listView);

        ArrayList<String> LIST_ITEM = new ArrayList<String>();
        LIST_ITEM.add("Item 1");
        LIST_ITEM.add("Item 2");
        LIST_ITEM.add("Item 3");
        LIST_ITEM.add("Item 4");
        LIST_ITEM.add("Item 5");
        LIST_ITEM.add("Item 6");
        LIST_ITEM.add("Item 7");
        LIST_ITEM.add("Item 8");
        LIST_ITEM.add("Item 9");
        LIST_ITEM.add("Item 10");

        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        adapter = new ListAdapter(MyActivity.this, LIST_ITEM);
        listView.setAdapter(adapter);

    }
}

COMPLETE SOURCE CODE
EDIT
ALTERNATIVE CODE.

A: For each list item you would need to create a boolean parameter isVisible. And set it to true/false on the click of the list item. Within the getView() method check the isVisible value of each visible item:
if(isVisible)
   make the image visible;
else
   hide the image;


text:
Q: PlatformIO cant find included libraries I am running into a strange issue with including libraries in the lib folder.
Project details:

*

*ESP32 with Arduino Framework

*Trying to get the Adafruit HX8357D LCD to work

What I have done:
Please see the picture attached. I have included all the libraries that I should need. When I compile I run into the "No such file or directory error. I have clearly included the "Adafruit_I2CDevice.h" file in the lib folder under its master folder. But the compiler does not see it. Why?
If I move all the .h and .cpp files in the Adafruit_BusIO-master folder to Adafruit_GFC-Librari-master folder then the "fatal error: Adafruit_I2CDevice.h no such..." error just changes to a different file that is located in the lib folder.
This means there is a deeper issue here with the linker.
Does anyone know why it is doing this? I have not in the past had issues with including files located in the lib folder into various other sources.
Any help would be great.
Thank you

A: I use TFT_eSPI by Bodmer for Adafruit HX8357D. I use the following command to install the lib in my project and it does all th taff.
 pio lib install "bodmer/TFT_eSPI@^2.3.64"

In your case have a look to c_cpp_properties.json in .vscode of your projet to be sure that the "includePath" and "path" points to the good include directories.

A: From the home screen of PlatformIO, you will have to go to the libraries section and search for your desired libraries there, assigning libraries to your desired libraries from there. Only then it will work properly.
If your libraries are successfully added, they should be inside the .pio\libdeps of your project directory.


text:
Q: ¿cómo obtener el valor de una celda en un Data Grid en Compact Framework con C#? Tengo un pequeño problema, ojala y me puedan apoyar, y es el siguiente:
Estoy desarrollando una aplicación para un dispositivo con Windows Embedded y la estoy haciendo en el Compact Framework 3.5; no en el Framework normal.
En la aplicación se mostrara una tabla, la cual tendrá 2 columnas: SKU y Producto. La tabla la hago con DataTable y esos datos los muestro con un DataGrid.
Lo que quiero hacer es, cuando el usuario presione una fila, obtener el SKU de la fila que seleccionó y poder hacer una consulta en base a eso; pero no encuentro la forma de hacerlo con un evento o algo en el DataGrid. Para este CF no viene DataGridView, con el que se puede hacer perfectamente lo que quiero.
¿Existe alguna otra manera de mostrar una tabla y obtener el valor de lo que seleccionó el usuario?


text:
Q: How to install and boot on a RAID 5 Configuration? I've been trying for a couple of days now to get Ubuntu 10.10 installed on a RAID 5 setup. I have 3 1TB drives so I also need Ubuntu to boot off of one of those drives. From what I've been able to find on the forums I need to set one of the drives to have a RAID 1 partition that I can use for /boot but I have no idea how to do that(something about using Gparted?). I'm farily new at this so a step-by-step would be awesome but I'll take any help I can get.

A: I finally resolve the software RAID-5 issue on the DELL R310.
The article just mislead us
https://help.ubuntu.com/community/Installation/SoftwareRAID
Workaround Steps for software RAID-5

*

*Remove all existing RAID settings, LVM setttins

*Create partition with 20G on each disks

*Set the first disk's 20G partition to use as root '/', install your whole OS into it.

*Configure the RAID-x for the rest of your partitions.

Done, hope you get over of it!!

A: You do not need to create a /boot partition anymore.  You do need to use the alternate/text mode installer.  At the partitioning step, create a partition on each disk and set its usage to raid, then create the raid array and assign it to be used for the root ( / ).


text:
Q: web crawler cannot exceed about 1MB/sec speed I am building a webcrawler that gets 1-3 pages off a list of millions of domains, I am using Python with multi threading, i have tried multithreading with httplib, httplib2, urllib, urllib2, urllib3, requests, and curl(fastest of the bunch) as well as twisted, and scrapy but none of them are allowing me to use up more than about 10 mbits of bandwidth( I have 60 mbit speed), usually maxes out at around 100-300 threads and after that it causes failed requests.  I have also had this problem with php/curl.  I have a scraper that scrapes from google plus pages with urllib3 and the Threads module (Python) and that maxes out my 100mbit connection ( I believe this may be because it is re-using an open socket with the same host and google has a fast network response)
here is an example of one of my scripts using pycurl I am reading the urls from a csv file containing the urls.
import pycurl
from threading import Thread
from Queue import Queue
import cStringIO

def get(readq,writeq):
    buf = cStringIO.StringIO()
    while True:
        url=readq.get()

        c = pycurl.Curl()
        c.setopt(pycurl.TIMEOUT, 15)
        c.setopt(pycurl.FOLLOWLOCATION, 1)
        c.setopt(pycurl.USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0')
        c.setopt(c.WRITEFUNCTION, buf.write)
        c.setopt(c.URL, url)
        try:
            c.perform()
            writeq.put(url+'  '+str(c.getinfo(pycurl.HTTP_CODE)))
        except:
            writeq.put('error  '+url)
print('hi')
readq=Queue()
writeq=Queue()

import csv
reader=csv.reader(open('alldataunq2.csv'))
sites = []
ct=0
for l in reader:
    if l[3] != '':
        readq.put('http://'+l[3])
        ct+=1
        if ct > 100000:
            break

t=[]
for i in range(100):
    Thread(target=get,args=(readq,writeq)).start()

while True:
    print(writeq.get())

the bottleneck is definitely network IO as my processor/memory is barely being used.  Has anyone had success in writing a similar scraper that was able to use a full 100mbit connection or more?
any input on how I can increase the speed of my scraping code is greatly appreciated

A: There are several factors you need to keep in mind when optimizing crawling speed.
Connection locality
In order to re-use connections effectively, you need to make sure that you're reusing connections for the same website. If you wait too long to hit an earlier host a second time, the connection could time out and that's no good. Opening new sockets is a relatively expensive operation so you want to avoid it at all costs. A naive heuristic to achieve this is to sort your download targets by host and download one host at a time, but then you run into the next problem...
Spreading the load between hosts
Not all hosts have fat pipes, so you'll want to hit multiple hosts simultaneously—this also helps avoiding spamming a single host too much. A good strategy here is to have multiple workers, where each worker focuses on one host at a time. This way you can control the rate of downloads per host within the context of each worker, and each worker will maintain its own connection pool to reuse connections from.
Worker specialization
One way to ruin your throughput is to mix your data processing routines (parse the HTML, extract links, whatever) with the fetching routines. A good strategy here is to do the minimal amount of processing work in the fetching workers, and simply save the data for a separate set of workers to pick up later and process (maybe on another machine, even).
Keeping these things in mind, you should be able to squeeze more out of your connection. Some unrelated suggestions: Consider using wget, you'd be surprised at how effective it is in doing simple crawls (it can even read from a giant manifest file).

A: I don't think you can expect to get anywhere near your internet connection's max throughput when doing web scraping.
Scraping (and web browsing in general) involves making a lot of small requests. A good deal of that time is spent in connection set-up and tear down, and waiting on the remote end to begin delivering your content.  I'd guess that the time spent actively downloading content is probably around 50%.  If you were downloading a bunch of big files, then I think you'd see better average throughput.

A: Try scrapy with scrapy-redis.
You will have to tune the settings: CONCURRENT_REQUESTS, CONCURRENT_REQUESTS_PER_DOMAIN and CONCURRENT_REQUESTS_PER_IP. Also make sure you have DOWNLOAD_DELAY = 0 and AUTOTHROTTLE_ENABLED = False.


text:
Q: Determine servlet to handle response in filter I want to be able to determine the servlet that will handle a request as part of a Filter implementation.  In the filter code, I want to examine the annotations on that servlet and make decisions on what the filter does based on those annotations.
This post basically asks the same question, but the accepted answer is to configure the mapping from URLs to filters so that the filter is only invoked for a specific set of URLs.  I don't want to have to resort to this if I can avoid it.
Is it possible to do this?


text:
Q: Image that resizes automatically covers text below it if too big I have three things on my page: a menu to the left, a picture beside it that automatically resizes when I change my browser window and an article below the picture.
The problem is that the article does not move down as the image gets bigger.

#about-wrapper{
    white-space:nowrap;
    margin-top:10px;
}

#box{
    border:1px solid #ba3e45;
    padding:10px;
    display:inline-block;
    margin:0 1vw 0 5vw;
    min-width:200px;
}

#content{
    display:inline-block;
}

.article-img{
    position:absolute;
    top:10px;
    width:75vw;
    height:auto;
  border: 1px solid black;
}

Menu 1

Menu 2

Menu 3

Menu 4

Lorem ipsum etc

How can I change it so that it keeps on looking like it does now but the article moves down if the image gets bigger?

A: Per your comment, this will get it so that the box under the image doesn't get hidden by the image.
#about-wrapper{
  white-space:nowrap;
  margin-top:10px;
}

#box{
  border:1px solid #ba3e45;
  padding:10px;
  display:inline-block;
  vertical-align: top;
    margin:0 1vw 0 5vw;
    min-width:200px;
}

#content{
    display:inline-block;
    vertical-align: top;
}

.article-img{
  top:10px;
  min-width: 100%;
  height:auto;
  border: 1px solid black;
}

However, you'll probably want to take a look at other options if you want a layout like:
[ #box width:200px ] [ #content width: always take up rest of page ]
once you have that, you can mess about with the image container and stuff from there, the main issue w/ your original implementation was the absolute positioning.


text:
Q: Add workaround for old Firefox "beforeunload" bug that makes it prompt twice when closing a window with unsaved changes There is an old 2005 bug in the Firefox based browsers that makes the confirmation dialog show up twice when closing a window which had some data entered.
The "beforeunload" event happens twice, the second time can be ignored.
There are questions/answers on stackoverflow.com about that and the fix is to add a flag that you set to false, so the second attempt is ignored. A timer is used to reset the flag in case the user decides to stay on the page.
There is a copy of my own implementation in my Snap! editor:
snapwebsites.Editor.prototype.initUnload_ = function()
{
    var that = this;
    jQuery(window).bind("beforeunload", function()
        {
            return that.unload_();
        });
};

snapwebsites.Editor.prototype.unload_ = function()
{
    var key,                // loop index
        that = this;        // this pointer in the closure function

    if(!this.unloadCalled_)
    {
        for(key in this.editorForms_)
        {
            if(this.editorForms_.hasOwnProperty(key))
            {
                if(this.editorForms_[key].toBeSaved()
                && this.editorForms_[key].wasModified(true))
                {
                    // add this flag and timeout to avoid a double
                    // "are you sure?" under Firefox browsers
                    this.unloadCalled_ = true;

                    // we create a function in a for() loop because
                    // right after that statement we return
                    setTimeout(function(){
                            that.unloadCalled_ = false;
                        }, 20);

                    // TODO: translation
                    //       (although it doesn't show up in Firefox based
                    //       browsers many others do show this message)
                    return "You made changes to this page! Click Cancel to avoid closing the window and Save your changes first.";
                }
            }
        }
    }

    return;
};

(For more of that source code, it is available in git on SourceForget.net: https://sourceforge.net/p/snapcpp/code/ci/master/tree/snapwebsites/plugins/editor/)
As you can see I use a flag, this.unloadCalled_, which I set to true when I first return. I reset the flag in the timeout function. The 20 in there could even be zero (0). Just to be safe I kept a larger number, but it worked for me with zero.
The reason for the double request is because Firefox considered the closure of the window and the one of the tab (something like that, I read that in a bug report on mozilla.com).


text:
Q: Loading a specific bootstrap tab I have a tab system in my view folder and i need to load a specific tab when the page loads.
I know this exact question has been asked here Twitter Bootstrap Tabs: Go to Specific Tab on Page Reload or Hyperlink
but everything i've tried hasn't worked. Ultamitly i want to load a tab depending on what link is pressed but right now i am just trying to load a specific tab off the start.
in my view file I have

and my tab system looks like this

Basic Computer Skills

Advanced Computer Skills

Multi-Media Skills

Word Processing Skills

Spreadsheet Skills

Presentation Skills

Email Skills

Internet/Network Skills

Social Media Skills

Online Collaboration

I know there are lots of posts on how to do this and bootstrap has their own javascript on their site but nothing has worked. Does anyone know what i could be doing wrong?
Also, my tabs work when i click on them so i don't think its a syntax error. Just all my attempts to make it load a specific tab has failed. I know about class = "active" but that doesn't help me for my end goal.
I am also using the gems
gem 'twitter-bootstrap-rails'
gem 'bootstrap-will_paginate', '0.0.9'
gem 'bootstrap-sass', '3'

A: You can use this function:
$(function () {

       $('ul.nav a.classtobeloaded').tab('show')

 })


text:
Q: Basic Questions about C++ & named pipes I'm trying to do some inter program data exchange and I decided to play a bit with named pipes.
I have a very basic reader and a very basic writer, taken from the example answer here.

*

*My first problem is that I cannot use two time write(...) unless I let the program sleep. Is there a way around that?
Having it call sleep(1) after every entry will explode the process time.

*I would also like to have more than one process write into the same fifo. Is that possible? My attempts returned quite a few issues...

*Finally is there a way to have a fifo carry an object instead of a string?

A: 1) Writing - check the result of the write.  If the other end of the pipe is not open, the number of bytes written will be 0.
2) Not possible but you can have one server fifo for receiving requests.  It then generates a pipe name for each client process to connect to and sends it to the client.  The client reads the server pipe, closes the server pipe and opens a pipe with the new name given by the server.  The server will have to poll all the pipes in separate threads.
3) It is just a write - it can take anything.  Just dump the whole object in binary.  Note that there should not be any pointers in the object as the pointers will not be pointing to the same address space.


text:
Q: Training data in S3 in AWS Sagemaker I've uploaded my own Jupyter notebook to Sagemaker, and am trying to create an iterator for my training / validation data which is in S3, as follow:
train = mx.io.ImageRecordIter(
        path_imgrec         = 's3://bucket-name/train.rec' …… )

I receive the following exception:
MXNetError: [04:33:32] src/io/s3_filesys.cc:899: Need to set enviroment variable AWS_SECRET_ACCESS_KEY to use S3

I've checked that the IAM role attached with this notebook instance has S3 access. Any clues on what might be needed to fix this?

A: If your IAM roles are setup correctly, then you need to download the file to the Sagemaker instance first and then work on it. Here's how:
# Import roles
import sagemaker
role = sagemaker.get_execution_role()

# Download file locally
s3 = boto3.resource('s3')
s3.Bucket(bucket).download_file('your_training_s3_file.rec', 'training.rec')

#Access locally
train = mx.io.ImageRecordIter(path_imgrec='training.rec' …… )


text:
Q: Three Fundamental Principles How many different pizzas can be ordered if a pizza can be selected with any combination of the following ingredients: anchovies, ham, mushrooms, olives, onion, pepperoni, and sausage?
Can someone give me a hint to this question.

A: Hint: a pizza corresponds to a set of ingredients. How many sets that are subsets of $\{1,2,...,7\}$ exist ? (each number represents an ingredient).
If you don't know how to compute this, here is a hint: For each ingredient you have two choices: put it or not put it (that is the question). So your total number of choices is the combination of all these individual choices.
Don't forget the special case of $\emptyset$ which is counted here, so if you consider that "no topping" is not a valid pizza then you should substract one to the formula.


text:
Q: How to output the members of list items? I'm a newbie in the C# and .NET at all.
So, I have a collection that contains objects
private List<object> trains = new List<object>();
...
trains.Add(trains[0]);
trains.Add(trains[1]);
trains.Add(trains[2]);
trains.Add(trains[3]);
trains.Add(trains[4]);

And later in my code I must to input all elements of my collection
I'm trying something like that, but it doesn't work
public void Display()
{
    ...
    for (int i = 0; i<trains.Count; i++)
    {
        Console.WriteLine(trains[i].Number);
        Console.WriteLine(trains[i].Destination);
    }
}

Help me please, I'm really dont understand how to input it to the console. I read Microsoft documentation about the "List" but :(

A: You have a list of objects. And object class doesn't have those members (Number and Destination). If you wanna access them either you need to cast your objects to your type or have a list of Train instead of object.

A: Currently you are storing your objects in a List<object>, Since your class (probably named) Train inherit from Object, you can store its object in object. You need List<Train> and then you can access each member property like:
private List<Train> trains = new List<Train>();

If you can do that for some reason then you have to explicitly cast your object to Train like:
Console.WriteLine(((Train)(trains[i])).Number);

A: Assuming this
class Train
{
    public int Number { get; set; }
    public string Destination { get; set; }
}

And that you are doing something like this:
var t1 = new Train();
t1.Number = 1;
t1.Destination = "somewhere";
var t2 = new Train();
t2.Number = 2;
t2.Destination = "somewhereelse";
trains.Add(t1);
trains.Add(t2);

Than you can output using this:
Train train;
foreach(object t in trains)
{
    if ((train = t as Train) != null)
    {
        Console.WriteLine(t.Number);
        Console.WriteLine(t.Destination);
    }
}

The advantage of using a list of objects is that you can put "anything" there. Not only "Train". But as pointed by @Chris, foreach do not filter, so you have to filter it yourself.

A: To access the Train object directly, you will need to cast the generic object to a Train object prior to referencing it's exposed properties.  This can be done on the fly, it's not necessary to declare the extra variable myTrain here, however for sake of clarity and readability, I generally do it like this.
public void Display()
{
    ...
    for (int i = 0; i<trains.Count; i++)
    {
        Train myTrain = (Train)trains[i];
        Console.WriteLine(myTrain.Number);
        Console.WriteLine(myTrain.Destination);
    }
}

Others have mentioned and I would agree, I can think of very few situations where you would NEED to use a:
List<object>();

rather than:
List<Train>();

The only thing that jumps out at me would be if you might be storing non Train objects in the same list with Train objects but I cannot think of a good reason to do something like that off the top of my head.


text:
Q: Calling a function in Agda I have this code which is basically a hello world, with an addition function, it compiles and runs and outputs 'Hello, world 5!':
open import Common.IO

data  ℕ  : Set  where
 zero  : ℕ
 suc   : ℕ → ℕ

-- how to call a function in agda i.e. '_+_(5, 4)' to get '9'

_+_   :  ℕ → ℕ → ℕ
zero + m = m
suc n + m = suc (n  + m)

main = putStrLn "Hello, world 5!"

How do I call my _+_ function? My goal is to call _+_ with two arguments like _+_(3,4) and get the program to output seven.
My intuition says to replace the line ' main = putStrLn "Hello, world 5!"' with something like 'putStrLn _+_(3,4)'
I'm new to Agda, and there aren't many examples online of working code. Can anybody get this function working by giving a practical code example?
Thanks!

A: open import Common.IO
open import Data.Nat using (ℕ; zero; suc)
open import Data.Integer using (ℤ; +_; show)
open import Data.String using (_++_)

_+_ : ℕ → ℕ → ℕ
zero  + m = m
suc n + m = suc (n + m)

main = putStrLn ("Hello, world " ++ show (+ (3 + 4)) ++ "!")


text:
Q: call meteor core packages method from client I am new to meteor and I could not understand that how methods are imported in Meteor. The methods that are starting with
    Meteor.methodName,
how to call these methods from client if they are exposed in server.
I have a method called Meteor.loginWithpassword in meteor package livechat / livechat.js.
Its package.js file looks like this:
Package.onUse(function(api) {
              api.versionsFrom('1.0');
              api.addFiles('livechat.js', 'server');

}
Now I want to call Method loginWithPassword method from client.How to achieve this??


text:
Q: How would I be able to input a string on a search bar? I'm programming in C and got my program to open up a search engine (Microsoft Edge), but I still can't figure out how to get the user's input to be entered in the search bar. I'm wondering if there's an easy way to accomplish my goal?

Here's my code:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>

#define size 100

int main(){
    // Not sure if I should use (int argc, char **argv, char **envp)

    char input[size];

    Printf("Please input your search!");
    scanf("%s", &input);

    system("\"\"c:\\program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe\" \"www.google.com\"\"");

return 0;
}


text:
Q: Conversion of Access desktop database to Access web database I require help on below:

*

*I am trying to compile a Report from a Access form by entering values separated using comma and at the click of a button,a Report should be exported for those values. otherwise we will have to look out manually for 100 such records daily.

*I want to update the status for selected records by using records selectors, where I will select few and change the Cheque status Combo box from the form header.

*Currently I am building it as an desktop database. How to convert it as Web database and share it on the web?

A: The first issue to deal with is #3. There is no technology that exists today that can take a typical car and convert that car into say an airplane. In other words, unless the car is designed from the ground up to fly, then the car will not fly. This issue of converting desktop applications is not restricted to Access, but really quite much any and all desktop development systems (they are the WRONG TOOL if you wish to build a web application).
So if you going to build an airplane, then you want and need to design the thing you are building as an aircraft.
Thus if you going to build a web application, then you want and need to design the application as web based FROM THE START. No conversion of the desktop applications to web exists. You could however consider having the desktop application run on a server via Terminal services and have the client desktops thus use RDP, or even utilize a RDP to HTML5 bridge. However without knowing what service providers you plan to choose or have now, such answers are much speculation.
So you need to create and start with a web based application if using Access. You also then need to determine who to use for web  hosting (since VERY few support access web services). And fewer support reports for Access. For example with Access web publishing to office 365 on-line the setup currently does not support reports. However if you have your own SharePoint server, then you can build reports with Access web development (Access web 2010 only – 2013,2016 don't support web reports).
A discussion of web development on a simple post here is not practical – such answers as to how to build and deploy a web based application would take 100's of pages for a proper response. (however there is this thing called google – you need to do some reading on web development).
As for updating records by using selectors? That is difficult in desktop, and even more of a challenge for Access web. A far more simple approach would be to add a check box column to the continues form, allow the user to check the rows, and then setup some code to process those rows. (for Access web, that would mean your form would call a data macro that then processes the rows that have the checkbox column marked as true).
Same goes for filtering a web report by comma separated values. For desktop, you can use the SQL "in" clause and thus create a report "where" clause. However for web based, you don't have use of the sql "in" command, so a different approach will be required. I would suggest perhaps setting up a form with a sub form, and you thus can type in each number on a separate row of the sub form – this then could be processed.
Last but not least:
If you going to start web development with Access, it is strongly recommended that you use Access 2013 for web development, as they significantly changed how Access web development works, and there is thus no migration from Access web 2010 to web 2013.


text:
Q: Prove that if $f(n) ∈ Θ(g(n))$ and $g(n) ∈ Θ(h(n))$ then $f(n) ∈ Θ(h(n))$. I know that by the assumption that $f ∈ Θ(g)$ we know that there exist constants $c_0$ and $c_1$ in $\mathbb R^+$, and there exists $n_0 ∈ \mathbb N$ such that:
$$c_0 \cdot g(n)\le f(n)\le c_1 \cdot g(n),$$
but this is then where I get stuck, can anyone help me out?

A: Try this:
$$
c_2 g(n) \leq f(n) \leq c_1 g(n)\\
c_4h(n) \leq g(n) \leq c_3 h(n)
$$
Now plug in the bounds for $g(n)$ in the first inequality:
$$
c_2 c_4 h(n) \leq f(n) \leq c_1 c_3 h(n)
$$
Since $c1 \cdot c3=c'$ and $c2 \cdot c4=c''$ are both constants:
$$
f(n)=\Theta (h(n))
$$


text:
Q: Why only first page data could get when using selenium? I use the python package selenium to click the "load more" button automatically, which is successful. But why do I cannot get data after "load more"?
I want to crawl reviews from HP.com using python. It only displays few monitors until I click "load more" button. I use the python package selenium to click the "load more" button automatically, which is successful. But why do I cannot get data after "load more" and just get the first page data repeatedly?
And I tried to use "wait.until(EC.invisibility_of_element_located)" but it didn't run whatever I use... so I chose hardcode like waiting specific seconds. If anyone can help to find how to recode, it'll be super appreciated....

from selenium import webdriver
import time

url = "https://www.hp.com/us-en/shop/plp/accessories/computer-monitors"
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36"}

browser = webdriver.Chrome("C:\Python310\chromedriver.exe")
browser.maximize_window()
browser.get("https://www.hp.com/us-en/shop/plp/accessories/computer-monitors")

loadmore = browser.find_element_by_css_selector('#content > div.clearfix.vwa > div.product-results.product-results.left-menu-open > div.search-results > span')

count = 0
while count < 5:
    browser.execute_script("window.scrollTo(0, document.body.scrollHeight)")
    time.sleep(3)
    loadmore.click()
    time.sleep(3)
    count+=1

import requests
import re
from bs4 import BeautifulSoup

res = requests.get(url, headers=headers)
res.raise_for_status()

soup = BeautifulSoup(res.text, "lxml")
prods = soup.find_all("a", attrs={"class":"product-title pdp-link"})
for prod in prods :
    print(prod.get_text())

A: headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36"}

options = Options()
options.add_argument(f'user-agent={headers}')
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()),options=options)
#Service("C:\Python310\chromedriver.exe") also works here
driver.maximize_window()
wait=WebDriverWait(driver,10)
driver.get("https://www.hp.com/us-en/shop/plp/accessories/computer-monitors")
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,"a.caclose"))).click()

count=0
while count<5:
    try:
        wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,"span.search-load-more"))).click()
        count+=1
    except Exception as e:
        print(str(e))
        break

texts=[x.text for x in wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR,"a.product-title.pdp-link")))]
print(texts)

There's an element proceeding from my region's site so I closed it.
If you want to click the load more 5 times or just use while True for until it disappears. Then grab all the text just wait for visibility and use .text.
Imports:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager

Outputs:
['HP M24FW FHD MONITOR', 'HP M27F FHD MONITOR', 'HP M24F FHD MONITOR', 'HP V241IB FHD MONITOR', 'HP 27F 27-INCH 4K DISPLAY', 'HP V24 FHD MONITOR', 'HP P22H G4 FHD MONITOR', 'HP U28 4K HDR MONITOR', 'HP Z24U G3 WUXGA USB-C DISPLAY', 'HP V20 HD+ MONITOR', 'HP E27 G4 FHD MONITOR', 'HP E24Q G4 QHD MONITOR', 'HP 27MQ 27-INCH MONITOR', 'HP E27U G4 QHD USB-C MONITOR', 'HP U27 4K WIRELESS MONITOR', 'HP M27FD FHD MONITOR', 'HP X34 WQHD GAMING MONITOR', 'HP X27C FHD GAMING MONITOR', 'HP X32C FHD GAMING MONITOR']

A: When you access this site with a fresh browser, after a delay, a dialog asking you to accept their privacy policy will appear. So the solution is to wait for and click the accept button before trying to click on load more.
wait = WebDriverWait(self.driver, 10)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,"button#onetrust-accept-btn-handler"))).click()

For this code to work you need to add the following imports:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

Here is a runnable example I made


text:
Q: Is there a way to add more image url in set_image? @client.command()
async def hug(ctx, *, user: discord.Member = None):

    hug_embed = discord.Embed(
        title=f'❤ {ctx.author.display_name} hugged {user.display_name} ❤',
        description=' ',
        color=0xcce5ff)
    hug_embed.set_image(
        url=
        'https://cdn.discordapp.com/attachments/787005334560309269/850480213111341056/hug_ghot.gif'
    )
    hug_embed.set_footer(text='hi')

    if user:
        await ctx.message.channel.send(embed=hug_embed)
    else:
        await ctx.send('hug someone ;n;')

Is there a way to add more image URLs, and when people run the command it displays a random one every time?
eg. https://media.discordapp.net/attachments/759127214745845774/850148274262507520/cat_hug.gif

A: import random
image_list = ["url", "url2", "url3", etc.]

inside command:
hug_embed.set_image(
    url=random.choice(image_list)
)

choice will randomly pick an element of image_list to set as the image URL


text:
Q: Graph API vs FQL which is faster? just wondering when it comes to just the basic GET/POST.
(i.e something simple as getting the users profile and not something complicated like getting a pictures from every album)
which is faster?
Graph or FQL.
i know FQL is newer than graph, but unsure if its more efficient.

A: I ran a simple test (getting the cover photo id) using the PHP SDK :
public $microtime_start = 0;

public function getExecutionTime() {
    return round(microtime(true) - $this->microtime_start, 4);
}

public function getFQL($request, $filter = true, $multiFilter = true) {
    if(is_array($request)) {
        $query = '{';
        foreach ($request as $key => $q) {
            $query .= '"'.urlencode($key).'":"'.urlencode(addslashes($q)).'",';
        }
        $query = substr($query, 0, -1).'}';
        $data = $this->callAPI('/fql?q=' . $query);
        if($filter) {
            $data = $data['data'];
            if($multiFilter) {
                $data = $data[count($data)-1]['fql_result_set'];
            }
            return $data;
        }
    } else {
        $data = $this->callAPI('/fql?q=' . urlencode($request));
        if($filter) {
            return $data['data'];
        }
    }
}

public function callAPI($path) {
    $params = array('access_token' => $this->getAccessToken());
    return $this->api($path, 'GET', $params);
}

public function getCoverPhotoId($uid) {
    $time = $this->getExecutionTime();

    $albums = $this->api("/me/albums");
    $album_id = "";
    foreach ($albums["data"] as $item) {
        if ($item["name"] == "Cover Photos") {
            $album_id = $item["id"];
            $profile_picture_id = $item["cover_photo"];
            break;
        }
    }
    $time2 = $this->getExecutionTime();
    echo 'graph api: '.($time2 - $time).'
';

    $data = $this->getFQL(array(
        'query1' => 'SELECT cover_object_id FROM album WHERE owner = ' . $uid.' AND name = "Cover Photos"'
    ));
    $time3 = $this->getExecutionTime();
    echo 'graph api with FQL: '.($time3 - $time2).'
';

    $data = $this->api(
            array(
                'method' => 'fql.query',
                'query' => 'SELECT cover_object_id FROM album WHERE owner = ' . $uid.' AND name = "Cover Photos"'
            )
    );

    $time4 = $this->getExecutionTime();
    echo 'FQL via rest api: '.($time4 - $time3).'
';
}

Results :

graph api: 1.28320002556
graph api with FQL: 0.744100093842
FQL via rest api: 0.544199943542

The basic FQL is much faster, the FQL via graph api is ok, but graph api is waaay too slow... And you will get a bunch of useless stuff with the graph api

A: It's in no way comparable like this. While you can get same data (in some cases) from both
their intents are completely different: FQL is a query language, Graph is an API.
Calling to FQL query if using new JS SDK is a Graph API call itself...
You can (and probably should, if you worry about real comparison and not theoretical speculation) compare speed of calls returning same data but you should take into account some things:

*

*Graph API still sucks at data filtering conditions and aggregation of data

*FQL just can't provide you too many of functionality required in today's applications (like Real-Time updates)

*Graph API have an ability batch calls, which may speed up things a lot, this also can be used to call fql.query and fql.multiquery (in a bit cumbersome way).

*Graph API rocks at data filtering with Field Expansion
Consider following example from FQL documentation, subquery that fetches all user information for the active user and friends:
SELECT uid, name, pic_square FROM user WHERE uid = me()
OR uid IN (SELECT uid2 FROM friend WHERE uid1 = me())

This simply not possible to achieve with a single Graph API call. (see Update)
Once you define desired subset of data to get you can choose appropriate method of retrieval based on your requirements.
BTW, FQL is much older than Graph, we had it aside to FBML (rip) and FBJS (rip)
Update:
Graph API providing way for Batch Requests and specifying dependencies between operations in the request. For example same sample as above can be achieved in a single call to Graph API
POST https://graph.facebook.com/
POST Data:
batch=[
  {
    "method": "GET",
    "name" : "get-friends",
    "relative_url": "me/friends?fields=id",
  },
  {
    "method": "GET",
    "relative_url": "?ids={result=get-friends:$.data.*.id}&fields=id,name,picture"
  }
]

Update 2:
As of 30 August 2012 Graph API is also support Field Expansion as additional (very powerful) mechanism of data retrieval (including nested data)


text:
Q: Can I insert a HTML file containing scripts and styles into another HTML (on client side)? Can I insert a HTML file containing scripts and styles into another HTML (on client side)?
I will try to elaborate a bit so it's clear what I wish to do... First of all, this will be served by an Arduino, so the whole point of this is to minimize the number of data sent on each request, and if possible have only two files (one small file that needs to be loaded on every request, and one big file which should be loaded only the first time, then be cached by the browser).
Currently I have something like this:
<!DOCTYPE html>
<html>
    <head>
        <style>
            Many lines of CSS...
        </style>
        <script>
            Many lines of Javascript
        </script>
    </head>
    <body>
        Many lines of HTML
    </body>

    <script type='text/javascript'>
        $(document).ready
        (
            function()
            {
                initializeStuff("1, 2, 3, 4, 5, 6, 7, 8, 9");
            }
        }
    </script>
</html>

Basically, I have this big page, but the only thing that may change on each GET request is the data on the initializeStuff() function. Tin functions then updates many parts of the body with this new data.
I know the normal thing would be to have different files for CSS, JavaScript and HTML content, but if it's possible I would like to have everything in one big file. I wanted this because the Arduino is very limited in terms of connections, so if a browser starts to send many GETs in parallel most of them will fail.
So my question if there is a way to have most of the data in one big file that can be cached by the browser, so that after this file is in the cache I only need to load a really small and basic HTML file, with little more than the initializeStuff() function (and whatever else is required do reference all the other stuff in the big file)?

A: I am not sure if this will meet your requirement, but for JavaScript, you can link with external files like:
<script type="text/javascript" src="script.js"></script>

And for external stylesheets:
<link rel="stylesheet" href="stylesheet.css" />


text:
Q: How to show that $f(x) = \frac{1}{x-a}$ is real-analytic? Let $a ∈ \Bbb R$, and define $f : \Bbb R \backslash \{a\} → \Bbb R$ by $f(x) = 1/(x − a)$. Show that f is real-analytic.
I can tell that f(x) is comparible to the geometric series $\frac{1}{1-x}$ where if $g:= \Bbb R \backslash \{1\} \to \Bbb R$, $g(x)= \frac{1}{1-x}$, the function $g(x)$ is real-analytic
however I can't quite find the relationship between them and is struggling with the proof. How should I proceed?

A: Let $c \neq a$. $\frac 1 {x-a} =\frac 1 {c-a} \frac 1 {1+\frac {x-c} {c-a}}$ and you can use the expansion $\frac 1 {1+y}=\sum (-1)^{n}y^{n}$ for $|y| <1$.

A: If $a \ne 0$ we have $\frac{1}{x-a}= -\frac{1}{a} \frac{1}{\left (1- \frac x a \right )}=-\frac{1}{a} \sum\limits_{n=0}^{\infty}\frac{x^n}{a^n} =-\sum\limits_{n=0}^{\infty}\frac{x^n}{a^{n+1}}$ for $|x|<|a|.$


text:
Q: How to make a tkinter window Fullscreen on all Displays? I am working on a program with a window that needs to be fullscreen on all plugged-in Monitors and/or external displays. Is there any way I can do this in Tkinter or do I have to use a different library? So far I have managed to get the window in Fullscreen on my main display but I also need it on the other one(s). This is my code so far:
def create_screencanvas():
    global master_screen
    master_screen = Toplevel(mywindow)
    picture_frame = Frame(master_screen, background = "blue")
    picture_frame.pack(fill=BOTH, expand=YES)

    global screenCanvas
    screenCanvas = Canvas(picture_frame, cursor="cross", bg="grey5")
    screenCanvas.pack(fill=BOTH, expand=YES)

    master_screen.attributes('-fullscreen', True)#Fullscreen on main display but not others
    master_screen.attributes('-alpha', .3)
    master_screen.lift()
    master_screen.attributes("-topmost", True)

mywindow = Tk()
mywindow.title("New Project")
mywindow.geometry("780x640")
mywindow.minsize(540, 420)
mywindow.configure(bg="blue")

mybtn = Button(text="activate", command=create_screencanvas, cursor="cross")
mybtn.pack() #Button opens the fullscrean window

mywindow.mainloop()

A: For screenshot taking purposes, you can make your Toplevel window cover all the displays by changing manually its geometry instead of making it fullscreen. So, remove
master_screen.attributes('-fullscreen', True)

and replace it with
w = master_screen.winfo_screenwidth()
h = master_screen.winfo_screenheight()
master_screen.geometry(f"{w}x{h}+0+0")

However, your window now has unwanted decorations. Depending on the OS you are using, you can either use
master_screen.overrideredirect(True)

or, if you are using Linux (in which case, overrideredirect might not allow you to have window transparency),
master_screen.attributes('-type', 'dock')

In both cases, you no longer need
master_screen.attributes("-topmost", True)


text:
Q: regex for getting particular output from sentences in python I have some sentences:
[1, 23] fun(): Error Code: 1230. fun doen't exist

Error Code: 1123. Unknown column 'hhh'

END: Error Code: 2134. database doen't exist

Now my concern is i want to get output like
['Error Code: 1230. fun doesn't exist','Error Code: 1123. Unknown column 'hhh'','Error Code: 2134. database doen't exist ']

I use \sError\s this regex  , but it didn't work , i do code in python
How to make a regex for it?

A: You may use
re.findall(r'\bError Code.*', s)

Details

*

*\b - a word boundary

*Error Code - a literal substring

*.* - the rest of the line.

See the regex demo.