text:
Q: Why am I getting a fail on trying to write to plist file I have 4 NSMutableArray, and on launch they are properly initialized. In a section of my code, I write the contents of these arrays to individual plist files, and these plist files have been created and added to the project. I have 4 instances of writing to file, and for some reason only the first 2 write to file successfully (didWrite and didWrite2) but didWrite3 and didWrite 4 return "nope" all the time meaning an unsuccessful write. Here is the code that initializes and allocates the arrays in applicationDidFinishLaunching:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *DataPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Data.plist"];
    NSString *inkDatesPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"inkDates.plist"];
    NSString *inkFontPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"inkFont.plist"];
    NSString *inkColorPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"inkColor.plist"];
    NSFileManager *fileManager = [NSFileManager defaultManager];

    if (![fileManager fileExistsAtPath: DataPath])
    {
        inks=[[NSMutableArray alloc] init ];
         NSLog(@"initialized inks as new");
    }
    else inks=[[NSMutableArray alloc] initWithContentsOfFile:DataPath];

    if (![fileManager fileExistsAtPath: inkDatesPath])
    {
        inkDates=[[NSMutableArray alloc] init ];
    }
    else inkDates=[[NSMutableArray alloc] initWithContentsOfFile:inkDatesPath];

    if (![fileManager fileExistsAtPath: inkFontPath])
    {
        inkFont=[[NSMutableArray alloc] init ];
    }
    else inkFont=[[NSMutableArray alloc] initWithContentsOfFile:inkFontPath];

    if (![fileManager fileExistsAtPath: inkColorPath])
    {
        inkColor=[[NSMutableArray alloc] init ];
        NSLog(@"initialized inkColor as new");
    }
    else {
        inkColor=[[NSMutableArray alloc] initWithContentsOfFile:inkColorPath];
        NSLog(@"initialized inkColor as copy");

When the app is first launched, I get "initialized inkColor as new", but I still get a fail to write. inks and inkDates write properly but the other two dont. And here is my code that tries to write to the plist files:
  NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
    NSString *documentsDirectory = [paths objectAtIndex:0]; //2

    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Data.plist"]; //3
    NSFileManager *fileManager = [NSFileManager defaultManager];

    if (![fileManager fileExistsAtPath: path])
    {
        NSString *bundle=[[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"];
        [fileManager copyItemAtPath:bundle toPath: path error:&error]; //6
    }

    NSString *pathDates = [documentsDirectory stringByAppendingPathComponent:@"inkDates.plist"]; //3
    NSFileManager *fileManagerDates = [NSFileManager defaultManager];

    if (![fileManagerDates fileExistsAtPath: pathDates])
    {
        NSString *bundle=[[NSBundle mainBundle] pathForResource:@"inkDates" ofType:@"plist"];
        [fileManagerDates copyItemAtPath:bundle toPath: pathDates error:&error]; //6
    }

    NSFileManager *fileManagerFont = [NSFileManager defaultManager];
    NSString *pathFont = [documentsDirectory stringByAppendingPathComponent:@"inkFont.plist"];
    if (![fileManagerFont fileExistsAtPath: pathFont])
    {
        NSString *bundle=[[NSBundle mainBundle] pathForResource:@"inkFont" ofType:@"plist"];
        [fileManagerFont copyItemAtPath:bundle toPath: pathFont error:&error]; //6
    }

    NSFileManager *fileManagerColor = [NSFileManager defaultManager];
    NSString *pathColor = [documentsDirectory stringByAppendingPathComponent:@"inkColor.plist"];
    if (![fileManagerFont fileExistsAtPath: pathColor])
    {
        NSString *bundle=[[NSBundle mainBundle] pathForResource:@"inkColor" ofType:@"plist"];
        [fileManagerColor copyItemAtPath:bundle toPath: pathColor error:&error]; //6
    }

    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"EEEE, MMMM d, YYYY"];
    NSString *dateString = [dateFormat stringFromDate:date];
    [dateFormat release];

            [appDelegate.inks addObject:[inkTextField text]];
            [appDelegate.inkDates addObject:dateString];
            [appDelegate.inkFont addObject:[inkTextField font]];
            [appDelegate.inkColor addObject:[inkTextField textColor]];
            NSLog(@"inkColor count: %i", [appDelegate.inkColor count]);
            NSLog(@"Wrote to new index");

    BOOL didWrite=[appDelegate.inks writeToFile: path atomically:YES];
    if(didWrite==YES)
       NSLog(@"didWrite");
    else NSLog(@"nope");

    BOOL didWrite2;
    didWrite2=[appDelegate.inkDates writeToFile: pathDates atomically:YES];
    if(didWrite2==YES)
        NSLog(@"didWrite");
    else NSLog(@"nope");

    BOOL didWrite3;
    didWrite3=[appDelegate.inkFont writeToFile: pathFont atomically:YES];
    if(didWrite3==YES)
        NSLog(@"didWrite");
    else NSLog(@"nope");

    BOOL didWrite4;
    didWrite4=[appDelegate.inkColor writeToFile: pathColor atomically:YES];
    if(didWrite4==YES)
        NSLog(@"didWrite");
    else NSLog(@"nope");

A: You are using writeToFile which attempts to write proper plists. Its documentation states:

This method recursively validates that all the contained objects are
  property list objects (instances of NSData, NSDate, NSNumber,
  NSString, NSArray, or NSDictionary) before writing out the file, and
  returns NO if all the objects are not property list objects, since the
  resultant file would not be a valid property list.
If the dictionary's contents are all property list objects, the file
  written by this method can be used to initialize a new dictionary with
  the class method dictionaryWithContentsOfFile: or the instance method
  initWithContentsOfFile:.

UIColor and UIFont are not in the list.
Generally you might want to use the NSCoding protocol (using NSCoder objects) instead which allows you to serialize data more effectively. However, even then there is no good way to store UIFont objects - they don't conform to NSCoding and cannot be serialized. You should store the font family/size and then have custom code to restore the font when loading the data.


text:
Q: MySQL SELECT * optimization Is there a reason why there is enormous difference between
1. SELECT * FROM data;      -- 45000 rows
2. SELECT data.* FROM data; -- 45000 rows

SHOW PROFILES;
+----------+------------+-------------------------+
| Query_ID | Duration   | Query                   |
+----------+------------+-------------------------+
|        1 | 0.10902800 | SELECT * FROM data      |
|        2 | 0.11139200 | SELECT data.* FROM data |
+----------+------------+-------------------------+
2 rows in set, 1 warning (0.00 sec)

As far as I know it, they both return the same number of rows and columns. Why the disparity in duration?
MySQL version 5.6.29

A: That's not much difference.  Neither are optimized.  Both do full table scans.  Both will parse to the optimizer the same.  You are talking about fractions of milliseconds difference.
You can't optimize full table scans.  The problem is not "select " or "select data.".  The problem is that there is no "where" clause, because that's where optimization starts.

A: The particular examples specified would return the same result and have the same performance.
[TableName].[column] is usually used to pinpoint the table you wish to use when two tables a present in a join or a complex statement and you want to define which column to use out of the two with the same name.
It's most common use is in a join though, for a basic statement such as the one above there is no difference and the output will be the same.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Panda Columns are Inexplicable Reversed This question may be a little obscure.  (Note: I am using python's Pandas library to extract some text data from .csv files.  I know that Pandas wasn't built for text, but I find it's far more intuitive than the csv lib.)
Here's my problem.
I have two files -- files A & B -- each with three columns, which appear in the exact same order in the csv files themselves.  The columns are X, Y, & Z.
colnames = ['X', 'Y','Z']
data = pandas.read_csv('C:...path...\File_A.csv', names=colnames)

col_x = list(data.X)
col_y = list(data.Y)
col_z = list(data.Z)

When I open and print the contents of File_B (i.e., placing File_B in the read_csv line instead of File_A), columns col_x & col_y are reversed.  In other words, if I print each col_x item for File_A, it shows the contents of col_x, but when I print col_x for File_B it shows the contents of col_y.
The columns are inexplicably reversed, and this is stopping me from abstracting the problem I'm trying to solve, since I have to change the scripts' functionality depending on which file I open.  Does anyone know why X & Y would be reversed in the different files?  The csv files themselves have the exact same column order -- X,Y,Z -- so I believe the problem is in the Pandas library or my script.  Any help would be hugely appreciated.  Thanks!


text:
Q: Laravel 5 adding HTML to email I'm currently trying to create a HTML email in Laravel 5 and I have some text (which contains
 elements) I want to insert in the email. I use the following piece of code to send the email:
Mail::send(array('html' => 'emails.newinvoice'), array('text' => $emailtext), function($message) use ($email, $subject, $contact_company)
{
    $message->to($email, $contact_company)->subject($subject);
});

So the $emailtext variable contains some text with HTML tags. In my emails.newinvoice layout view, I have the following:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

{{{ $text }}}

When sending the email, the inserted text in my mail and the HTML elements in that text are displayed as normal characters which means that my email shows up like:
test
test

Instead of
test
test

How can I make sure that the HTML tags in the inserted text get rendered as HTML and not as plain text?

A: You need to specify html key in the first parameter:
Mail::send( ['html' => 'emails.newinvoice'], ['text' => $emailtext],
//           ^^^^

Also replace auto-escaped block {{ }} with unescaped {!! !!} in the template:

 {!! $text !!}

A: Yeah the solution above work just fine..
use {!! $contents !!}
instead of this
{{ $contents }}

This {!! $contents !!} is for allowing html
While this {{ $contents }} is just for plain text.

A: You need to use:
{!! $text !!}

instead of
{{ $text }}

Blade automatically escapes any html when echoing unless you explicitly tell it not to.

A: After checking various solutions, following codes worked for me -
 try {
      $template_data = ['otp' => $otp, 'name' => $name];
      //send verification code
      Mail::send(['html' => 'email.account_verification'], $template_data,
                function ($message) use ($email) {
                   $message->to($email)
                   ->from('test@yourdamin.com') //not sure why I have to add this
                   ->subject('Account verification');
      });

      return Response::json(['code' => 200, 'msg' => 'Sent successfully']);

      } catch (Exception $ex) {
            return Response::json(['code' => 200, 'msg' => 'Something went wrong, please try later.']);
      }

A: If you are using ShouldQueue to send email, you should run the command 'php artisan queue:work' again, then you run your app again. After that, you check the receiver email, you can see the email content displayed in html format.


text:
Q: Populate second dropdown based on the value selected in the first dropdown in flask using ajax and jQuery I am not getting anywhere on this. Any help regarding this would be greatly appreciated!
I have two dropdowns for Managers and Employees.
Managers dropdown contains a list of Managers by default.
I want to populate Employees dropdown with the employees name by querying a SQL Server database with the Manager name a user selects in Managers dropdown.
So for e.g. if a person selects Tom as the Manager in the Managers dropdown then the Employees dropdown should populate with the Employees name where Manager = Tom.
So far I have the following code:
Route (which I am using to query SQL Server database to get employees list based on a manager name):
@app.route ('/getEmployees', methods=['GET'])
def getEmployees():
    engine = create_engine('mssql+pyodbc://<server name>/<DB name>?driver=SQL+Server+Native+Client+11.0')
    Base = declarative_base(engine)

    class Bookmarks(Base):
        __tablename__ = '
'
        Employee = Column(String(50))
        __table_args__ = {'autoload': True}

        def __repr__(self):
            return '{} '.format(self.Employee)

    def loadSession():
        metadata = Base.metadata
        Session = sessionmaker(bind=engine)
        session = Session()
        return session
    if __name__ == "__main__":
        session = loadSession()
        return session.query(Bookmarks).filter_by(Manager='')

Managers dropdown in index.html

  <select class="form-control" id="next" name="division" data-error="Required!" required>
    <option value="default" disabled selected>Select something</option>
    <option value="option1">Tom</option>
    <option value="option2">Bob</option>
  </select>

Employees dropdown in app.py
Employees = QuerySelectField('Employees', query_factory=getEmployees, allow_blank=True)

In index.html

    {{ render_field(form.Employees,class="form-control", required="required") }}

I am using jQuery with ajax to get the Manager name a user selects in the manager dropdown and then do something with it..
$(document).ready(function(){

    $("#next").change(function() {

        var Manager=($('#next option:selected').text());
        console.log(Manager);

        $.ajax({
            url: "/getEmployees",
            type: 'GET',
            contentType: 'application/json',
            dataType: 'json',
            // not sure what to do next..?
        });
    });
});

Can anyone please help as what I should do next once I have the value a user selects in Managers dropdown?

A: I think you're almost there. I don't know python or flask, but I can give you the main idea.

*

*When you select the manager, you get the manager name and you have to send that name in the ajax call, so you can get it in your Route code and use it to filter the array. You can send that value using the data parameter of the ajax call...
$(document).ready(function(){

    $("select#next").change(function() {

        var managerName = $(this).find('option:selected').text();

        $.ajax({
            type: 'GET',
            url: "/getEmployees",
            data: { manager: managerName }
            contentType: 'application/json',
            dataType: 'json'
        });
    });
});

*In your ajax call, create a success callback function that will be called when you receive a successful response. Something like this...
$(document).ready(function(){

    $("select#next").change(function() {

        var managerName = $(this).find('option:selected').text();

        $.ajax({
            type: 'GET',
            url: "/getEmployees",,
            data: { manager: managerName }
            contentType: 'application/json',
            dataType: 'json',
            success: function(response) {
            }
        });
    });
});

*You could also add a check to verify if you've selected manager or unselected. In case you unselect manager, you have can empty the employee select, disable it, show all employees, or whatever you want.
$(document).ready(function(){

    $("select#next").change(function() {

        if ($(this).val() != 'default') {

            var managerName = $(this).find('option:selected').text();

            $.ajax({
                type: 'GET',
                url: "/getEmployees",,
                data: { manager: managerName }
                contentType: 'application/json',
                dataType: 'json',
                success: function(response) {
                }
            });
        }
        else {  // No manager selected.
            // Do what you wnat when there's no manager selected.
            // For example, if you'd want to empty and disable the employees select...
            $('select#sel_user').html('').prop('disabled',true);
        }
    });
});

Now is where I have problems to help you, because of my lack of knowledge of python/flask:

*

*In your Route code, you have to read the manager parameter sended with the GET ajax call. I don't know how you do that in python/flask but it has to be easy. In php would be just $_GET['manager']. With a quick search, it looks like it could be something like request.GET['username'], but you'll know it way better than me. You have to get that parameter and put that value in the last return line, something like...
return session.query(Bookmarks).filter_by(Manager=request.GET['username'])

*Is not clear to me the format of this response, so I don't know how to extract the info to create the employees select. Looking at your ajax call, you say the response is in JSON format, but I would need to see an example of that response to shw you the exact code. The idea is that you have to get that info and create the options in the success function of the ajax call, and then put that options in the employees select. Something like...
// Imagine that your response is an array of objects similar to this
// [{"name": "Tommy", "other": "value10"},{"name": "Jim", "other": "value32"},...]

success: function(response) {

    var options = [];
    for (var i=0, l=response.length; i<l; i++)
        options.push('<options value="'+response[i].other+'">'+response[i].name+'<options>');

    $('select#sel_user').html(options.join(''));
}

I think with all this you can have an idea of how to proceed, adapting it to your specific needs. I hope it helps.

A: Using AJAX/Jquery
You can do something like this,
You have two dropdown selects, one as the manager select and the second is the employee select , the employee select dropdown values depends on the manager select
1st select dropdown,
<select id="manager_select">
</select>

<select id="employee_select">
</select>

/* This will populate your managerselect */
$.ajax({
    url: 'url that will display all list'
    dataType: 'json',
    type: 'get',
    success: function(data){
      var output = "";
       $.each(data, function(a,b){
          output += "<option value='"+b.id+"'>"+b.manager_select_name+"  </option>"
        $("#manager_select").append(output);
       });
    }
})

/* This will populate your employee select upon changing the values of your manager*/
$(document).on("change", "#manager_select", function(){
  var manager_id = $(this).attr("id");
 $.ajax({
     url: 'url that will display employee data where manager_id = manager_id ',
     type: 'POST',
     dataType: 'json',
     data: { 'manager_id' : manager_id } /* you are passing manager_id*/
     success: function(data){
          $("#employee_select").empty();
          var output = "";
          $.each(data, function(a,b){
              output += "<option id="+b.employee_id+">"+b.employee_desc+"</option>";
          })
          $("#employee_select").append(output);
     }
 })

})


text:
Q: How to optimize update_all calls Currently, I'm doing the update_all with concatenation like this:
collection.update_all(flag: false)
collection.update_all(["description = CONCAT(description, ?)", 'not_available'])

Is it possible to do it at once?
Obviously, this construction doesn't work:
collection.udpate_all(flag: false, ["description = CONCAT(description, ?)", 'not_available'])

A: update_all can take array, so you should be able to do something like this:
collection.udpate_all([
  "description = CONCAT(description, ?)", flag = ?,
  'not_available',
  false
])


text:
Q: How to correctly vectorize map function in Tensorflow data pipeline I'm trying to speed up my training task. After doing some research, I found that "vectorize" the map function, and move the .batch() ahead is worth a try. The problem is I couldn't manage to do that. No matter how I do it, there are different bugs.
Each unit of input contains:

*

*x_img as (6, 256, 340)

*x_wave as (4410,)

*y_map as (256, 340)
And since I wrote bytes into .tfrecords, I used tf.io.decode_jpeg() for decoding.
My current parse function is here:
def parse_func(example_proto):

    feature_description = {

       "x_img": tf.io.VarLenFeature(tf.string),
       "x_wave": tf.io.VarLenFeature(tf.float32),
       "y_map":tf.io.VarLenFeature(tf.string)
        }

    feat = tf.io.parse_single_example(example_proto, feature_description)

    x = {}
    x_images = tf.sparse.to_dense(feat["x_img"])

    x_img = tf.stack([
        tf.io.decode_jpeg(x_images[0], channels = 3),
        tf.io.decode_jpeg(x_images[1], channels = 3),
        tf.io.decode_jpeg(x_images[2], channels = 3),
        tf.io.decode_jpeg(x_images[3], channels = 3),
        tf.io.decode_jpeg(x_images[4], channels = 3),
        tf.io.decode_jpeg(x_images[5], channels = 3),
    ])

    x["x_img"] = x_img/255

    x_wave = tf.sparse.to_dense(feat['x_wave'])
    x["x_wave"] = x_wave

    y_map = tf.sparse.to_dense(feat['y_map'])
    y = tf.io.decode_jpeg(y_map[0], channels = 1)
    y = tf.image.resize(y, (256, 340))
    y = y/255

    return x, y

And here's the code for building .tfrecords
    with tf.io.TFRecordWriter(tfrcpath) as file_writer:

    for i in range(x_img.shape[0]):

        print("TFRC SHAPE", x_img[i].shape, x_wave[i].shape, y_map[i].shape)
        record_bytes = tf.train.Example(
            features = tf.train.Features(
               feature={
                "x_img": tf.train.Feature( bytes_list = tf.train.BytesList( value= x_img[i])),
                "x_wave": tf.train.Feature( float_list = tf.train.FloatList( value= x_wave[i].flatten().tostring())),
                "y_map": tf.train.Feature( bytes_list = tf.train.BytesList( value= [y_map[i]]))

                })).SerializeToString()

        file_writer.write(record_bytes)

The shapes are the same as each unit of inputs.
Please share some advices. Thank you.


text:
Q: ALIAS record vs A Record for custom domains? I have a site where users can point their own custom domain through the use of DNS records.
For example, someone might point example.com to theirsite.mysite.com so that they are free to use their own domain rather than a subdomain.
Which record would be best for users to set up?
An ALIAS record pointing to mysite.com
An A record pointing to xxx.xx.xx.xx
A CNAME pointing to mysite.com
What are the advantages of using each one?

A: Which is best depends on the specifics of what you're establishing. Here are the differences:
If you set up an A record, the DNS will resolve to an IP and the end user's browser will make a call to that IP with the host name. That's the call that you have to listen for and handle. Since it's direct to IP right from the start, at scale that IP should be a redirector or load balancer.
Otherwise if you need to switch it to a different machine as an endpoint, you have to deal with inconsistencies on how that traffic is routed due to DNS cacheing and whatever TTL you set expiring. Beyond that the biggest issue you're going to run into is that the customer registers their domain and if it's an A record you give them, they're putting in that IP and to change it you're going to have to get the customer to do it, which is definitely not best practice.
CNAME and ALIAS records are similar. In the brief outline you give above, either of these would seem to be better than an A record. You can give them a domain to enter and that doesn't ever change on their side - but you can switch the end IP they're going to as your architecture expands. There are a few minor differences, but the only significant one is that a CNAME cannot be used as an apex record, e.g. example.com, so most likely you'd need to use an ALIAS record.
If you want to read more about the differences between CNAME and ALIAS, there is a good article on it here.


text:
Q: How to make a standard field for Redmine Required? I'm using Redmine 2.4.0. I need to make a standard field (Planned Start) as required. Is it possible?

A: This functionality was added in v2.1.0 allowing configuration of required fields from a tab in the workflow settings.  Read more details on Redmine Issue 703

A: Field permissions are set up per "Role" and "Tracker". I set up field permissions all the time and I've never had any problems with them. Did you take care of these settings?


text:
Q: Meaning of "to be due for a set"
Dr Li: Okay, I'll take a look. It looks a little discolored. We'll get a set of X-rays today to get to the bottom of it.
Tina: X-rays? Will that be an out-of-pocket expense?
Dr Li: No, you're due for a set. It'll be covered by your insurance.

If you break it down what does "due"& "a set" mean and also overall meaning?

A: disclaimer: not medical advice.
He probably means that you can get a number of x-ray prints (a set of them) made for free.

due adjective
  1.2 (of a person) having reached a point where the thing mentioned is required or owed.
  'she was due for a rise'
  - ODO


text:
Q: vb.net - "is in array" function? is there any easy way how to find if any string is present in array of strings without any looping through them?
Example:
Dim array1() As String = {"blue", "white", "black", "yellow", "red"}
Dim check as String = "blue"
Dim response as Boolean

response = check isinarray(array1) 'or something like this - in this case 'response' should be true

All I need is to get true/false (in case it is (or not) present), no index of it or anything else. It can be even case sensitive etc.
How to correctly declare this array and how to "ask" for a presence of a string in the values of the array please?


text:
Q: Facing issue with Firefox browser while running Selenium script Specs
Firefox version: 45.0.2
Selenium: selenium-java-2.53.1 (also tried with selenium-java-3.0.0-beta2)
Code
package Selenium_Practice;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Launch_Browser {

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

        System.setProperty("webdriver.gecko.driver", "C:\\Selenium\\Selenium_Practice\\EXEs\\geckodriver-v0.10.0-win64\\geckodriver.exe");
        WebDriver driver = new FirefoxDriver();

        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        driver.get("http://abcd.jsp");//just for reference

        driver.findElement(By.xpath("//input[@id='loginForm:user-name']")).sendKeys("admin");

        driver.findElement(By.xpath("//input[@id='loginForm:user-password']")).sendKeys("admin");

        driver.findElement(By.xpath("//input[@id='loginForm:submit']")).click();

        driver.close();

    }

}

Error
1470892418708 Marionette: Element is missing an accesible name -> id: loginForm:user-name, tagName: INPUT, className: 1470892418759 Marionette: Element does not have a correct accessibility role and may not be manipulated via the accessibility API -> id: loginForm:user-  password, tagName: INPUT, className:

After entering user name, password & clicking on 'Submit' button, login form is getting refreshed. Please help in resolving the issue.
Also let me know how to encrypt the password in the code the same can do in QTP.

A: You better use the following:
    driver.findElement(By.xpath("//input[contains(@id,'user-name')]")).sendKeys("admin");

    driver.findElement(By.xpath("//input[contains(@id,'user-password')]")).sendKeys("admin");

    driver.findElement(By.xpath("//input[contains(@id,'submit')]")).click();

This is because the character ':' has the special meaning in XPaths.


text:
Q: Is it possible to compute some measure of effect size from four means from a split-plot (both within- and between-subjects) 2x2 design? For a meta-analysis, we are interested in the comparison of two groups. From the articles, we can extract four means: two baseline measures on one of our dependent variables, and two measures collected after some manipulation took place. We also have the standard deviations for these means. The sample sizes are generally very small (which is one of the reasons why we usually have both pre- and post-measures; the researchers were probably aware of their low sample sizes and wanted to increase their power).
Although these means and SD's (variances) are often reported, the only statistics we have are usually from multivariate analyses, rendering them, at best, tricky to use (because the models (included covariates) differ substantially between studies). So we'd prefer to stick to the means and variances.
So, we want to compute the effect size. The go-to measure would be Cohen's d, to see how strongly these groups differ. We could ignore the baseline measure and compute d for post-test only, but this would of course yield a much lower power; ideally we'd look at change from baseline.
However, we don't have individual scores - we can't compute change over time per participant. We only have 'within-group variance' (to use oneway anova vocabulary).
I'd say this means that we might as well not have the baseline means: there is not way to use them to compute an effect size measure. But I want to make sure this is true - I'm not sure there's not something I miss. It feels like I do, but I'm not sure.
To provide an example, we have from one of the studies the following means (SD's):
               pre            post
control        33.2 (12.4)    33.1 (11.2)
experimental   29.5 (13)      30.9 (14.1)

Our goal is to express this association (columns 'within', rows 'between' subjects) in an effect size measure.
Is my intuition/fear, that we're forced to discard the first column because we can't remove or model the dependency between the two columns, correct? Or am I missing something and is there a way to use all available data after all?

A: This was discussed by Becker (1988) (and others). The suggested approach is to calculate the standardized mean change within each group and take the difference. The computation of the standardized mean change for one group is explained in this answer. So, compute this for the first and second group and denote those two values as $d_C$ and $d_E$ (and the corresponding sampling variances as $v_C$ and $v_E$). Then the difference in the standardized mean change is simply $$d = d_E - d_C$$ with sampling variance $$v = v_E + v_C.$$
One difficulty here is that the computation of $v_C$ and $v_E$ requires knowing the correlation between pre- and post-test scores within the groups (which is often not reported). So, you may have to make an educated guess about the correlation and then do sensitivity analyses at the end.


text:
Q: Python compare 2 files to get specific output So I have 2 files.
File A (there are no headres in this file)
ag
bb
hg_tf
gtf

File B
field      id      ag     ytyv   bb    kgka   hg_tf    ghhg     gtf
brown      01       0      1     0.1    2.1     7       3.5     0.8
green      02       0      0.8   1      3.12    0.87    0.5     1.8
blue       03       0      1     2.1     4.1    0.76    3.2     0.75
purple     04       0      2     4.12     2     0.89    3.1     0.8

I want to read over File A and get the data for only those samples from file B.
Output file (wanted)

field      id      ag        bb       hg_tf        gtf    ....
brown      01       0        0.1       7            0.8
green      02       0        1         0.87         1.8
blue       03       0        2.1       0.76         0.75
purple     04       0        4.12      0.89         0.8

My code is:
#!/usr/bin/env python2

import collections
samples = collections.defaultdict(list)
with open('FileA.txt') as A:
  # This I hope read over fileA.
  Asamples = [l.strip() for l in A if l.strip()]
  print(Asamples)

 with open('FileB.csv') as B:
 #And this is where I'm stuck
 ...

Ps: I asked a pretty similar question already but couldn't figure out how to change the code for this new situation.
Thanks everyone

A: Assuming that files A and B looks exactly as in your code samples.
# read and parse A content
file_a = '/tmp/a.txt'
with open(file_a) as filea:
    a_data = [a.strip() for a in filea]

# read and parse B content
file_b = '/tmp/b.txt'
with open(file_b) as fileb:
    b_data = [[l.strip() for l in line.split()] for line in fileb]

# get target columns indexes
# include 'field' and 'id' index
indexes = [0, 1]
for a in a_data:
    try:
        indexes.append(b_data[0].index(a))
    except ValueError:
        pass

# filter data
new_data = [[line[index] for index in indexes] for line in b_data]

# separate columns by tabs and rows by line breaks
new_data_string = '\n'.join(['\t'.join(line) for line in new_data])

# save merged data
new_file = '/tmp/new.txt'
f = open(new_file, 'w')
f.write(new_data_string)
f.close()


text:
Q: Short-circuit current through disconnected capacitor I have a large capacitor made of two smaller 200V rated 560uF capacitors. If I charge this capacitor to 30V with 4.5A from a bench power supply and disconnect it after around 7 seconds, how do I calculate the short circuit current between the positive and negative terminals?

simulate this circuit – Schematic created using CircuitLab

A: What you are asking is very complicated. Looks easy enough until you realise that you are connecting a 0Ω resistor across a voltage source. The current you would get if that 0Ω was ideal, and the capacitor is ideal:
$$ I = \frac{V}{R} = \frac{V}{0\Omega} = \infty A $$
The time it would take to discharge the capacitor is zero seconds, since the time constant is also zero:
$$ \tau = R \times C = 0\Omega \times C = 0 $$
So you have inifinite current passing for no time, which doesn't make sense at all.
In reality the capacitor is not ideal, and the wire you use to short circuit the capacitor is not 0Ω. So the first thing you need to find out is what is the actual resistance between the capacitor's terminals when you "short circuit" it.
The other thing you need to know is the equivalent series resistance (ESR) of the capacitor, and that will not be trivial. It is highly dependent on rate of discharge, temperature, and other factors.
Lastly, the physical loop you form (around which current will flow) has inductance, which will depend on loop area, and whatever else is present inside the loop. Inductance will have the effect of preventing current from rising instantly, further complicating your calculations.
In short (pun intended) you are asking for something way beyond a simple formula, and you can easily damage the capacitor by discharging it in this way.

A: The short circuit current decreases rapidly with time and depends critically on the internal resistance of the cap. Also, to a charged up capacitor, even the wire you use to short the terminals may contribute resistance that appreciably reduces the peak amplitude of the short circuit current. So the test setup matters, too.
So you can estimate it based on the resistance of the capacitors, or you can short the cap with a precision shunt and measure the voltage vs time with an oscilloscope. But ideally the shunt should be smaller than the series resistance of the cap.

A: You don't yet have enough information to calculate it.
You need to know the ESR and ESL (equivalent series resistance and inductance respectively) of the capacitor, and the same for the external circuit.
The current will be 'large'.

A: A simplified model of a capacitor is shown below.
It consists of:

*

*Cp = parallel capacitance, or the bulk capacitance. In your case, the 1020uF capacitance.

*Rp = parallel resistance, or, the leakage resistance. Typically in
the tens of meg-ohm range for a properly formed aluminum electrolytic capacitor.

*Ls = series inductance. This includes the inductance of internal plates, internal
wiring, and leads. This could be hundreds of nH to tens of
uH depending on the construction of the capacitor and lead length.

*Rs = series resistance. Commonly called Equivalent Series Resistance (ESR) which has a frequency dependency. This includes the resistance of the capacitor
structure, internal wiring, and external leads. This can be in the
low milli-ohms to a few ohms depending on construction.

*Rshort and Lshort are the resistance and inductance of your shorting
conductor. These items are added to Rs and Ls.

The series inductances, Ls + Lshort, affects the rise time of short-circuit current.
The series resistance, Rs + Rshort, determines the short-circuit current (use Ohm's law). Rs & Rshort will change when you short the capacitor due to heating which is hard to quantify. Repeated high current shorts can damage the internal structure of the capacitor due to spot heating of the internal structure causing parametric changes.
The parallel resistance, Rp, will determine the discharge of the capacitor when not connected to the charging source. With a 1000uF capacitor, you won't see any significant change in voltage over 7 seconds after you remove the charging source.
Trying to calculate the short circuit current with any accuracy is a bit dicey since the loss parameters are dynamic during the short event. You also have changes in loss parameters with age and usage for aluminum electrolytics.
Shorting capacitors is fun to do, but err on the side of caution and wear eye protection. Good quality capacitors charged to 30V could generate 300+ Amps which can cause molten bits of metal to be expelled. I've had a 150V, 2 Farad, capacitor bank vaporize a PCB copper ground plane which caused a plasma arc which melted the head of a stainless steel bolt a few cm away. Took a few hours for hearing to return to normal.

simulate this circuit – Schematic created using CircuitLab


text:
Q: Configuration Profile with MDM Payload not getting installed to the device Did anybody can tell me what's the reason for that Configuration Profile with MDM Payload not getting installed using IPCU.
How to deal with it?

A: perhaps a bit old but your MDM server url must be a valid HTTPS URL with a cert from a trusted source, self signed certs will not work.

A: View the console for the device in iPCU. This may help you to track down the cause of your issue.

A: Self-signed ssl will work and while generating self-signed ssl certificate in server side,generate identity.p12 certificate and this certificate you need to use in identity section of IPCU and see this and this also.
Please verify again.


text:
Q: jQuery Dialog Popup Cookie I need this popup to show only once for each visitor. When the user clicks the close button the cookie should trigger and set the popup to not show for 30 days. I have tried installing a cookie myself, but to no avail as I have limited understanding of JavaScript. I've read several posts on here relating to this, but they id not help me.
JavaScript:
<link rel="stylesheet" href="jquery-ui-1.10.3.custom/jquery-ui-1.10.3.custom.css" />

HTML:

If you are taking advantage of our 21 day risk free trial your credit card will not be charged for 21 days after you receive your new biofeedback headband.

Only Available for residents of the USA

No Risk - 100% Money-Back Guarantee

If you're not satisfied we even pay for your return shipping

Thanks.

A: You could use the jquery cookie plugin. If you include that library, you can do the following:
$(function () {
    if (!$.cookie("notice-accepted")) {
        $("#dialog-modal").dialog({
            height: 380,
            width: 500,
            modal: true,
            buttons: {
                Ok: function () {
                    $.cookie("notice-accepted", 1, { expires : 30 });
                    $(this).dialog("close");
                }
            }
        });
    }
});

Note: You will want to add style="display: none;" to your dialog
 so it is not displayed when you do not open the dialog.
Demo on JSFiddle


text:
Q: VLC show file in folder I sometimes browse my short-length videos collection. Then I i.e. find some funny one and I want to copy it somewhere else or send it to a friend. The problem is, that the collection is really big, so I don't want to scroll it just looking on thumbnails.
The best option would be to open this file in a folder, so I would get explorer.exe with collection directory and the current video selected. But I cannot quite find that option in VLC. Do you guys know if there's one like this? Or maybe in a form of lua extension?

A: You can right click the video and choose information, then copy the path to the file, then press win+r and enter explorer.exe /select,c:\path\to\file.wmv
Edit:
I made a primitive lua extension that uses this command. Tested with vlc 3.0.4 on windows 10 x64.
usage:

*

*Save the script in the extensions folder.

*Play the desired video to
make it the current playlist item(just selecting in the playlist is
not enough.)

*Open the extension view->select_in_explorer

*Click the
button "select in explorer" in the dialog window.

*The explorer should
open with the file selected.

select_in_explorer.lua
-- "select_in_explorer.lua" -- VLC Extension

function descriptor()
    return {
        title = "Select in explorer",
        version = "0.1",
        author = "mb",
        url = "",
        shortdesc = "Select in explorer",
        description = [[opens Windows explorer and select the currently played file]],
        capabilities = {}
    }
end

function activate()
    dlg = vlc.dialog("Select in explorer")
    update_dialog()
end

function deactivate()
end

function close()
        vlc.deactivate()
end

function meta_changed()
    return false
end

function update_dialog()
    path = vlc.playlist.get(vlc.playlist.current()).path
    dlg:add_button("select in explorer",select_in_explorer, 1, 1, 1, 1)
    path_label = dlg:add_label(path, 2, 1, 1, 1)
    dlg:show()
end

function select_in_explorer()
    path = vlc.playlist.get(vlc.playlist.current()).path
    cmd = "explorer.exe /select,"..path
    io.popen(cmd)
end

A: Just for sake of completeness...

*

*on macOS you can right click > Reveal in Finder - which will highlight the file directly.

*on Windows, right click > Show containing folder [though in a large folder, that's going to be less useful]


text:
Q: Can an objective-c class conform to a swift protocol? Let's say we have a protocol in swift as:
@objc protocol MySwiftyProtocol: NSObject {}

Can an objective-c class conform to a swift protocol?
Like:
@interface MyObjcClass : NSObject <MySwiftyProtocol>

A: Yes they can, (but only in the .m file).


text:
Q: Why I have this error? ArrayIndexOutOfBoundsException I'm creating a android application. When I tested in Emulator, Samsung S8 Plus and General Mobile GM8, I haven't any error but play console always gives me some crushes.
Code is:
int count = getItemCount() >= 30 ? 30 : getItemCount();
if (count == 0)
    return new long[] {0};

long[] result = new long[count];
for (int i = 0; i < count; i++)
    result[i] = users.get(i).getPk();
return result;

Error message:
ArrayIndexOutOfBoundsException
How I can fix it I really do not know.

A: remove the "=" sign in the condition it will work properly :
int count = getItemCount() > 30 ? 30 : getItemCount();
        if (count == 0)
            return new long[] {0};

        long[] result = new long[count];
        for (int i = 0; i < count; i++)
            result[i] = users.get(i).getPk();
        return result;

A: For eg. if count is 4 and users list have only 3 data or less than count then it will throw ArrayIndexOutOfBoundsException
To avoid ArrayIndexOutOfBoundsException try below approach
int count = getItemCount() >= 30 ? 30 : getItemCount();
    if (count == 0)
        return new long[] {0};

    long[] result = new long[count];
    if(users != null && users.size() > 0){
        for (int i = 0; i < count; i++){
            if(i >= users.size()){
                break;
            }
            result[i] = users.get(i).getPk();
        }
    }

return result;

A: If what you want is an array with size equal to the size of the users list with maximum 30 items and minimum 1 element, then change count to the users list size if this size is less than 30:
    int count = getItemCount() >= 30 ? 30 : getItemCount();
    if (count > users.size())
        count = users.size();
    if (count == 0)
        return new long[] {0};

    long[] result = new long[count];
    for (int i = 0; i < count; i++)
        result[i] = users.get(i).getPk();
    return result;

A: It can happen because of out of index.
Let me make it simple if array have 4 indexes so
a=[0,1,2,3]//eg:

SO that if you want to print a[0] then
o/p=
0

But for a[5]:
you will have ArrayOutofBoundsExeption
Here in your example you have not specified your user field How it is generated so after making some assumptions..
Im telling you
result[i] = users.get(i).getPk();

here the problem is occured in users.get(i)
where user field is not that contains value but it may be dynamic:
so my solution will be
You should use
Try exception and just pass it  ArrayIndexOutOfBoundsException
and raise exception your program should work fine!
I hope it will help you!

A: It seems the size of users list does not equal to counts and it is smaller. so to prevent ArrayIndexOutOfBoundsException, I suggest to edit your code in this way:
int count = getItemCount() >= 30 ? 30 : getItemCount();
count = count > users.size()  ? users.size() : count;
        if (count == 0)
            return new long[] {0};

        long[] result = new long[count];
        for (int i = 0; i < count; i++)
            result[i] = users.get(i).getPk();
        return result;

by modifying your code like that, in situations that users list is greater than counts, you will not have any controls on the items at the end of users list.


text:
Q: Populate multiples DropDownList using an array I try to populate severals DropDownLists. In my UI there are multiples tabs and always the same DropDownList in each tab. I use an array then a foreach to populate my DropDownList like that :
public void DropDownList()
    {
        string filePath = Server.MapPath("~/Datas.xml");
        using (DataSet ds = new DataSet())
        {
            DropDownList[] ddls = new DropDownList[]{
               DropDownList_1, DropDownList2,
               DropDownList4, DropDownList5,
               DropDownList7
            };

            foreach (DropDownList ddl in ddls)
            {
                ds.ReadXml(filePath);
                ddl.DataSource = ds;
                ddl.DataTextField =  "name";
                ddl.DataValueField = "id";
                ddl.DataBind();
            }
        }
    }

Here is the XML :
<?xml version="1.0" encoding="utf-8" ?>
    <fields>
      <cafs>
        <caf>
          <id>1</id>
          <name>TEST18</name>
        </caf>
        <caf>
          <id>2</id>
          <name>TEST28</name>
        </caf>
        <caf>
          <id>3</id>
          <name>TEST36</name>
        </caf>
        <caf>
          <id>4</id>
          <name>TEST45</name>
        </caf>
        <caf>
          <id>5</id>
          <name>TOTAL</name>
        </caf>
      </cafs>
    </fields>

Image of the error :
But I get an error on the line ddl.DataBind();
it says that System.Data.DataRowView have no 'name' property. (null in InnerException)
I don't understand why because it was working before. The dataset is loaded and I can display it in Visualizer.
Any ideas why this error could occur ?


text:
Q: How to mock init of helper class I am having trouble with checking if an object is being constructed with the proper params from another instance of an object. In the below example, I am trying to create an instance of B within an instance of A. I want to check the parameter being used in the constructor of B inside of the A instance. When I run the test below, I get:
AssertionError: assert None
[CPython36:setup:stdout] E        +  where None = <bound method NonCallableMock.assert_called_with of <MagicMock name='B' id='139968329210736'>>(4)
[CPython36:setup:stdout] E        +    where <bound method NonCallableMock.assert_called_with of <MagicMock name='B' id='139968329210736'>> = <MagicMock name='B' id='139968329210736'>.assert_called_with

I am not quite sure what I am doing wrong here and have looked at other stack overflow posts, but have not been able to solve my issue.
b.py:
class B(object):
    def __init__(self, x):
        self.x = x

    def square(self):
        return x * x

a.py:
from b import B

class A(object):
    def foo(self):
        b = B(4)
        b.square()

test_a.py:
import unittest
from unittest.mock import patch

from a import A

class TestA(unittest.TestCase):

    @patch('a.B')
    def test_foo(self, mock_b):
        self.a = A()
        self.a.foo()
        assert mock_b.assert_called_with(4)

A: The method assert_called_with returns None, so what your are doing is like doing
assert None

And that's basically the error message you are getting.
You can just use
mock_b.assert_called_with(4)

Which has an assert internally and pytest will display it correctly in case of failure. Try to check it by changing the argument value.
Alternatively, if you prefer to write the assert yourself, you can do something like this:
from unittest.mock import call
assert mock_b.call_args_list == [call(4)]

Or just the last call:
from unittest.mock import call
assert mock_b.call_args == call(4)


text:
Q: Isn't there a mistake at the correction? Bas shouldn't turn on when V1 > 0
So there a table depending on the values of V1, the book solved it like this:
+----+---+---+-----+------+
| V1 | S | R | BAS | HAUT |
+----+---+---+-----+------+
|V1>0| 1 | 0 |  1  |   0  |
+----+-------------+------+
|V1<0| 0 | 1 |  0  |   1  |
+----+-------------+------+

I don't get it. Is this correct? I have questions about this:

*

*When V1>0: Why Bas = 1 when S = 1? It doesn't make any sense. Isn't Haut supposed to be 1 instead since S = 1 and R = 0? I have the same question about when V1 is negative.

*Why S = 1 and R = 0 anyway? Isn't it supposed to be 0 for each of them? Since the result of F1(when V1 is positive) = 1, then it should pass to S = 1(Then it becomes 0 since it's inverted) and R = 1 too(Then it becomes 0)

A: It's wrong.
V3 and SR both invert yet LEDs are positive logic.
Even inversions cancel so it is wrong.
Yes for Vi bypassing V3 the FF is negative logic input R and inverted Q out so it is positive logic
Bracket([ inverts negative logic to normal (1)=set ,, ditto reset.
\$~~Vi ~~  \bar{S}~~(S )~~~\bar{R}    ~(R)~~Q~~~\bar{Q}\$
\$>0~~~ 0~~~[1]~~0~~(1)~~1~~1\$
\$<0~~~1~~~[0]~~0~~(0)~~1~~0\$
Due to contention when both RS are active, both outputs are active.
Due to latency in OpAmp lagging S keeps Set active when both SR go off.
The author shud be fired.  No. its a common newbie design mistake.

A:
Notice this little bubble before the S input. This bubble is an indicator meaning that the input is inverted; i.e. a 0 on the input acts like a 1 in a standard SR flip-flop and vice versa. This bubble is the same as the one in the symbol for a NOT gate, so you can imagine it as a sort of miniaturized NOT gate at the input (it's not implemented that way, though).
Many SR flip-flops use inverted inputs, because it just works out easier in TTL, and compatibility means manufacturers keep using active-low designs even though TTL is pretty obsolete by now.


text:
Q: JSON not mapped to Class I have a asp.net core 3.0 application with WebPages and I try to send a JSON via ajax to my handler. But the parameter is always null or just filled with the default values. I tried to if the JSON string from the post is parseable and it works when I parse manually.
This is my controller:
    public void OnPost([FromBody]FilterModel filter)
    {
        Console.Write(filter);
    }

This is the model class:
public class FilterModel
{
    public DateTime TimeRangeFrom { get; set; }
    public DateTime TimeRangeTo { get; set; }

    public int CustomerId { get; set; }
}

The ajax request:
                    $.ajax({
                        url: "/CustomerOverview/Test",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        data: JSON.stringify({
                            CustomerId: customerId,
                            TimeRangeFrom: picker.startDate,
                            TimeRangeTo: picker.endDate
                        }),
                        beforeSend: function(xhr) {
                            xhr.setRequestHeader("XSRF-TOKEN",
                                $('input:hidden[name="__RequestVerificationToken"]').val());
                        },
                        success: function(response) {
                            button.hide();
                        },
                        failure: function(response) {
                            alert(response);
                        }
                    });

And the JSON as logged in Chrome Dev Tools:
{CustomerId: "1", TimeRangeFrom: "2019-08-26T22:00:00.000Z", TimeRangeTo: "2019-09-25T21:59:59.999Z"}

Do I have to setup a mapping or something?

A: FromBody attribute  will parse the model the default way which in most cases are sent by the content type application/json from the request body.So if you fill a form and pass the form data to the controller action,you need to convert the JavaScript object into a string with JSON.stringify().
FromForm attribute is for incoming data from a submitted form sent by the content type application/x-www-url-formencoded.
Reference:https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-3.0#sources

A: Turns out that it can't convert an "1" to an int. I had to convert the value for customerId to a int first so that I have this JSON:
{
    "CustomerId": 1,
    "TimeRangeFrom": "2019-08-26T22:00:00.000Z",
    "TimeRangeTo": "2019-09-25T21:59:59.999Z"
}


text:
Q: SSIS job fails via automation I've developed an SSIS job in Visual Studio 2017, targeting Microsoft SQL server 2016.  When I execute it manually via Visual Studio it runs to completion with no errors.  The original deployment to the SQL server was running just fine via the "run at 11pm" schedule that was setup.
Now I've made some change and re-published, and it's failing to run.  I've tried to wrap the entire section of code in try/catch/finally blocks and have the catch send me an email, for example, but I don't get anything.
What can I do to debug why this fails to run via the schedule but doesn't fail to run from Visual Studio?  The job runs as me on the SQL server so it's not a user permission error, to the best of my knowledge.
I can't directly log into the SQL server, but I can have IT run some things for me or export a share if there's a better log I can find.

A: I generally configure the Package OnError eventhandler to send an email with the exception details.
If the problem is in a script, you can use the try..catch block to raise an event in the catch block and provide a useful message for your email. e.g.
catch (Exception e)
{
     Dts.Events.FireError(0, null, string.Format("Error parsing file: {0}", e),null, 0);
      Dts.TaskResult = (int)DTSExecResult.Failure;
}


text:
Q: Prove that : $|f(b)-f(a)|\geqslant (b-a) \sqrt{f'(a) f'(b)}$ with $(a,b) \in \mathbb{R}^{2}$
Let $(a,b) \in \mathbb{R}^{2}$ such that $a<b$ and $f\in C^2([a,b],\mathbb{R})$ such that   $f'\neq 0$ and $f''/f'$ is decreasing.
Prove that :
$$|f(b)-f(a)|\geqslant (b-a) \sqrt{f'(a) f'(b)}$$

My attempt:
By the MVT theorem, we have to prove :
$$
|f'(c)| \geq \sqrt{f'(a)f'(b)}, \quad c\in (a,b)
$$
Without loss of generality we can assume that $f'$ is stricly positive.
Thus, by the fact that $\ln(f')$ is concave we get
$$
\frac{\ln(f'(c))-\ln(f'(a))}{c-a}\geqslant\frac{\ln(f'(b)-\ln(f'(c))}{b-c}
$$
So,
$$
\frac{\ln \frac{f'(c)}{f'(a)}}{c-a}\geqslant\frac{\ln \frac{f'(b)}{f'(c)}}{b-c}
$$
Notice that I haven't use  $\frac{f''(a)}{f'(a)}\geq \frac{f''(b)}{f'(b)}$,
So I think what I am doing it's not enough.
Any ideas?
Thank you in advance for your help,

A: Abbreviate $f'=g$. Please note that you can not use the MVT, as
$$|g(c)|\geq \sqrt{g(a)g(b)},\quad \forall c\in (a,b) $$
is not possible if $g(a)\neq g(b)$. Instead we note that (wlog $g>0$)
$$|f(b)-f(a)|=\int_a^b g(x)dx=(b-a)\int_0^1g((1-s)a+bs)ds. $$
As $g$ is log concave, we have that
$$g(sb+(1-s)a)\geq g(b)^sg(a)^{1-s}.$$
This gives us
$$|f(b)-f(a)|\geq (b-a)\int_0^1g(b)^sg(a)^{1-s}ds =(b-a)\frac{g(b)-g(a)}{ln(g(b))-ln(g(a))}.$$
The inequality
$$ \frac{g(b)-g(a)}{ln(g(b))-ln(g(a))} \geq \sqrt{g(a)g(b)} $$
is not too difficult to proof, I will leave it to you. (Please ask if you need help).


text:
Q: set of tuples of items in grocery I was doing a question given vectors of itemName, price, and quantity in which I had to find out how many duplicates are there in them when combined. So I did solve the problem by using the set of tuples but then I thought of unpacking them and print them. Here's my code:
#include<bits/stdc++.h>
using namespace std;
int main(){
    vector<string> name{"ball", "bat", "glove", "glove","glove"};
    vector<int> price{2,3,1,2,1};
    vector<int> w{2,5,1,1,1};
set<tuple<string,int,int>> s;
for(int i = 0; i < name.size(); i++){
    s.insert({name[i],price[i],w[i]});
}
for(int i = 0; i < s.size(); i++){
    string st;
    int p;
    int we;
    tie(st,p,we) = s[i]; **statement**
    cout<<st<<" "<<p<<" "<<we<<'\n';
}
cout<<name.size() - s.size();
return 0;
}

But there's an error in the statement line. Can't unpack. Need help. Thanks.

A: Unfortunately you cant unpack a tuple using tie.
Although, if you are using c++17, you could use structural bindings like this (pardon the indentation):
#include<bits/stdc++.h>
using namespace std;

int main(){
    vector<string> name{"ball", "bat", "glove", "glove","glove"};
    vector<int> price{2,3,1,2,1};
    vector<int> w{2,5,1,1,1};
     set<tuple<string,int,int>> s;
for(int i = 0; i < name.size(); i++){
    s.insert({name[i],price[i],w[i]});
}

for(auto tup : s){
    auto [a, b, c] = tup;
    cout<<a<<" "<<b<<" "<<c<<'\n';
}
cout<<name.size() - s.size();
return 0;
}

In C++11/14, you might consider printing it directly:
cout << get<0>(tup) << " " << get<1>(tup) << " " << get<2>(tup) << endl;


text:
Q: If statement not running correctly What I'm trying to do is get my program to run a method to make lemonade (makeLemonade) if and only if I have enough ingredients to make the lemonade, but I keep getting an error from the tests provided for me that tells my lemonade is being made even when I don't have enough ingredients.
Here's the code I have right now for the if statement that's giving me some trouble. I've tried using && and || along with different mixes of >= and > to no avail so far.
 public int makeLemonade() {
    if (lemons >= 6 && gallonsOfWater >= 1 && cupsOfSugar >= 1 && emptyGlasses >= 8) {
        lemons = lemons - 6;
        gallonsOfWater = gallonsOfWater - 1;
        cupsOfSugar = cupsOfSugar - 1;
        emptyGlasses = emptyGlasses - 8;
        glassesOfLemonade = glassesOfLemonade + 8;
        return glassesOfLemonade;
    } else {
        return 0;
    }
}

This is the error my test is giving me right now
"Test of method makeLemonade failed for activty 3.
The following code was executed:
LemonadeStand ls = new LemonadeStand(5, 2, 2, 16, 1.1);
ls.makeLemonade();

Fields were modified even though there was not enough lemons available to make lemonade."
Here is the entire code so far
    /**
 * LemonadeStand.java
 *
 */

//Put any imports below this line.

/**
 * Short, one-line description of LemonadeStand class here.
 *
 * Optionally, include a paragraph that provides a more
 * detailed description.
 *
 * @author Nicholas Thomas
 * @version 2/19/2018
 */
public class LemonadeStand
{
    //Put instance variables below this line.
    private int lemons;
    private int gallonsOfWater;
    private int cupsOfSugar;
    private int emptyGlasses;
    private double price;
    private double income;
    private int glassesOfLemonade;
    /** No arg constructor.
     * LemonadeStand Constructor
     *
     */
    public LemonadeStand()
    {
        lemons = 0;
        gallonsOfWater = 0;
        cupsOfSugar = 0;
        glassesOfLemonade = 0;
        emptyGlasses = 0;
        price = 0;
        income = 0;
    }

    /** Contructor.
     * LemonadeStand Constructor
     *
     * @param newLemons A parameter
     * @param newGallonsOfWater A parameter
     * @param newCupsOfSugar A parameter
     * @param newEmptyGlasses A parameter
     * @param newPrice A parameter
     */
    public LemonadeStand(int newLemons, int newGallonsOfWater,
    int newCupsOfSugar, int newEmptyGlasses, double newPrice)
    {
        setLemons(newLemons);
        setGallonsOfWater(newGallonsOfWater);
        setCupsOfSugar(newCupsOfSugar);
        setEmptyGlasses(newEmptyGlasses);
        setPrice(newPrice);
        glassesOfLemonade = 0;
        income = 0;
    }

    /** Main method of the program.
     * Method main
     *
     * @param args A parameter
     */
    public static void main(String[] args)
    {
        LemonadeStand lemonadeStand = new LemonadeStand(15, 3, 4, 20, 1.5);
        lemonadeStand.makeLemonade();
        System.out.println(lemonadeStand.getLemons());
        System.out.println(lemonadeStand.getGallonsOfWater());
        System.out.println(lemonadeStand.getCupsOfSugar());
        System.out.println(lemonadeStand.getGlassesOfLemonade());
    }

    /** Mutator to change the amount of lemons.
     * Method setLemons
     *
     * @param newLemons A parameter
     * @return newLemons
     */
    public int setLemons(int newLemons)
    {
        if (lemons < 0)
        {
            lemons = newLemons;
            return newLemons;
        }
        else
        {
            return 0;
        }

    }

    /** Mutator to change gallons of water.
     * Method setGallonsOfWater
     *
     * @param newGallonsOfWater A parameter
     * @return gallonsOfWater
     */
    public int setGallonsOfWater(int newGallonsOfWater)
    {
        if (gallonsOfWater < 0)
        {
            gallonsOfWater = newGallonsOfWater;
            return gallonsOfWater;
        }
        else
        {
            return 0;
        }
    }

    /** Mutator to set cups of sugar.
     * Method setCupsOfSugar
     *
     * @param newCupsOfSugar A parameter
     * @return cupsOfSugar
     */
    public int setCupsOfSugar(int newCupsOfSugar)
    {
        if (cupsOfSugar < 0)
        {
            cupsOfSugar = newCupsOfSugar;
            return cupsOfSugar;
        }
        else
        {
            return 0;
        }
    }

    /** Mutator to modify the number of empty glasses.
     * Method setEmptyGlasses
     *
     * @param newEmptyGlasses A parameter
     * @return emptyGlasses
     */
    public int setEmptyGlasses(int newEmptyGlasses)
    {
        if (emptyGlasses < 0)
        {
            emptyGlasses = newEmptyGlasses;
            return emptyGlasses;
        }
        else
        {
            return 0;
        }
    }

    /** Mutator to modify the glasses of lemonade.
     * Method setGlassesOfLemonade
     *
     * @param newGlassesOfLemonade A parameter
     * @return glassesOfLemonade
     */
    public int setGlassesOfLemonade(int newGlassesOfLemonade)
    {
        if (glassesOfLemonade < 0)
        {
            glassesOfLemonade = newGlassesOfLemonade;
            return glassesOfLemonade;
        }
        else
        {
            return 0;
        }
    }

    /** Mutator to change the price.
     * Method setPrice
     *
     * @param newPrice A parameter
     * @return price
     */
    public double setPrice(double newPrice)
    {
        if (price < 0)
        {
            price = newPrice;
            return price;
        }
        else
        {
            return 0;
        }
    }

    /** Mutator to set the income.
     * Method setIncome
     *
     * @param newIncome A parameter
     * @return income
     */
    public double setIncome(double newIncome)
    {
        if (income < 0)
        {
            income = newIncome;
            return income;
        }
        else
        {
            return 0;
        }
    }

    /** Accessor to make lemonade.
     * Method makeLemonade
     *
     * @return The return value
     **/

    public int makeLemonade()
    {
        if (lemons >= 6 && gallonsOfWater >= 1 && cupsOfSugar >= 1
        && emptyGlasses >= 8)
        {
            lemons -= 6;
            gallonsOfWater -= 1;
            cupsOfSugar -=  1;
            emptyGlasses -= 8;
            glassesOfLemonade += 8;
            return glassesOfLemonade;
        }
        else
        {
            return 0;
        }
    }

    /** Accessor to lemonade selling.
     * Method sellLemonade
     *
     * @return The return value
     */
    public int sellLemonade()
    {
        if (glassesOfLemonade <= 1)
        {
            makeLemonade();
            return 0;}
        else
        {
            glassesOfLemonade = glassesOfLemonade - 1;
            income = income + price;
            return glassesOfLemonade;
        }

    }

    /** Accessor to get number of lemons.
     * Method getLemons
     *
     * @return The return value
     */
    public int getLemons()
    {
        return lemons;
    }

    /** Accessor to return gallons of water.
     * Method getGallonsOfWater
     *
     * @return The return value
     */
    public int getGallonsOfWater()
    {
        return gallonsOfWater;
    }

    /** Accessor to return cups of sugar.
     * Method getCupsOfSugar
     *
     * @return The return value
     */
    public int getCupsOfSugar()
    {
        return cupsOfSugar;
    }

    /** Accessor to return the value of empty glasses.
     * Method getEmptyGlasses
     *
     * @return The return value
     */
    public int getEmptyGlasses()
    {
        return emptyGlasses;
    }

    /** Accessor to return glasses of lemonade.
     * Method getGlassesOfLemonade
     *
     * @return The return value
     */
    public int getGlassesOfLemonade()
    {
        return glassesOfLemonade;
    }

    /** Accessor to return the price.
     * Method getPrice
     *
     * @return The return value
     */
    public double getPrice()
    {
        return price;
    }

    /** Accesor to return the income rate.
     * Method getIncome
     *
     * @return The return value
     */
    public double getIncome()
    {
        return income;
    }

    /** Accessor for lemonade selling.
     * Method sellMoreLemonade
     *
     * @param requestedGlasses A parameter
     * @return The return value
     */
    public int sellMoreLemonade(int requestedGlasses)
    {
        return 0;
    }
}

A: The main issue with the code is the setter-usage. For example:
if (gallonsOfWater < 0) {
  gallonsOfWater = newGallonsOfWater;
  return gallonsOfWater;
} else {
    return 0;
}

The gallonsOfWater field of LemonadeStand is initialized e.g. in the 2nd constructor by the call setGallonsOfWater(newGallonsOfWater);.
Let us assume that you pass the value 3 to this constructor, so it will be  setGallonsOfWater(3);. In the setter this leads to  3 < 0 and hence

*

*the return value of 0 for the setter.

*not setting the value for the field gallonsOfWater.

(I assume that debugging would have helped here also)


text:
Q: Android QRCode Scanner Library What do we have out there available to us (if anything) that we can call for QR data discovery and extraction on an image?
While there have been plenty of posts thus far referencing the ZXing library for QRCode scanning, I haven't found that to be a solution that works for me. Several others have been asking for QRCode scanning alternatives and I have not seen useful feedback. I thought I might ask the community once more what the other options might be for a QR code library that does not launch an activity and call outside our own applications. It should scan images from the Camera2 API in a very simplistic manner.  It shouldn't be a complicated library. I hadn't seen examples or individuals speaking of it in this manner.
It actually puzzles me as to why there hasn't been native implementations of the QRCode functionality added into perhaps the Camera library or similar place within the Google SDK natively within the operating system.
Calling and requiring another application (or even requesting a download) is not an elegant solution and no users should be succumbed to doing such thing.  As developers we should have access to a library capable of extracting a QRCode from an image or frame that we can then remove encoded data from.

A: Android QRCode Scanner Library
This may help you, this library doesn't require any download or use of any external application. We can directly integrate this into your app and use it for scanning a QR code.
https://github.com/dm77/barcodescanner
This wiki will help you to integrate with your app,
https://github.com/dm77/barcodescanner/blob/master/README.md

A: You can also check MobileVisionBarcodeScanner (note I'm the author of this package). It is powered by Google's mobile vision API. Also see the overview
here .

A: I used this library in my app. It also works with xing but you don't need any third party applications. Additional it's really easy to use.
https://github.com/journeyapps/zxing-android-embedded
Maybe you searched something like this.

A: You've already found the library you're looking for, I think. See the core/ module:
https://github.com/zxing/zxing/tree/master/core
You're just looking at the Intent-based integration, but, in fact the core scanning is its own stand-alone library that you can embed into your own app.
I think Intent-based integration is best in most cases, simply because it is so simple, and, most people don't have the time to reimplement their own scanning UI and such on top of the core. Most devices have Barcode Scanner installed already, so it doesn't usually need a download.
Still, take your pick. That's why there are at least two ways to use it.

A: While Sean Owen and others that have worked on the original Zxing library had provided an approach to work with the barcode libraries for the past several years, Google has finally put out an official release with Google Play Services for handling qr and barcodes.
The barcode detection library is described here.  The inclusion of these libraries will make for a smooth integration.  I'll repost with some sample code for achieving these results from a captured image.  At the moment, I wanted to update my answer for this official release.  If this indeed does provide a nice way to get at this information (without jumping through hoops and complications), then I'll update with the source and check this off as an accepted answer.
The detection library that Google has provided within the past year has been a much easier library to work with.  It allows for quick integration with the camera APIs and extracts the information with simplicity.  This would be the component that I would suggest going forward with recognition.  A quick snippet is demonstrated below for handling a Qr-code.  A handful of pseudocode is left in there as well.
public final void analyzeFrameForQrCode(byte[] qrCodePictureF, int imageFormatF, XriteSize previewWindowSizeF)
{
    if(!qrCodeDetectionPossible() || qrCodePictureF == null || mIsAnalyzingQrCodeFrame)
    {
        return;
    }

    ... //Bitmap conversion code

    Frame frame = new Frame.Builder().setBitmap(pictureTaken).build();
    SparseArray<Barcode> barcodes = mBarcodeDetector.detect(frame);
    if(barcodes != null && barcodes.size() != 0)
    {
        Barcode qrCode = barcodes.valueAt(0);//barcodes.get(Barcode.QR_CODE);
        if(qrCode != null)
        {
             if(extractInformationFromQrCode(qrCode.rawValue)) {
                    mIsRequestingBarcodeDetection = false;
                    vibrateForQrCodeDiscovery();
                    ((Activity)mContext).runOnUiThread(new Runnable() {
                        @Override
                        public void run()
                        {
                            hideBarcodeDetection(true);
                        }
                    });
                }
            }
        }

     ... //Cleanup and code beyond Qr related material

   }
}

There are of course other calls available that can be taken advantage of.  But there are really only a couple lines in there.  The service for analyzing the frames with the library are not there by default on devices however.  So, you should check whether or not the library is available (such as when internet is not available) before calculating as well.  This is a slight nuisance of it.  I had assumed it would be available as updates for devices going forward as part of the support library or Google Services going out to all devices.  But it needs the communication first with an external service to use these library calls.  Once it does this one time then that device is good from that moment on.
In my small example, I pop a toast up after a check and then back out of the activity and let the user check their connection.  This can be done with a small amount of sample code as well.
if(!mBarcodeDetector.isOperational())
{
    updateUserInstructions("The barcode library cannot be downloaded");
    return false;
}

Edit (Update):
A considerable amount of time has passed since working with the latest Google Play Services Vision libraries available for barcode detection.  While the limitation for needing to download the library over the wifi is indeed a limitation, it is a one time process.  And lets be honest...
...our devices will have a connection.  The library itself is downloaded in the background so you don't even notice it happening unless there is trouble downloading it and then you would have to report an appropriate corrective measure such as enabling a connection to the internet for it.
One additional tidbit is that it is a little tricky sometimes with how you integrate the library into your application.  Using it as a library project worked on some devices and then failed on others.  Adding the jar to the build path worked across a broader number of devices (it could be all, but it solved a problem).  So as such, I would do it using the secondary method when including it in your projects for now.

A: Rather than QRCODE ZXing library integration You are able to open camera and scan QRCode from anywhere:
The code i found below will may be helps to you for scanning QRCode :
try {
                Intent intent = new Intent("com.google.zxing.client.android.SCAN");
                intent.putExtra("SCAN_MODE", "QR_CODE_MODE"); // "PRODUCT_MODE for bar codes
                startActivityForResult(intent, 0);
            } catch (Exception e) {
                Uri marketUri = Uri.parse("market://details?id=com.google.zxing.client.android");
                Intent marketIntent = new Intent(Intent.ACTION_VIEW,marketUri);
                startActivity(marketIntent);
            }

Please remember that You must have a barcode scanner application by "Zxing" in Mobile Phone else it will firstly redirect to Google play store link for download it.


text:
Q: How to display Group name also along with dropdown list items using jquery multiselect in mustache I'm using mustache.js for rendering my page. Here is the snippet of what I'm trying to do:
{{#items}}

  <optgroup label ="Countries">

<option >

{{name}} // json data
</option>
 </optgroup>

{{/items}}

The items contain the json data and I'm trying to render it in a form of a table using the jquery multiselect plugin.
Here is the jquery widget that I'm using, I'm trying to add a label on top of the options, i.e
Countries:
      Afghanistan
      Albania...and so on

Any ideas how can it be implemented?  I tried using the "optgroup", howevevr it doesn't work. Maybe I'm not using it the right way.
Any ideas appreciated!!!!
Thanks!

A: The optgroup should be out of the {{#items}}
<select>
  <optgroup label ="Countries">
{{#items}}
     <option>{{name}}</option>
{{/items}}
 </optgroup>
</select>

This will generate proper HTML.


text:
Q: Moment.js giving tomorow and yesterday in reverse My console:

same w/o new Date constructor:

What can be wrong??
PS: it is not project related because I am getting same results in console on momentjs.com
EDIT:
To easily reproduce, go to momentjs.com, open console, put:
moment().calendar('2016-11-27T07:31:29.000+0000'); // expecting "Sunday at 9:58 AM" getting "Tuesday at 9:58 AM"
moment().calendar('2016-11-28T07:31:29.000+0000'); // expecting "Yesterday at 9:58 AM" getting "Tomorrow at 9:58 AM"
moment().calendar('2016-11-29T07:31:29.000+0000'); // this is correct "Today at 9:58 AM"
moment().calendar('2016-11-30T07:31:29.000+0000'); // expecting "Tomorrow at 9:58 AM" getting "Yesterday at 9:58 AM"

A: In the docs it says:
moment().calendar(referenceTime);

Calendar time displays time relative to a given referenceTime (defaults to now), but does so slightly differently than moment#fromNow
So the results what you get is correct, because your string time is reference.
For the correct result use:
moment('2016-11-30T07:31:29.000+0000').calendar();

A: .calendar()'s second parameter is the reference time. Docs Here
if you're trying to change the date of something. instead, create it like:
moment().subtract(1, 'days').calendar()

or
moment('2016-11-28T07:31:29.000+0000').calendar()

A: So as @Andrey pointed the correct order is:
moment('2016-11-28T07:31:29.000+0000').calendar()

not
moment().calendar('2016-11-28T07:31:29.000+0000')

Thank you @Andrey


text:
Q: Is there a better way to break columns every 3rd row in Bootstrap CSS with PHP? Equal-width multi-row I found the following in the bootstrap documentation:
Create equal-width columns that span multiple rows by inserting a .w-100 where you want the columns to break to a new line every 3rd column.  - https://getbootstrap.com/docs/4.0/layout/grid/#equal-width-multi-row
Is there a better way to do this?

A: echo "
";

$rows = [];
$rows = ["apples", "oranges", "bananas", "pears", "grapes", "watermelons"];

foreach ($rows as $value) {

    echo "
" . $value . "
";

}

echo "
"; //End of row


text:
Q: AAPT: error: '6495ed' is incompatible with attribute background (attr) reference|color <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_gravity="center"
    android:layout_marginTop="15dp">

    <View
        android:id="@+id/divider2"
        android:layout_width="wrap_content"
        android:layout_height="5dp"
        android:background="6495ed"/>

</LinearLayout>

This is my code and it keeps displaying  the error incompatible with attribute background

A: android:background="6495ed" is the problem. You want it written as android:background="#6495ed"
A better practice is to save those color values in an XML file that specifically holds colors. These go in your res>values folder, under colors.xml.
To do it that way, in res>values>colors.xml, add:
<color name="addala_color_blue">#6495ed</color>
Then in your layout XML, you'd set:
android:background="@color/addala_color_blue" or whatever you named it.


text:
Q: Using C++ base class constructors? While working with templates I ran into a need to make a base class constructors accessible from inherited classes for object creation to decrease copy/paste operations.
I was thinking to do this through using keyword in same manner with functions case, but that not work.
class A
{
public:
    A(int val) {}
};

class B : public A
{
};

class C : public A
{
public:
    C(const string &val) {}
};

class D : public A
{
public:
    D(const string &val) {}
    using A::A;              // g++ error: A::A names constructor
};

void main()
{
    B b(10);                // Ok.   (A::A constructor is not overlapped)
    C c(10);                // error: no matching function to call to 'C::C(int)'
}

So my question: Is there any way to import a base class constructors after new ones in inherited class been declared?
Or there is only one alternative to declare new constructors and call a base ones from initializer list?

A: Prefer initialization:
class C : public A
{
public:
    C(const string &val) : A(anInt) {}
};

In C++11, you can use inheriting constructors (which has the syntax seen in your example D).
Update: Inheriting Constructors have been available in GCC since version 4.8.

If you don't find initialization appealing (e.g. due to the number of possibilities in your actual case), then you might favor this approach for some TMP constructs:
class A
{
public:
    A() {}
    virtual ~A() {}
    void init(int) { std::cout << "A\n"; }
};

class B : public A
{
public:
    B() : A() {}
    void init(int) { std::cout << "B\n"; }
};

class C : public A
{
public:
    C() : A() {}
    void init(int) { std::cout << "C\n"; }
};

class D : public A
{
public:
    D() : A() {}
    using A::init;
    void init(const std::string& s) { std::cout << "D -> " << s << "\n"; }
};

int main()
{
    B b; b.init(10);
    C c; c.init(10);
    D d; d.init(10); d.init("a");

    return 0;
}

A: You'll need to declare constructors in each of the derived classes, and then call the base class constructor from the initializer list:
class D : public A
{
public:
    D(const string &val) : A(0) {}
    D( int val ) : A( val ) {}
};

D variable1( "Hello" );
D variable2( 10 );

C++11 allows you to use the using A::A syntax you use in your decleration of D, but C++11 features aren't supported by all compilers just now, so best to stick with the older C++ methods until this feature is implemented in all the compilers your code will be used with.

A: class A
{
public:
    A(int val) {}
    A(string name) {}
};

class B : public A
{
using A::A;
};

Addition to other answers, in case there are several constuctors with the base class, and you just want to inherit some of them, you can delete the unwanted.
 class B : public A
 {
    using A::A;
    B(string) = delete;
 };

A: No, that's not how it is done. Normal way to initialize the base class is in the initialization list :
class A
{
public:
    A(int val) {}
};

class B : public A
{
public:
  B( int v) : A( v )
  {
  }
};

void main()
{
    B b(10);
}

A: Yes, Since C++11:
struct B2 {
    B2(int = 13, int = 42);
};
struct D2 : B2 {
    using B2::B2;
// The set of inherited constructors is
// 1. B2(const B2&)
// 2. B2(B2&&)
// 3. B2(int = 13, int = 42)
// 4. B2(int = 13)
// 5. B2()

// D2 has the following constructors:
// 1. D2()
// 2. D2(const D2&)
// 3. D2(D2&&)
// 4. D2(int, int) <- inherited
// 5. D2(int) <- inherited
};

For additional information see http://en.cppreference.com/w/cpp/language/using_declaration

A: Here is a good discussion about superclass constructor calling rules. You always want the base class constructor to be called before the derived class constructor in order to form an object properly. Which is why this form is used
  B( int v) : A( v )
  {
  }


text:
Q: Repeated Single Regression w/ Factor and Continuous Variables I have a dataset similar to the below structure that I'd like to run several single regressions with:
example <- tibble(
  id = paste0('ID', runif(100,0,10)),
  response = runif(100,0,10),
  x1 = runif(100,0,10),
  x2 = factor(rep(seq(1,5),20)))

regression_1 <- lm(response ~ x1, data = example)
regression_2 <- lm(response ~ x2, data = example)

And so on for n predictors. I've tried a variety of approaches but I keep running into an error and cannot figure out for the life of me any neat and easy way to do this.
Appreciate any help

A: Using reformulate.
lapply(c("x1", "x2", "xn"), function(x) lm(reformulate(x, response="response"), d))
# [[1]]
#
# Call:
#   lm(formula = reformulate(x, response = "response"), data = d)
#
# Coefficients:
#   (Intercept)           x1
#       0.03567      0.03603
#
#
# [[2]]
#
# Call:
#   lm(formula = reformulate(x, response = "response"), data = d)
#
# Coefficients:
#   (Intercept)           x2
#       0.03098     -0.14824
#
#
# [[3]]
#
# Call:
#   lm(formula = reformulate(x, response = "response"), data = d)
#
# Coefficients:
#   (Intercept)           xn
#       0.02961      0.08823

Data:
set.seed(42)
d <- data.frame(matrix(rnorm(400), 100, 4, dimnames=list(NULL, c("response", "x1", "x2", "xn"))))

A: We can subset the data and use ~ .
lapply(c("x1", "x2", "xn"), function(x) lm(response ~ ., df1[c('response', x)]))


text:
Q: Propensity Score Matching using MatchIt. How to introduce a caliper to an exact additional specification I'm new to R, and Im using matchit to match patients by propensity scores. My dataset includes two groups of patients that differ by whether or not they received a drug.  As well as matching on propensity score, I also want to exact match on age, gender and family practice, as the decision to treat does vary significantly depending on these characteristics.
My problem is that I would like to exact match by age ± 2 years, as I would like to increase the number of treated patients that can be matched in my dataset, by increasing the flexibility of my exact matches (rather than using an arbitrary cut-off, as with an categorical age variable, for example).
The code below works well
match.1 <-  matchit(exposed ~ imd2010_5 + hyp + mhealth + mm_score + GP_consult + smoke + no_pres3m + lterm_pres + pres_rate,
data=dataset_pscore2,
distance=dataset_pscore2$pscores,
method="nearest",
exact=c("gender", "pracid", "age_cat"),
discard="both",
caliper=0.25,
ratio=2)

Id just like to change the exact code to something like
exact=c("gender", "pracid", "age" *with a caliper*),

Is this possible?

A: As far as i can tell, Propensity Score Matching (PSM) usually uses a LOGIT regression to find the estimated propensity scores, as a way to avoid the curse of dimensionality.So, doing exact matching in some covariates in a PSM set-up sounds unlikely.
I suggest running two matching procedures: The first one with exact matching on the covariates which you would like to be exact matched. Then, running the PSM on the new matched-sample on the other covariates.
As an example:
match.1 <-  matchit(exposed ~ gender + pracid + age_cat,
data=dataset_pscore2,
method="exact")

matched_sample <- match.data(match.1) # Get Propensity Scores for 'matched_sample'

match.2 <-  matchit(exposed ~ imd2010_5 + hyp + mhealth + mm_score + GP_consult + smoke + no_pres3m + lterm_pres + pres_rate,
data=matched_sample,
distance=matched_sample2$pscores,
method="nearest",
discard="both",
caliper=0.25,
ratio=2)

I also suggest reading the MatchIt package documentation. And this other wonderfull package, called cem.

A: You can now (as of matchIt version 4.0.0) supply specific covariates to the caliper` argument to request calipers on them directky in the context of another matching method. For you example, this owuld look like this:
match.1 <-  matchit(exposed ~ imd2010_5 + hyp + mhealth + mm_score + GP_consult + smoke + no_pres3m + lterm_pres + pres_rate,
                    data=dataset_pscore2,
                    distance=dataset_pscore2$pscores,
                    method="nearest",
                    exact=c("gender", "pracid"),
                    discard="both",
                    caliper=c(0.25, age = 2),
                    std.caliper = c(TRUE, FALSE),
                    ratio=2)

The key lines are caliper=c(0.25, age = 2) and std.caliper = c(TRUE, FALSE). The caliper line says that we want a caliper of .25 on the distance measure (i.e., the propensity score) and a caliper of 2 on age. The std.caliper line says that we want the first caliper to be in standard deviation units and the second caliper to be in raw units. This way, you have that units must be within .25 standard deviations of the propensity score and within 2 years of age to be able to be matched with each other. See the documentation at help("method_nearest", package = "MatchIt") for details and an example.


text:
Q: Random single letter within BODY tag I have a random "d" letter between my opening and closing BODY tag right after the footer tag in my Wordpress installation which is causing it to display a random "d" letter site wide near my header/menu area.
Any thoughts? Thanks.

A: Check your header.php and index.php templates.

A: Review if your Theme has properties to add content after/before the body. If so, try to found the property in your theme options and remove the letter.


text:
Q: Visual SourceSafe 2005 - How to GET changed files for a certain date range (command line tool) Here I was trying to perform a GET operation to pull a list of files that have been checked in/changed for a given date range, excluding the ones that have not been changed in that time frame.
Here's the command I'm using:
ss Get $\MY_PROJECT to . -Vd8/01/10;12:00a~08/03/10;11:59p -R

In the beginning it actually seems to do what I want - it keeps crunching for a while trying to figure out the files that have changed. Then, all of a sudden, it dumps the remaining non-changed files in the same dir.
Is there a way to achieve what I need? If yes, what's missing? Thanks!

A: Try this (my vss is on a remote server):
SET SSDIR=\$myserver\myvss\myproject
"C:\Program Files\Microsoft Visual SourceSafe\SS.exe" history $/myproject -Vd31/12/10~17/11/10 -R
Please note that the end date is BEFORE the start date in the range.
I only needed a list of what changes and not the files, that's why I used history.


text:
Q: Unable to locate button and href in Selenium I am trying to locate some elements in Selenium and I have problem.
There are no normal elements like ID etc.
Issue no 1 --> should click to Continue button
<a _ngcontent-c3="" routerlink="cms" href="/cms">Continue</a>

Issue no 2 --> should click to Add button
<button _ngcontent-c11="" aria-label="Add user" class="action-btn add" type="button">

Issue 2 html screenshot
I tried using fidning elements by PartialLinkText, I tried to make my own CSS selector/xPath, but test case always fails...
One of unsuccessful solutions for Issue 1:
WebElement continueButton = driver.findElement(By.partialLinkText("Continue"));
continueButton.click();

Any suggestions?
Thanks.

A: You can find button by class and i hope using this xpath your problem will be
Here your possible xpath is //a[@routerlink='cms'][text()='Continue'] and //button[@aria-label='Add user']/i']
WebElement Continue = (new WebDriverWait(driver, 30))
                        .until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@routerlink='cms'][text()='Continue']")));
                Continue.click();
            WebElement adduser = (new WebDriverWait(driver, 30))
                    .until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@aria-label='Add user']/i")));

            adduser.click();


text:
Q: Replace empty values in list of dictionaries by corresponding value i have a list of dictionaries with missing values. I want to replace the empty value with the corresponding value by the more efficient way.
Input:
[
    {"Host": "dailymotion", "Url": ""},
    {"Host": "youtube", "Url": ""},
    {"Host": "Vimeo", "Url": ""},
    {"Host": "", "Url": "https://www.dailymotion.com/video/x37j4ox"},
    {"Host": "", "Url": "https://www.youtube.com/watch?v=uDLQfA2o0"},
    {"Host": "", "Url": "https://vimeo.com/42399207"},
]

Output:
[
    {"Host": "dailymotion", "Url": "https://www.dailymotion.com/video/x37j4ox"},
    {"Host": "youtube", "Url": "https://www.youtube.com/watch?v=uDLQfA2o0"},
    {"Host": "Vimeo", "Url": "https://vimeo.com/42399207"},
]

A: You may

*

*pair the first half (raw[:len(raw) // 2]) with the second half (raw[len(raw) // 2:]) using zip

*then  take the Host from one (d1['Host']), and the Url from the other (d2['Url'])
raw = [{'Host': 'dailymotion', 'Url': ''},
       {'Host': 'youtube', 'Url': ''},
       {'Host': 'Vimeo', 'Url': ''},
       {'Host': '', 'Url': 'https://www.dailymotion.com/video/x37j4ox'},
       {'Host': '', 'Url': 'https://www.youtube.com/watch?v=uDLQfA2o0'},
       {'Host': '', 'Url': 'https://vimeo.com/42399207'}]

result = [{'Host': d1['Host'], 'Url': d2['Url']}
          for d1, d2 in zip(raw[:len(raw) // 2], raw[len(raw) // 2:])]
print(result)

A: Another solution:
lst = [
    {"Host": "dailymotion", "Url": ""},
    {"Host": "youtube", "Url": ""},
    {"Host": "Vimeo", "Url": ""},
    {"Host": "", "Url": "https://www.dailymotion.com/video/x37j4ox"},
    {"Host": "", "Url": "https://www.youtube.com/watch?v=uDLQfA2o0"},
    {"Host": "", "Url": "https://vimeo.com/42399207"},
]

hosts = [d["Host"] for d in lst if d["Host"] != ""]
urls = [d["Url"] for d in lst if d["Url"] != ""]

out = [{"Host": h, "Url": u} for h, u in zip(hosts, urls)]
print(out)

Prints:
[
    {"Host": "dailymotion", "Url": "https://www.dailymotion.com/video/x37j4ox"},
    {"Host": "youtube", "Url": "https://www.youtube.com/watch?v=uDLQfA2o0"},
    {"Host": "Vimeo", "Url": "https://vimeo.com/42399207"},
]

A: Another solution which works even if order of elements in your list is changed:
data = [
    {"Host": "dailymotion", "Url": ""},
    {"Host": "youtube", "Url": ""},
    {"Host": "Vimeo", "Url": ""},
    {"Host": "", "Url": "https://www.youtube.com/watch?v=uDLQfA2o0"},
    {"Host": "", "Url": "https://www.dailymotion.com/video/x37j4ox"},
    {"Host": "", "Url": "https://vimeo.com/42399207"},
]

hosts = [host['Host'] for host in data if host["Host"]]
urls = [host['Url'] for host in data if host["Url"]]
out = []
for host in hosts:
    for url in urls:
        if host.lower() in url.lower():
            out.append({"Host": host, "Url": url})
            break
print (out)

Output:
[{'Host': 'dailymotion', 'Url': 'https://www.dailymotion.com/video/x37j4ox'}, {'Host': 'youtube', 'Url': 'https://www.youtube.com/watch?v=uDLQfA2o0'}, {'Host': 'Vimeo', 'Url': 'https://vimeo.com/42399207'}]


text:
Q: Get variables always in differnet .phtml templates I have to use some variables again and again in different files.
$_product = $this->getProduct();
$_helper = $this->helper('catalog/output');
$_productType = $_product->getTypeID();
$_productName = $_helper->productAttribute($_product, $_product->getName(), 'name');
$_manufacturer = $_product->getAttributeText('manufacturer');
$_decor = $_product->getAttributeText('decor');
$_serie = $_product->getAttributeText('serie');
$originalImageWidth = $this->helper('catalog/image')->init($_product, 'image')->getOriginalWidth();
$originalImageHeight = $this->helper('catalog/image')->init($_product, 'image')->getOriginalHeight();
$originalImageRelation = $originalImageWidth / $originalImageHeight;

All this, I need in /templates/catalog/product/view.phtml and /templates/catalog/product/type/grouped.phtml and templates/catalog/product/media.phtml.
Is there a way to gather this in a central file and reuse it in all this places?

A: Yes, using magento you should be able to create a view helper which can be called from within the view.
You can check This tutorial which should give you everything you need to solve your problem


text:
Q: Join Duplicate Rows Into One Row in SQL Server id name number counter
1 test  010101 2
2 test  010101 1

I need to select the duplicates rows that have the same number-name combination. And I need to update the counter in one of the rows with the sum of the counter in the two rows and then delete the second row
I'm using the below query to select the duplication but I'm not being able to do the update:
SELECT *
FROM [prof]
WHERE ID NOT IN
  (
  SELECT MAX(ID)
  FROM [prof]
  GROUP BY number, name
  )

A: This will take two statements, best wrapped in a transaction:
update prof
set counter = (select SUM(counter) from prof group by number, name)
where ID in (select MAX(id) from prof group by number, name);

delete from prof where ID not in
(select MAX(id) from prof group by number, name);

A: This will update the counter and keep the first(lowest) id. It will only keep one unique id so if there are 3 or more rows with the same name, number this will still work.
Update [prof]
set counter=a.cnt
from [prof] p inner join (
    select name,number,sum(counter)cnt
    from [prof]
    group by name,number)a
on p.name=a.name and p.number=a.number;

delete [prof]
from [prof] join (
     select id,row_number () over (partition by name, number order by id asc)row
     from [prof])d
on [prof].id=d.id
where d.row>1;

A: Here's a way to do it using a cte. Here's what the cte looks like
id  name    number  counter totalCounter    DupNum
2   test1   10101         1            3         1
1   test1   10101         2            3         2
5   test2   10102         5           12         1
4   test2   10102         4           12         2
3   test2   10102         3           12         3

You can run the whole thing with the delete statement commented out to update the data. Then comment out the update statement and uncomment out the delete and run again.
;WITH table1_cte
AS
(
  SELECT id
    name,
    number,
    counter,
    ROW_NUMBER() over(PARTITION BY name, number ORDER BY id DESC) AS DupNum,
    SUM(counter) over (PARTITION BY name, number) AS totalCounter
  FROM prof
)

UPDATE table1_cte
SET counter = totalCounter
WHERE dupnum =1

--DELETE FROM table1_cte
--WHERE dupnum > 1

A: The update would be something like this.
update prof
set counter = counterSum
from prof join
(select name, number, sum(counter) counterSum
from prof
where whatever
group by name, number) temp on prof.name = temp.name and prf.number = temp.number
where whatever

The two "where whatever"s should be the same.


text:
Q: HP F370 - All lights are on & stable, printer not responding My printer HP F370 isn't working. When I power it on, all the lights namely Power, Error (Paper                                                                                & Ink), Page Count, Paper Type (Plain paper as well as Photo)                                                                                light up.
Ideally, after the initial setting up, only Power, Paper Count, Paper Type (either Plain or Photo) should light up.
Now, the printer isn't responding at all, although Windows is still able to detect it.
Please help me resolve this issue.

A: Is this a copier/printer? If it is, attempt to make a copy of something without using your computer. If it prints, then its not the printer. If it doesn't, unplug and replug into wall outlet and retry printing.
Also make sure that all of your cables are connected (to the computer of coarse).
At this point, it would be the print spooler. Reinstall the printer software on your computer and retry printing.
This should do the trick.