text:
Q: How to clear the recent searched keywords display on website - Recent Searches Widget I have installed a plugin from this question -->
Show most recent search terms in wordpress. I have the plugin working on my site, but i would like to ask that, how to clear the recent searched keywords that displaying on my website. I am running out of idea how to make it happen.
As you can see the result from my site: www.ncc.my. There are now 10 keywords on top of search box. I want to clear all the keyword. I have searched over the google but yet to get the answer. Here is the php code of the widget. See if you can get the solution to clear the keywords. Thanks!
    <?php
/*
Plugin Name: Recent Searches Widget
Plugin URI: http://www.poradnik-webmastera.com/projekty/recent_searches_widget/
Description: Shows recent searches in a sidebar widget.
Author: Daniel Frużyński
Version: 1.2
Author URI: http://www.poradnik-webmastera.com/
Text Domain: recent-searches-widget
*/

/*  Copyright 2009-2010  Daniel Frużyński  (email : daniel [A-T] poradnik-webmastera.com)

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

if ( !class_exists( 'RecentSearchesWidget' ) ) {

class RecentSearchesWidget {
    // Constructor
    function RecentSearchesWidget() {
        // Initialize plugin
        add_action( 'init', array( &$this, 'init' ) );

        // Page load
        add_action( 'template_redirect', array( &$this, 'template_redirect' ) );

        // Widgets initialization
        add_action( 'widgets_init', array( &$this, 'widgets_init' ) );
    }

    // Plugin initialization
    function init() {
        load_plugin_textdomain( 'recent-searches-widget', false, dirname( plugin_basename( __FILE__ ) ) . '/lang' );
    }

    // Page load
    function template_redirect() {
        if ( is_search() ) {
            // Store search term
            $query = $this->strtolower( trim( get_search_query() ) );

            $options = get_option( 'recent_searches_widget' );
            if ( !is_array( $options ) ) {
                $options = $this->get_default_options();
            }
            $max = $options['max'];

            $data = get_option( 'recent_searches_widget_data', array() );
            if ( !is_array( $data ) ) {
                if ( isset( $options['data'] ) ) {
                    $data = $options['data'];
                    unset( $options['data'] );
                    update_option( 'recent_searches_widget', $options );
                }
                if ( !is_array( $data ) ) {
                    $data = array();
                }
            }

            $pos = array_search( $query, $data );
            if ( $pos !== false ) {
                if ( $pos != 0 ) {
                    $data = array_merge( array_slice( $data, 0, $pos ),
                        array( $query ), array_slice( $data, $pos + 1 ) );
                }
            } else {
                array_unshift( $data, $query );
                if ( count( $data ) > $max ) {
                    array_pop( $data );
                }
            }

            update_option( 'recent_searches_widget_data', $data );
        }
    }

    // Widgets initialization
    function widgets_init() {
        $widget_ops = array(
            'classname' => 'widget_rsw',
            'description' => __('Shows recent searches', 'recent-searches-widget'),
        );
        wp_register_sidebar_widget( 'recentsearcheswidget', __('Recent Searches', 'recent-searches-widget'),
            array( &$this, 'widget_rsw' ), $widget_ops );
        wp_register_widget_control( 'recentsearcheswidget', __('Recent Searches', 'recent-searches-widget'),
            array( &$this, 'widget_rsw_control' ) );
    }

    function widget_rsw( $args ) {
        extract( $args );
        $title = isset( $options['title'] ) ? $options['title'] : '';
        $title = apply_filters( 'widget_title', $title );
        if ( empty($title) )
            $title = ' ';
        echo $before_widget . $before_title . $title . $after_title, "\n";
        $this->show_recent_searches( "
\n
", "
\n
", "
\n
" );
        echo $after_widget;
    }

    function show_recent_searches( $before_list, $after_list, $between_items ) {
        $options = get_option( 'recent_searches_widget' );
        if ( !is_array( $options ) ) {
            $options = $this->get_default_options();
        }

        $data = get_option( 'recent_searches_widget_data' );
        if ( !is_array( $data ) ) {
            if ( isset( $options['data'] ) ) {
                $data = $options['data'];
            }
            if ( !is_array( $data ) ) {
                $data = array();
            }
        }

        if ( count( $data ) > 0 ) {
            echo $before_list;
            $first = true;
            foreach ( $data as $search ) {
                if ( $first ) {
                    $first = false;
                } else {
                    echo $between_items;
                }

                echo '', wp_specialchars( $search ), '';
            }
            echo $after_list, "\n";
        } else {
            _e('No searches yet', 'recent-searches-widget');
        }
    }

    function widget_rsw_control() {
        $options = $newoptions = get_option('recent_searches_widget', array() );
        if ( count( $options ) == 0 ) {
            $options = $this->get_default_options();
            update_option( 'recent_searches_widget', $options );
        }
        if ( isset( $_POST['rsw-submit'] ) ) {
            $options['title'] = strip_tags( stripslashes( $_POST['rsw-title'] ) );
            $options['max'] = (int)( $_POST['rsw-max'] );
            $options['nofollow'] = isset( $_POST['rsw-nofollow'] );
            if ( count( $options['data'] ) > $options['max'] ) {
                $options['data'] = array_slice( $options['data'], 0, $options['max'] );
            }
            update_option( 'recent_searches_widget', $options );
        }
        $title = attribute_escape( $options['title'] );
        $max = attribute_escape( $options['max'] );
        $nofollow = $options['nofollow'];
    ?>

<?php _e('Title:', 'recent-searches-widget'); ?> <input class="widefat" id="rsw-title" name="rsw-title" type="text" value="<?php echo $title; ?>" />

<?php _e('Max searches:', 'recent-searches-widget'); ?> <input id="rsw-max" name="rsw-max" type="text" size="3" maxlength="5" value="<?php echo $max; ?>" />

<?php _e('Add rel="nofollow" to links:', 'recent-searches-widget'); ?> <input id="rsw-nofollow" name="rsw-nofollow" type="checkbox" value="yes" <?php checked( $nofollow, true ); ?>" />

    <input type="hidden" id="rsw-submit" name="rsw-submit" value="1" />
    <?php
    }

    // Make string lowercase
    function strtolower( $str ) {
        if ( function_exists( 'mb_strtolower' ) ) {
            return mb_strtolower( $str );
        } else {
            return strtolower( $str );
        }
    }

    function get_default_options() {
        return array(
            'title' => '',
            'max' => 4,
            'nofollow' => true,
        );
    }
}

// Add functions from WP2.8 for previous WP versions
if ( !function_exists( 'esc_html' ) ) {
    function esc_html( $text ) {
        return wp_specialchars( $text );
    }
}

if ( !function_exists( 'esc_attr' ) ) {
    function esc_attr( $text ) {
        return attribute_escape( $text );
    }
}

// Add functions from WP3.0 for previous WP versions
if ( !function_exists( 'get_search_link' ) ) {
    function get_search_link( $query = '' ) {
        global $wp_rewrite;

        if ( empty($query) )
            $search = get_search_query();
        else
            $search = stripslashes($query);

        $permastruct = $wp_rewrite->get_search_permastruct();

        if ( empty( $permastruct ) ) {
            $link = home_url('?s=' . urlencode($search) );
        } else {
            $search = urlencode($search);
            $search = str_replace('%2F', '/', $search); // %2F(/) is not valid within a URL, send it unencoded.
            $link = str_replace( '%search%', $search, $permastruct );
            $link = trailingslashit( get_option( 'home' ) ) . user_trailingslashit( $link, 'search' );
        }

        return apply_filters( 'search_link', $link, $search );
    }
}

$wp_recent_searches_widget = new RecentSearchesWidget();

// Show recent searches anywhere in the theme
function rsw_show_recent_searches( $before_list = "
\n
", $after_list = "
\n
", $between_items = "
\n
" ) {
    global $wp_recent_searches_widget;
    $wp_recent_searches_widget->show_recent_searches( $before_list, $after_list, $between_items );
}

} // END

?>

I can't see which part is for clearing up the keywords. Any suggestion? Thanks!
Updated part:
After the clearing history issue solved, this is the next issue i got.
function get_default_options() {
        return array(
            'title' => '',
            'max' => 4,  <---it was originally set to 10
            'nofollow' => true,
        );
    }
}

I have set the searched keywords to "4" which was originally set as 10, it should work and display only maximum 4 keywords by right. But, i don't know why the setting seems to follow the very first time i use this plugin. No matter how i tried to set from 0 to 5, the setting never take effect and the keywords there are still displaying as maximum 10 searches. Need help in this!
Any solution?

A: I found an "archaic" way to do it.
If you search for "store" in the script", at the end of it you'll find the string

update_option( 'recent_searches_widget_data', $data );

If you set $data to 0 (e.g. $data=0;)right before this line and then you try to search something, you'll be able to delete the search history.
Remember to delete the line where you set $data to 0, otherwise the plugin won't start to work again
Edit:
Sorry for the late response, but I have the answers for your question (and also another way to do the previous point).
What I understood is that from the script you can't change after the initialisation the number of elements that have to be shown. When does this happen? When you install the plugin. So you should unzip the folder, change the number of elements in the .php file, zip the folder and install again the plugin.
Not so tricky, but quite long.
Now, the good news.
I don't know if you have ever managed with the database that is behind wp, but there is a table (wp_options) where many part of code that wordpress uses are stored.
Usually here you can also find the data that the plugins set up.
And here we go: in that table there are two rows, called recent_searches_widget and recent_searches_widget_data.
In the first you can find the setting for the number of elements to be shown (its the i:10; that is set by default, if you haven't changed the script yet), in the other you can find the previous searches (and, if you want to delete them, you just need to change the value of the row to 0).


text:
Q: Minimum length Regex I need help enforcing a correct Australian phone number.  This is what I have so far.  How can I make this require the user to start the number with either '02,04,03,07 or 08 and it Must be 10 characters long?
^\({0,1}((0|\+61)(2|4|3|7|8)){0,1}\){0,1}(\ |-){0,1}[0-9]{2}(\ |-){0,1}[0-9]{2}(\ |-){0,1}[0-9]{1}(\ |-){0,1}[0-9]{3}$

A: If you want to allows exactly 10 characters then remove the unwanted (, -, +61 from your regex,
^((0)(2|4|3|7|8))[0-9]{2}[0-9]{2}[0-9]{1}[0-9]{3}$

DEMO

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get current time in the format YYYY-MM-DD-HH.MI.Sec.Ms using XSLT I have the following xml:
<root>
<Test>tested</Test>
</root>

Now, I want to add the current date time stamp in the format YYYY-MM-DD-HH.MI.Sec.Ms to a new node  for the above xml using XSLT. For example my resultant xml should look like below:
<root>
<Test>tested</Test>
<dateTimeStamp>2014-05-21-01.25.32.000000</dateTimeStamp>
</root>

Can anybody help me on this?
Can you please add the code for XSLT 1.0 also so that I can find the difference? I will give +1 for that.

A: You can use format-dateTime()...
XSLT 2.0
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="/*">
        <xsl:copy>
            <xsl:copy-of select="@*|node()"/>
            <dateTimeStamp>
                <xsl:value-of select="format-dateTime(current-dateTime(),'[Y0001]-[M01]-[D01]-[H01].[m01].[s].[f]')"/>
            </dateTimeStamp>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

Output
<root>
   <Test>tested</Test>
   <dateTimeStamp>2014-05-21-01.44.58.312</dateTimeStamp>
</root>

See http://www.w3.org/TR/2014/REC-xpath-functions-30-20140408/#rules-for-datetime-formatting for more info.

A: try something like:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="2.0">

    <xsl:strip-space elements="*"/>

    <xsl:output indent="yes" omit-xml-declaration="yes"/>

    <xsl:template match="/root">
        <xsl:variable name="timeNoMs" select="translate(substring-before(substring-before(string(current-time()), '+'), '.'), ':', '.')"/>
        <xsl:variable name="timeMs" select="format-number(number(substring-after(substring-before(string(current-time()), '+'), '.')), '##0000')"/>
        <xsl:copy>
            <xsl:copy-of select="node()|@*"/>
            <dateTimeStamp><xsl:value-of select="concat(substring-before(string(current-date()), '+'), '-', $timeNoMs, $timeMs)"/></dateTimeStamp>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>


text:
Q: Order of evaluation in C++ function parameters If we have three functions (foo, bar, and baz) that are composed like so...
foo(bar(), baz())

Is there any guarantee by the C++ standard that bar will be evaluated before baz?

A: In C++11, the relevant text can be found in 8.3.6 Default arguments/9 (Emphasis mine)

Default arguments are evaluated each time the function is called. The order of evaluation of function arguments is unspecified. Consequently, parameters of a function shall not be used in a default argument, even if they are not evaluated.

The same verbiage is used by C++14 standard as well, and is found under the same section.

A: From [5.2.2] Function call,

The order of evaluation of arguments is unspecified. All side effects of argument expression evaluations take effect before the function is entered.

Therefore, there is no guarantee that bar() will run before baz(), only that bar() and baz() will be called before foo.
Also note from [5] Expressions that:

except where noted [e.g. special rules for && and ||], the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified.

so even if you were asking whether bar() will run before baz() in foo(bar() + baz()), the order is still unspecified.

A: There's no specified order for bar() and baz() - the only thing the Standard says is that they will both be evaluated before foo() is called. From the C++ Standard,  section 5.2.2/8:

The order of evaluation of arguments
  is unspecified.

A: C++17 specifies evaluation order for operators that was unspecified until C++17. See the question What are the evaluation order guarantees introduced by C++17? But note your expression
foo(bar(), baz())

has still unspecified evaluation order.

A: No, there's no such guarantee. It's unspecified according to the C++ standard.
Bjarne Stroustrup also says it explicitly in "The C++ Programming Language" 3rd edition section 6.2.2, with some reasoning:

Better code can be generated in the
  absence of restrictions on expression
  evaluation order

Although technically this refers to an earlier part of the same section which says that the order of evaluation of parts of an expression is also unspecified, i.e.
int x = f(2) + g(3);   // unspecified whether f() or g() is called first

A: As others have already pointed out, the standard does not give any guidance on order of evaluation for this particular scenario. This order of evaluation is then left to the compiler, and the compiler might have a guarantee.
It's important to remember that the C++ standard is really a language to instruct a compiler on constructing assembly/machine code. The standard is only one part of the equation. Where the standard is ambiguous or is specifically implementation defined you should turn to the compiler and understand how it translates C++ instructions into true machine language.
So, if order of evaluation is a requirement, or at least important, and being cross-compiler compatible is not a requirement, investigate how your compiler will ultimately piece this together, your answer could ultimate lie there. Note that the compiler could change it's methodology in the future


text:
Q: How can i improve arrowhead line drawing using CoreGraphics? In my app i have view where user can draw arrows.
It works almost perfect.
If i swipe slowly i have nice result.
Image
Bu if i try to swipe faster i got the arrowhead somewhere but not at the very end of line.
image
Sorry, due to my reputation i can't post images here.
How Can i improve arrowhead line drawing to draw however fast i swipe?
To do this i use next method -
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

mouseSwiped = YES;

UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:self.view];

 UIGraphicsBeginImageContext(self.view.frame.size);
   [self.tempDrawImage.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];

  CGContextClearRect(UIGraphicsGetCurrentContext(),CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height));

   double slopy, cosy, siny;
   // Arrow size
   double length = 10.0;
   double width = 10.0;

   slopy = atan2((firstPoint.y - lastMovePoint.y), (firstPoint.x - lastMovePoint.x));
   cosy = cos(slopy);
   siny = sin(slopy);

   CGContextMoveToPoint(UIGraphicsGetCurrentContext(), firstPoint.x, firstPoint.y);
   CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
        //here is the tough part - actually drawing the arrows
   //a total of 6 lines drawn to make the arrow shape

   CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastMovePoint.x, lastMovePoint.y);

   CGContextAddLineToPoint(UIGraphicsGetCurrentContext(),
                           lastMovePoint.x +  (length * cosy - ( width / 2.0 * siny )),
                           lastMovePoint.y +  (length * siny + ( width / 2.0 * cosy )) );
   CGContextAddLineToPoint(UIGraphicsGetCurrentContext(),
                           lastMovePoint.x +  (length * cosy + width / 2.0 * siny),
                           lastMovePoint.y -  (width / 2.0 * cosy - length * siny) );
   CGContextClosePath(UIGraphicsGetCurrentContext());

   CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
   CGContextSetLineWidth(UIGraphicsGetCurrentContext(), brush );
   CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), red, green, blue, 1.0);
   CGContextSetBlendMode(UIGraphicsGetCurrentContext(),kCGBlendModeNormal);

   CGContextStrokePath(UIGraphicsGetCurrentContext());
   self.tempDrawImage.image = UIGraphicsGetImageFromCurrentImageContext();
   [self.tempDrawImage setAlpha:opacity];
   UIGraphicsEndImageContext();

   lastMovePoint = currentPoint;

A: From my experience when drawing with core graphics, when swiping fast over a view, the distance between the points every time touchesMoved: gets called is larger, and I see that you are using a lastMovePoint which can be further than you'd like, giving you unwanted results. This does not happen when moving slowly and the distance between each point is minimal (sometimes even less than 1 point)
I suggest working only with the firstPoint and currentPoint, calculate the angle and draw the arrow using only that, because, when it comes to it, to draw a line you only need the first and last point, it doesn't matter where the user touched before :)


text:
Q: Angularjs Fadeout then Fadein onclick I'm trying to fadeout a div element or paragraph, change the text inside of it, and fade it back in.
I am currently using the code below with jquery but would like to know how i could do the same with angular.
i tried quite a couple of things (angular-animate might implement it wrong) but has not really worked. i have just found the jquery option working. but i would like to expand my knowledge on angular and angular animate.

$("#main").fadeOut(25, function() {
        $(this).html('html');
        $(this).fadeIn();
    });

See the Pen Random Quote Machine


text:
Q: VSCode + Github, No initalize repository button Following several tutorials, but run into the same issue. I expect it's something simple, but I'm new to git and Visual Studio Code. I'm on Win10.
The "initialize repository" button mentioned everywhere is not there, just "SOURCE CONTROL" then a text box with "Message(Ctrl + Enter to commit on..." inside, then Changes with a 0.
I follow this to the one minute mark but don't have the button. Every other tutorial assumes you have it. https://www.youtube.com/watch?v=Ik3wFSyFaNc&t=60s
I've tried closing all folders and editors, and opening a folder, but it's not there.
When I close and open VSCode, the buttons in Source Control are are "Open Folder, and "Clone repository", with "no folder opened" in caps. When I open a folder from that button, it's the same, source control has no initialize button. The folder that I'm opening is empty (just created as per the vid tutorial).
What I expect (left side):
What I get:

A: If I look at the second screen grab for "What I get", doesn't it already show that you are in a branch "master" in the bottom left? The video you mention has it as "main". It looks like you have already initialized it as "master".

A: Make sure your %PATH% environment variable does include git.exe
When you launch VSCode in that environment, it should detect Git and proposes all Git-related options, like initializing a repository.


text:
Q: Scripting for table data in a file I have the following data file, EMP.txt:
SNO,NAME,GENDER,COMPANY,EMPID,SALARY,JOINING_DATE,PHONE_NO,LOCATION
1,sravan kumar,M,ibm,1095,20000,01-SEP-2014,7651523,HYDERABAD
2,Vijay Prakash,M,IBM,2056,30000,05-JAN-2014,9936789,HYDERABAD
3,Surya,M,HP,1046,30000,01-FEB-2013,8904561,BANGALORE
4,Karthik,M,APPLE,1023,10000,03-JUN-2014,756098,HYDERABAD
5,Latha,F,MAPR,1010,20000,05-FEB-2012,9874522,BANGALORE
6,Swetha,F,MAPR,1080,30000,04-JUN-2014,98701234,HYDERABAD
7,Sunil,M,GOOGLE,1098,34000,07-SEP-2014,993451,BANGALORE

the above data is stored in file EMP.txt
I Want script to list emp_name,Emp_id,Salary,location whose salary is greater than 20000.
plz help me

A: AS it is my work i tried to get the output Thank you @DavidPostill you made me to try by self
for var in cat EMP.txt | tail –n  +2                                                                                #tail -n +2 if for removing the header
do
sal=echo $var | cut -d "," -f6#for seleceting salary field
if [ $sal -gt 20000 ]
then
echo $var          #displaying each line from $var
fi
done


text:
Q: Sharing certificates encryped by password between DBs and instances Question:
I am trying to create a single (self signed) certificate and deploy across many databases and instances.
I create and backup the cert with:
USE MASTER
CREATE CERTIFICATE DavesCert ENCRYPTION BY PASSWORD ='S3creT!' WITH SUBJECT = 'The master cert'

BACKUP CERTIFICATE DavesCert TO FILE = 'd:\DavesCert.cer'
WITH PRIVATE KEY ( DECRYPTION BY PASSWORD = 'S3creT!' ,
FILE = 'd:\DavesCert.pvk' ,
ENCRYPTION BY PASSWORD = 'S3creT!' );

I restore with
USE FOO
GO

CREATE CERTIFICATE ERecruitStatsGatheringCert
FROM FILE = 'd:\DavesCert.cer'
WITH PRIVATE KEY (FILE = 'd:\DavesCert.pvk',
DECRYPTION BY PASSWORD = 'S3creT!')

and get the following error: "Please create a master key in the database or open the master key in the session before performing this operation."
I don't want to create a database master key. I'm happy to decrypt the cert by password as needed.
Background:
SaaS application.  Many to Many relationship between DB's and instances.
I need each DB to be able to query it's own stats by executing a stored procedure that wraps up some calls to DMV's to return the stats.
App runs under a low-privileged account. DMV's require VIEW SERVER STATE permission, therefore, I'm implementing signing of the stored procedures using certs.
Basic way of setting this up is to:

*

*Create a cert in the user DB.

*Backup/restore that cert to master.

*Create login in master, assigned that permissions, etc.

*Add Certificate to stored procedure.

I have test code for the above and it works well, however the model does not scale very well for deployment across multiple instances/dbs.
Therefore, I think I want to use the same cert across all DB's/instances.
Happy for other suggestions/approaches.
--Originally posted to Stack Exchange then moved on suggestion from another use

A: You only specify the password to decrypt the private key file with. You need to add a password to store the certificate with:
CREATE CERTIFICATE ERecruitStatsGatheringCert
ENCRYPTION BY PASSWORD = 'S3creT!
FROM FILE = 'd:\DavesCert.cer'
WITH PRIVATE KEY (
    FILE = 'd:\DavesCert.pvk',
    DECRYPTION BY PASSWORD = 'S3creT!');

But your Background information makes the whole exercise futile. You're doing it wrong. The correct sequence of actions is:

*

*Create a cert in the user DB

*Add the signature to the store procedure(s)

*Drop the private key of the certificate

*Backup/restore that cert to master (public key only!)

*Create login in master, assigned that permission, etc.

Notice that not only the private key never leaves the database, is in fact explicitly dropped right after signing the procedure. This is required in order to prevent further use of this certificate to sign other procedures and abuse the login permissions created at step 5. You repeat these steps on each database and use a different certificate on each database. You repeat these steps each time you modify any of the signed procedure and generate a new certificate each time.
As a general rule, any signature/encryption public/private key (RSA) scheme that requires a copy of the private key is broken. This is why is called private and this is what gives value to the signature: the knowledge that there exists only one instance of this private key in the world, therefore anything signed by it is proof that it came from the one and only owner/holder of the unique private key.

I know there are some who shun my recommendation of dropping the private key right after is used to sign the procedure. I stand by my recommendation, but the important thing for your problem is that it is not required to copy the private key into [master] in order to leverage the the code signing permission you desire. You can (and should) create the login derived from the certificate using just the public key.
Regarding automation: As I see it, basically it is a tool (script, app) that takes two inputs: a securable (procedure, function, module) and a permission (VIEW SERVER STATE). Everything else is an automated process (create a one-time-use throw-away cert, sign, export cert, import cert in [master], create login, grant permission). The names implied (cert name, login name) can all be generated.
Proliferation of names is a valid concern. An alternative would be to use only one certificate and associated private key, and the signature tool could add the private key when needed (when signing the procedure), then remove it after the signing. Is really a matter of how you run your shop and how important is the asset you're protecting. But the important thing is that you do not need to import the private key in [master].

A: I haven't used certificates and keys much in production but the way I understand the concept is that creating a certificate with a private key, means using the database master key to encrypt the private key of the certificate.
I found this article on technet: http://technet.microsoft.com/en-us/library/bb964742.aspx
The database master key is a symmetric key that is used to protect the private keys of certificates and asymmetric keys that are present in the database.
To see if I could use your certificate on another server, I created your certificate without a private key.
CREATE CERTIFICATE DavesCert WITH SUBJECT = 'The master cert'

Then I backed it up
BACKUP CERTIFICATE DavesCert TO FILE = 'D:\MSSQL\davescert.cer'

I moved the certificate to another server and restored it.
CREATE CERTIFICATE davescert FROM FILE = 'd:\mssql\davescert.cer'

View the certificate
SELECT name, certificate_id, pvt_key_encryption_type_desc from sys.certificates

name    certificate_id  pvt_key_encryption_type_desc
davescert   257 NO_PRIVATE_KEY

If you don't use a private key to encrypt your certificate they you don't need the database master key. If you do use a private key, then you will have to create a master key on each database where you use your certificate.

A: You should create a master key per server to avoid the error. Here's what I did to fix the same error on my secondary servers.
drop certificate [MyCertwithPK]
drop master key

create master key encryption by password = '4_Str0ng!MasterKey'

--verify.
open master key decryption by password = '4_Str0ng!MasterKey';
close master key;

--next.
create certifate [MyCertwithPK] from file = '\\SQL1\Backups\MyCertwithPK.cer'
with private key (file = '\\SQL1\Backups\MyCertwithPK.key' , decryption by
password = '4_Str0ng!CertKey') ;

--Note: My cert doesn't encrypt by password. Uses encryption hierarchy & private key instead.

--To clarify, these were my initial create/backup cmds on my **primary** svr.
create master key encryption by password = '4_Str0ng!MasterKey';
create certificate [MyCertwithPK] with subject = 'Certificate for SQL backups with Private Key' ;
backup certificate [MyCertwithPK] to file = '\\SQL1\Backups\MyCertwithPK.cer' with private key (file= '\\SQL1\Backups\MyCertwithPK.key', encryption by password = '4_Str0ng!CertKey') ;

Check this across the servers you wish to match databases with a master key that's encrypted by the server's service master key.
select name from sys.databases where is_master_key_encrypted_by_server=1

Reference: https://learn.microsoft.com/en-us/sql/relational-databases/security/encryption/sql-server-and-database-encryption-keys-database-engine
This paragraph helped me:

The copy of the DMK stored in the master system database is silently updated whenever the DMK is changed. However, this default can be changed by using the DROP ENCRYPTION BY SERVICE MASTER KEY option of the ALTER MASTER KEY statement. A DMK that is not encrypted by the service master key must be opened by using the OPEN MASTER KEY statement and a password.


text:
Q: Losing accuracy as thread speed increases So i have this simple thread that updates my TextBox with the new time difference every second.
try {
        Thread.sleep(1000);
    } catch(InterruptedException ex) {
        Thread.currentThread().interrupt();
    }

    editTextBox.setText(""+timeDifference);

But I want the TextBox to update faster, yet maintain the same value. So my idea was to reduce the sleep value to 1/4 of what it is now (250), and to keep my output the same I would also cut my output by 1/4, resulting in this:
try {
        Thread.sleep(250);
    } catch(InterruptedException ex) {
        Thread.currentThread().interrupt();
    }

    editTextBox.setText(""+timeDifference/4);

However the 2nd examples output is about 10% behind. Why is this? Does the computation of my processes take longer than 250ms and that's why its behind?
thanks in advance

A: Thread.sleep(250) does not mean that your thread will begin executing again exactly 250 ms later.
When you sleep a thread, its state passes to idle. When the sleep ends, it passes to active, which means that can be executed, but the scheduler may be busy executing another thread (or even chose other thread for execution before that.
Add to that the time needed to put back into execution a thread (change of environment) and and possible timing errors, and you have an delay. Most of that variation, while not constant, is not related to the time spent sleeping, so the difference is comparatively bigger when the sleep time is small.
In the end, remember that Java is not a Real Time System and so you cannot expect times to follow a close "schedule" (for want of a better word).

A: It really doesn't matter what the problem with this program is, because you shouldn't invoke any methods on a Swing UI component from a thread other than the Event Dispatch Thread.
Instead, the timer thread should be periodically passing a task to invokeLater(). That task should quickly compute the time to be displayed and set the text property of the text box.
Runnable task = new Runnable() {
  private long previous = System.currentTimeMillis();
  @Override
  public void run() {
    editTextBox.setText(String.valueOf(System.currentTimeMillis() - previous));
  }
};
while (true) {
  try {
    Thread.sleep(250);
  }
  catch (InterruptedException ex) {
    Thread.currentThread().interrupt();
    break;
  }
  SwingUtilities.invokeLater(task);
}


text:
Q: Perl error: Can't modify non-lvalue subroutine call at I get the following error with my class: "Can't modify non-lvalue subroutine call at file.do line 26." My file.do looks something like this:
line 2:    use BookController;
line 3:    my $bookdb = BookController->new();
...
line 26:   $bookdb->dbh = 0;

And my BookController.pm looks like this:
#!/usr/bin/perl

package BookController;
use strict;

sub new
{
    my $this = shift;
    my $class = ref($this) || $this;

    my $self = {};
    $self->{DBH} = undef;

    bless $self, $class;

    return ($self);
}

sub dbh
{
    my $self = shift;
    $self->{DBH} = shift if (@_);
    return $self->{DBH};
}

1;

Any suggestions?

A: You're attempting to set the return value of the sub, hence the error. Judging by the actual method, I think you meant:
$bookdb->dbh(0);


text:
Q: Read specific columns and rows from .text Well, I need to read columns and rows from a .txt
and get only the data I need.
Example: The file "sample.txt" has the following content
C = Columns
R = Rows
  C1  C2 C3

R1   0     0  0       3694440008091082330089 ALBINA HANSEN OF OLMEDO 00000075000000022091401520117873
I need the following data for each row:
0003694440008091082330089 ALBINA HANSEN DE OLMEDO       00000075000000022091401520117873
(The series of numbers and letters above the value of the first line)

*

*First Value: Starts at C19 to C25 (2330089)

*Second Value: Starts at C28 to C50 (ALBINA HANSEN DE OLMEDO)

*Third Value: Starts at C64 to C68 (75000)

*Fourth Value: Starts at C73 to C78 (220914)

*Fifth Value: It is only the C80 column (1)
And I need to display the data in a message box:
I have the following code:
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim fileReader As String
        fileReader = My.Computer.FileSystem.ReadAllText("C:\Users\cogentvaio\Desktop\Banco Itau\TXT-FOMENTO ANGELIUS.txt")
        MsgBox(fileReader)
    End Sub
End Class

This allows me to read the entire contents of .txt
Hopefully you can help me with this, I'm learning to program in vb.net.

I'll show you my code, I can not see the boundaries made with substrinng, I used the code you suggested,
Imports System
Imports System.IO
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim fileReader = My.Computer.FileSystem.ReadAllText("C:\Users\cogentvaio\Desktop\Banco Itau\ejemplo\-TXT-ITAU ANGELIUS.txt")
    Dim line As String
    For Each line In fileReader
        If line.Length > 80 Then
            Dim c1 = line.Substring(18, 7)
            Dim c2 = line.Substring(28, 50)
            Dim c3 = line.Substring(64, 68)
            Dim c4 = line.Substring(73, 78)
            Dim c5 = line.Substring(80)

        End If
    Next

    MessageBox.Show(fileReader)

End Sub

End Class
And what I got was this
IMAGE_PHOTO
I don't know where is my mistake

A: string.Substring is your friend here. This method extracts substring from a string starting from a char index and getting back the requested number of chars (length). Also remember that an array (a string is an array of chars) starts always at index zero, so your values Cx values should be decremented by one.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    ' Instead of ReadAllText, use ReadAllLines to have your input splitted in an array of strings
    Dim fileReader = System.IO.File.ReadAllLines(......)

    for each line in fileReader

       ' To avoid nasty exceptions be sure that the line is at least 81 chars long
       if line.Length > 80 Then
          Dim c1 = line.Substring(18, 7)
          Dim c2 = line.Substring(27, 23)
          Dim c3 = line.Substring(63, 5)
          Dim c4 = line.Substring(72, 6)
          Dim c5 = line.Substring(79, 1)

          .... process these values....
          .... for example ....
          Dim newLine = string.Join(" ", c1,c2,c3,c4,c5)
          MessageBox.Show(newLine)

       End if
    Next
End Sub

This changes takes a line, extract the part and creates a new string with only the parts required joined together with a space. Then prints out this new text. Of course, you want a join of all the rows with these subparts you need to add the newLine variable to a List( Of String) an then do a final join of the single rows
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    ' Instead of ReadAllText, use ReadAllLines to have your input splitted in an array of strings
    Dim fileReader = System.IO.File.ReadAllLines(......)
    Dim subText = New StringBuilder()
    for each line in fileReader
        if line.Length > 80 Then
          ....

          Dim newLine = string.Join(" ", c1,c2,c3,c4,c5)
          subText.Add(newLine)
       End if
    Next
    MessageBox.Show(string.Join(Environment.NewLine, subText))

However your indexes doesn't seem to correctly point to the data required.
This substring extraction seems to find correctly your data
  Dim c1 = line.Substring(18, 7)
  Dim c2 = line.Substring(26, 23)
  Dim c3 = line.Substring(56, 5)
  Dim c4 = line.Substring(65, 6)
  Dim c5 = line.Substring(72, 1)


text:
Q: If demand of a product is normally distributed how to choose order quantity to maximize profit Assume the demand of a product $x$ is normally distributed with mean $\mu$ and standard deviation $\sigma$. If the order quantity of this product is $y$, then the profit will be $ax-b(y-x)$ for $y\ge x$ and $ay$ for $y<x$ where $a$ and $b$ are positive. How to choose $y$ to maximize profit?
I interpret this problem as the following:
$X$~$N(\mu,\sigma)$, define $Z=aX-b(y-X)$ for $X\le y$ and $ay$ for $X>y$, and we need to choose a $y$ to maximize the expectation of $Z$. I think firstly we need to express the expectation of $Z$ explicitly, and so we need to compute CDF $F(z)=P(Z\le z)$ and then take derivative we will get PDF of $Z$ and then we can compute the expectation. Now, I am not sure what is CDF $F$ here.
Moreover, intuitively I guess we should choose $y$ that maximize $g(x)=xf(x)$($f(x)$ is the PDF of $X$) as the order quantity.
Thanks for any hint.

A: Fix $y$. Then $Z$ is a deterministic function of $X$, i.e. $Z=G(X)$ where $G(x) = ax-b(y-x)$ for $x<y$ and $G(x) = ay$ for $x>y$. Now computing the expectation of $Z$ is easy :
$$\mathbb E[Z] = \mathbb E[G(X)] = \int_{\mathbb R} G(x)f_X(x)dx$$
where $f_X$ is the PDF of $X$. So
$$\mathbb E[Z] = \int_{-\infty}^y[ax-b(y-x) ]f_X(x)dx + \int_{y}^{+\infty}ayf_X(x)dx.$$
We want to optimize in $y$ so we differentiate in respect to $y$. Using Leibniz's differentiation rule,
$$\frac d{dy}\mathbb E[Z] = [ay-b(y-y)]f_X(y)\times 1 + \int_{-\infty}^y-bf_X(x)dx\ \ - ayf_X(y) + \int_{y}^\infty af_X(x)dx. = a(1-F_X(y)) - b F_X(y) = a-(a+b)F_X(y)$$
It becomes 0 when $F_X(y) = a/(a+b)$.


text:
Q: Built-in Vector Types in Numba Cuda Can I use the built-in vector type float3 that exists in Cuda documentation with Numba Cuda? I know that is possible to use with PyCuda, for example, a kernel like:
addarrs_codetext = """
__global__ void add_3darrs_broadcast(float3 *out, float3 *a, float3 *b, int* SZ)
{
    const int M = SZ[0];
    const int N = SZ[1];
    const int S = SZ[2];
    const int tx = threadIdx.x;
    const int bx = blockIdx.x;
    const int BSZ = blockDim.x;
    int t;
    for (int s=0;s<S;s++)
    {
        t = s*BSZ+tx;
        if(t<N)
            dest[bx*N+t].x = b[t].x + a[bx].x;
            dest[bx*N+t].y = b[t].y + a[bx].y;
            dest[bx*N+t].z = b[t].z + a[bx].z;
        __syncthreads();
    }
}
"""

How could I do the same with Numba Cuda?
Thanks!

A:
Can I use the built-in vector type float3 that exists in Cuda documentation with Numba Cuda?

No, you cannot.
Numba CUDA Python inherits a small subset of supported types from  Numba's nopython mode. But that is all. There are a lot of native CUDA features which are not exposed by Numba (at October 2021). Textures, video SIMD instructions and vector types are amongst them.


text:
Q: Can a student with a heavy math background start learning physics with Goldstein's "Classical Mechanics"? Can a student with a heavy math background start learning physics with Goldstein's "Classical Mechanics"?
Or is the book too obtuse with basic physics that I need to start elsewhere?

A: Not only can but you should. Goldstein is a great book. Good mixture between math and ideas.

A: You can, certainly, it is a good book. But there are many other good books that you might also appreciate, with more advanced math. E.g. the "classics"
V. I. Arnold, Mathematical Methods of Classical Mechanics, Graduate Texts in Mathematics, Vol. 60, Springer, 1989
R. Abraham and J.E. Marsden, Foundations of Mechanics, AMS Chelsea Publishing, 2008.
J.E. Marsden, T.S. Ratiu, Introduction to Mechanics and Symmetry: A Basic Exposition of Classical Mechanical Systems, Springer, 1999.
Michael Spivak's new book on mechanics (Spivak,  Physics for Mathematicians.  Mechanics I, 2010) seems to be great, too. See http://mathpop.com/mechanics1.htm.


text:
Q: bootstrap multiselect drop down is not dropping down I'm using the bootstrap multiselect plugin and binding the data to it with knockout js. It is in this jsfiddle. The options actually do get data-bound to the multiselect - You can confirm this by right clicking the multiselect element in the jsfiddle output window and inspecting it, and the <option>'s are indeed there. However, clicking the multiselect element does not cause the dropdown to drop down.
The bootstrap multiselect does not seem to know that it has <option>'s in the <select>, this is proven when I use the disableIfEmpty configuration option, it disables the multiselect permanently. Why does the bootstrap multiselect not know that it has options, thus causing it to not open the drop down?
jsfiddle here

A: You can only instantiate your multiselect widgets after knockout has done its rendering, which is basically after your apply bindings.
To get the idea, check out this forked fiddle: http://jsfiddle.net/r0kbch7u/
I've basically moved the $("#category-select").multiselect() code from your CategorySelect constructor to your document loaded event listener.


text:
Q: Why does Ubuntu show slightly less RAM than my computer has built in? My machine's RAM is 8 GB. I have recently installed Ubuntu 17.04.
Why does Ubuntu show me that it has only 7.7 GB and not the full 8 GB?

A: It's probably because the kernel is using part of your memory. Since kernel memory can't be freed in most cases, Ubuntu just reports the total available (less the amount used by the kernel).
You can find out more detail by using the following commands:
Check how big your RAM sticks claim to be:
sudo dmidecode | grep Size | grep MB

Check how much RAM is available for general use:
free -h

Estimate how much memory your kernel is using:
cat /proc/meminfo | grep Slab

Check for memory "stolen" by your graphics card:
dmesg | grep stolen

This is actually covered in this answer (which has more details).
Hope that helps.

A: This is most probably due to your graphics card reclaiming some of the RAM for its own purposes (mostly texture storage). There's also a chunk of memory reserved by the kernel, but it's tiny (a few megabytes) compared to the discrepancy you see.
On many systems, the amount of RAM reserved for graphics is configurable in BIOS settings.

A: Your actual RAM is measured in 8 Gigabytes = 8,000,000,000 bytes
that is, 8,000,000,000/(1024*1024)=7629.39 MeBi Bytes=7.62939 GiBi Bytes
Since it is rounded up, it is shown as 7.7 GiBi Bytes.


text:
Q: UITextField delegate jumping to 100% CPU usage and crashing upon using keyboard shortcut So, I have a UITextField subclass which is it's own Delegate and is crashing when keyboard shortcuts are used. It maxes out on CPU and doesn't give an error. Without assigning itself as it's Delegate, it works without problem. When it is assigned as it's Delegate, it crashes even when using none of the (optional) methods.
Try it yourself:
Subclass UITextField.
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

        self.delegate = self;

    }
    return self;
}

It should crash.
EDIT
Backtrace:
* thread #1: tid = 0x3bb8d, 0x39f14726 libobjc.A.dylib`lookUpImpOrNil + 18, queue = 'com.apple.main-thread, stop reason = signal SIGSTOP
    frame #0: 0x39f14726 libobjc.A.dylib`lookUpImpOrNil + 18
    frame #1: 0x39f0dcb6 libobjc.A.dylib`class_respondsToSelector + 34
    frame #2: 0x39f1d05c libobjc.A.dylib`-[NSObject respondsToSelector:] + 32
    frame #3: 0x323b9242 UIKit`-[UITextField respondsToSelector:] + 46
    frame #4: 0x325c88a2 UIKit`-[UITextField customOverlayContainer] + 50
    frame #5: 0x325c8730 UIKit`-[UITextField automaticallySelectedOverlay] + 28
    frame #6: 0x32554208 UIKit`-[UIKeyboardImpl inputOverlayContainer] + 424
    frame #7: 0x32553942 UIKit`-[UIKeyboardImpl _autocorrectPromptRects] + 454
    frame #8: 0x323c7530 UIKit`-[UIKeyboardImpl updateAutocorrectPrompt:] + 368
    frame #9: 0x323e63e0 UIKit`-[UIDelayedAction timerFired:] + 80
    frame #10: 0x305fbe6c Foundation`__NSFireTimer + 64
    frame #11: 0x2fbe1e86 CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 14
    frame #12: 0x2fbe1aa2 CoreFoundation`__CFRunLoopDoTimer + 794
    frame #13: 0x2fbdfe2a CoreFoundation`__CFRunLoopRun + 1218
    frame #14: 0x2fb4a540 CoreFoundation`CFRunLoopRunSpecific + 524
    frame #15: 0x2fb4a322 CoreFoundation`CFRunLoopRunInMode + 106
    frame #16: 0x348812ea GraphicsServices`GSEventRunModal + 138
    frame #17: 0x324011e4 UIKit`UIApplicationMain + 1136
    frame #18: 0x0009929c Today`main(argc=1, argv=0x27d79c80) + 164 at main.m:29

A: Problem solved by changing the delegate to the object which inits my text view.

A: I encountered the same issue today when working with a self-delegating UITextField subclass.  If it is not possible to change the delegate to something other than self, I would recommend overriding respondsToSelector rather than implementing a customOverlayContainer method that may return an invalid object (are you sure it's supposed to be an instance of UITextField?  How do you know iOS isn't asking for a UIView or a CGLayer or any other type of object?)
-(BOOL) respondsToSelector:(SEL)aSelector {

    NSString * selectorName = NSStringFromSelector(aSelector);

    if ([selectorName isEqualToString:@"customOverlayContainer"]) {

        NSLog(@"preventing self.delegate == self crash");

        return NO;
    }

    return [super respondsToSelector:aSelector];
}

A: I solved this by custom customOverlayContainer and return the textFiled. eg.
@implementation CustomTextField

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.delegate = self;
    }
    return self;
}

- (id)customOverlayContainer {
    return self;
}

@end

Tested on iOS 7 and iOS 6.


text:
Q: Access Node.js variable from javascript file in front end Is it possible to access a node.js variable from the backend in a javascript file with pug?
It seems to work when using inline javascript inside the pug template, but I can't get it to work if when link to a .js file.
This is my router:
router.get("/test", function (req, res) {
  testVar = {
    title: "Test Title",
    string: "Test string"
  };
  res.render("test", { testVar: testVar });
});

My template looks like this:
h1 #{testVar.title}

div #{testVar.string}

//- Inline JavaScript works
script.
    var object = !{JSON.stringify(testVar)};
    console.log(object.title);
    console.log(object.string);

//- This does not work
script(src="/javascripts/test.js")

test.js have the same content as the inline javascript:
var object = !{JSON.stringify(testVar)};
console.log(object.title);
console.log(object.string);

If I try to run it with test.js enabled I get an error saying:
Uncaught SyntaxError: missing : after property id

A: the problem is with !{JSON.stringify(testVar)}
JSON.stringify turns your object to a string, then you put it in an object and turn it into a boolean.
So var object isn't an object and you're getting an error when referring to object.id.
You can test this by console.log(object) or even testVar.


text:
Q: Why we add $2\pi k$ when taking a root When taking a root, let say $r=\sqrt[n]{w}$ we look at $w$ as $pe^{(\theta+2\pi k) i}$
But in this case we have repetition so we take $k=0,1,...,n-1$ we not just take  $w=pe^{\theta i}$?

A: Because in the process of taking the $n$'th root of $pe^{(\theta + 2k\pi)i}$, we calculate the exponent as $(\theta + 2k\pi)i/n$, which, for different values of $k$, really does give different complex numbers.
Example: The number $i$ may be written as $1\cdot e^{(\pi /2)i}$. Thus $\sqrt[2]i = \sqrt[2]1\cdot e^{(\pi/4) i}$. However, $i$ can also be written as $1\cdot e^{(\pi/2 + 2\pi)i}$, and using that, we get $\sqrt[2]i = \sqrt[2]1\cdot e^{(\pi/4+\pi)i}$, which is not the same.


text:
Q: How to get the dynamic change of main modal from JS for checkbox in partial view .cshtml file (Knockout js)? I have a main view _New.cshtml and from this view I am calling a partial view _Contact.cshtml.
_New.cshtml
Here I have a checkbox for "Print" which is checked/unchecked based on parameter dataModel.Files([@i].IsPrint
@for (var i = 0; i < Model.Files.Count; i++)
{

    Print
    <input type="checkbox" data-bind="checked: dataModel.Files()
    [@i].IsPrint, value: dataModel.Files()[@i].IsPrint()"
    id="IsPrint, click: getPrint.bind($data,@i)" name="Documents[@i].IsPrint" />

    @{
             Html.RenderPartial("_Contact", Model);
     }

}

_Contact.cshtml
I have a checkbox here also in which I have binded "IsEmail" from passed dataModel.
@{var v = Model.Files[Model.Index].Contacts[Model.Index].IsEmail ? "true" : "false";}
<input type="checkbox" data-bind="checked:@v,click: $parent.getEmail.bind($data,@Model.Index)" />

new.js
Both the view's have common js file.
this.getEmail = function (index) {
     if (dataModel.Files()[index].IsPrint() == true) {
             dataModel.Files()[index].IsPrint(false);
         }
         else {
            dataModel.Files()[index].IsPrint(true);
           }
           return true;
};
this.getPrint = function (index) {
     if (dataModel.Files()[index].IsPrint() == true) {
             dataModel.Files()[index].Contacts()[index].IsEmail(false);
         }
         else {
            dataModel.Files()[index].Contacts()[index].IsEmail(true);
           }
   return true;
};

So, on click from checkbox in contact.cshtml I am changing the boolean value of IsPrint in the model for the corresponding index. Eventually it is getting checked or unchecked in the main View. But when I am trying to click on Is Print from main view and then updating the IsEmail value in js the model value change doesn't reflect in the partial view (checked:always stays the initial value)? How to get the scope of the model inside the partial view and get the parameters change dynamically?


text:
Q: How do I query current and previous months data from a DB that uses UNIX EPOCH time? I am trying to query a DB that is in UNIX EPOCH time format, so I can't use any of the standard modifiers that I am used to. I heard Carbon was useful for these things however I still haven't mastered it's use.
    $date = Carbon::today();
    $this_months_values = (new $propdash->custommenuitems->monthly_real_time_feed)::where('time',$date->copy()->format('m'))->sum('data');
    $one_month_agos_values = (new $propdash->custommenuitems->monthly_real_time_feed)::sum('data');

    $two_month_agos_values = (new $propdash->custommenuitems->monthly_real_time_feed)::sum('data');
    $three_month_agos_values = (new $propdash->custommenuitems->monthly_real_time_feed)::sum('data');
    $four_month_agos_values = (new $propdash->custommenuitems->monthly_real_time_feed)::sum('data');
    $five_month_agos_values = (new $propdash->custommenuitems->monthly_real_time_feed)::sum('data');
    $six_month_agos_values = (new $propdash->custommenuitems->monthly_real_time_feed)::sum('data');
    $seven_month_agos_values = (new $propdash->custommenuitems->monthly_real_time_feed)::sum('data');
    $eight_month_agos_values = (new $propdash->custommenuitems->monthly_real_time_feed)::sum('data');
    $nine_month_agos_values = (new $propdash->custommenuitems->monthly_real_time_feed)::sum('data');
    $ten_month_agos_values = (new $propdash->custommenuitems->monthly_real_time_feed)::sum('data');
    $eleven_month_agos_values = (new $propdash->custommenuitems->monthly_real_time_feed)::sum('data');

So how would I go about doing that?
This is what the collection looks like when you are not filtering anything. As you can tell the 'time' is in EPOCH UNIX time.
Collection {#9512 ▼
  #items: array:2 [▼
    0 => Feed115 {#9511 ▼
      #connection: "emoncms"
      #table: "feed_115"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:2 [▼
        "time" => 1552716000
        "data" => 222.314
      ]
      #original: array:2 [▼
        "time" => 1552716000
        "data" => 222.314
      ]
      #changes: []
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #fillable: []
      #guarded: array:1 [▶]
    }
    1 => Feed115 {#9510 ▼
      #connection: "emoncms"
      #table: "feed_115"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:2 [▼
        "time" => 1552629600
        "data" => 405.903
      ]
      #original: array:2 [▼
        "time" => 1552629600
        "data" => 405.903
      ]
      #changes: []
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #fillable: []
      #guarded: array:1 [▶]
    }
  ]
}

I tried this but it did not work:
    $date = Carbon::today();

    /* Yearly Realtime Consumption data feed */
    $startthis = Carbon::now()->startOfMonth()->timestamp;
    $endthis = Carbon::now()->endOfMonth()->timestamp;
    $this_months_values = (new $propdash->custommenuitems->monthly_real_time_feed)::where('time',[$startthis, $endthis])->sum('data');

A: You might be able to do something like this for an individual month:
$start = Carbon::parse('-5 months')->startOfMonth()->timestamp;
$end = Carbon::parse('-5 months')->endOfMonth()->timestamp;

$five_month_agos_values = YourModel::whereBetween('time', [$start, $end])->sum('data');

Or if you don't like the idea of parsing strings:
$start = Carbon::now()->subMonths(5)->startOfMonth()->timestamp;


text:
Q: Lie's theorem about infinitesimal rigid motions and riemannian manifolds curvature The theorem states that in a Riemannian connected finite dimensional manifold of 3 dimensions the existence of a 6-dimensional group of local isometries that determine infinitesimal rigid displacements implies that this manifold must possess a constant curvature(one can read the complete statement and proofs in Lie's "Theorie der Transformationsgruppen, Vol. 3").
I'm interested in the conclusions one can derive from this restriction, for instance does this theorem imply some sort of limitation on Riemannian manifolds of variable curvature with respect to the existence of stationary points of functionals(variational principles) on the manifold?
Added: To be more specific, if we use the language of principal G-bundles and consider a tangent frame bundle with the total space as the group of local isometries, the fiber G the point-stabilizer group and the base manifold that on wich the isometry group acts,  does this theorem limit the maximum number of dimensions of the total space to 6 for a 3-dimensional base manifold and to a finite number for any finite-dimensional base manifold?
Also, do the infinitesimal rigid motions expressed by the local isometry group in a Riemannian manifold determine the maximum number of dimensions of the group of symmetries, defined as vanishing functional derivatives and corresponding Euler-Lagrange equations routinely used in multidimensional calculus of variations, of any objects defined on the manifold that undergo such rigid motions?

A: The claim you are quoting is simply false in dimensions $>3$, just take the Riemannian direct product of, say, hyperbolic 3-space with, say, Euclidean space of dimension $>0$.
The correct result which holds in all dimensions $n$ is:
Theorem. Suppose that $M$ is an $n$-dimensional connected Riemannian manifold such that every point in $M$ has a neighborhood which admits a local isometry group of dimension $d=\frac{n(n+1)}{2}$. Then $M$ has constant sectional curvature.
Specializing to the  case $n=3$ we get $d=6$.
Edit: As for the proof, it is absolutely straightforward: Check that the local isometry group acts locally transitively on $M$ with point-stabilizers locally isomorphic to $O(n)$. From this conclude that the action is locally transitive on the bundle of tangent $2$-planes over $M$.  Hence, the sectional curvature is locally constant, thus globally constant by connectivity of $M$.
As for "limitations" imposed on the Riemannian metric on $M$, this theorem simply imposes limitations on the dimension of the group of local isometries of a Riemannian manifold. The dimension $n(n+1)/2$ is maximal. In case $n=3$, the group of local isometries cannot be 5-dimensional, but can be 4-dimensional and 6-dimensional. I do not think you can get anything else from this result. One can get sharper estimates on the dimension of the local isometry group in higher dimensions.  As for "stationary points of functionals", you have to be much more specific for this to be answerable.


text:
Q: Scanf will only scan once in a For loop scanf will only allow me to input a single number before ending the for loop, whereas I should be able to input 7, here's the code:
#include <stdio.h>

int main(){
    float M, N=0;
    int n;
    for(n=1; n<8; n++){
        printf("Digite o peso da pessoa nro %d em kg:", n);
        scanf(" &N");
        M+=N/7;
        n=n+1;
    }
    printf("A media de peso em kg e: %f", M);
}

Does anyone know what's going on?

A: Replace the following line:
scanf(" %f", &N);

f stands for your float.


text:
Q: mock __init__(self, ...): TypeError: super(type, obj): obj must be an instance or subtype of type I try to mock the constructor of a class like this https://stackoverflow.com/a/17950141/633961
class MockedHttpResponse(django.http.response.HttpResponseBase):
    def check(self, *args, **kwargs):
        status=kwargs.get('status')
        if status is None and self.status_code==200:
            return # default
        if not status==self.status_code:
            raise self.AssertionErrorStatusCode('%s!=%s' % (self.status_code, status))

    def __init__(self, *args, **kwargs):
        self.check(*args, **kwargs)
        django.http.response.HttpResponseBase.__init__(self, *args, **kwargs)

    class AssertionErrorStatusCode(AssertionError):
        pass

usage in test:
def test_assert_http_response_status__with_self_mocking(self):
    from django.http import HttpResponse
    with mock.patch('django.http.response.HttpResponse', testutils.MockedHttpResponse):
        HttpResponse(status=200)

But I get this exception:
Traceback (most recent call last):
  File "/home/foo_eins_di514/src/djangotools/djangotools/tests/unit/utils/test_testutils.py", line 129, in test_assert_http_response_status__with_self_mocking
    HttpResponse(status=200)
  File "/home/foo_eins_di514/lib/python2.7/site-packages/django/http/response.py", line 258, in __init__
    super(HttpResponse, self).__init__(*args, **kwargs)
TypeError: super(type, obj): obj must be an instance or subtype of type

How can I mock a class and modify its __init__() method?

A: I can't say for sure since I'm not an expert on how mock works, but unless it's doing some very impressive gymnastics, you've statically bound the original django.http.HttpResponse object to HttpResponse within the test module scope (from django.http import HttpResponse).  Unless mock is dynamically modifying locals() \ globals() within the context manager to patch over aliased references to the patch target, no amount of patching on the module itself will impact the HttpResponse object you are using in the test.  I think at least one step you need to take is to reference the class from the module explicitly within the patch context manager, though it looks like you could also use with mock.patch('django.http.response.HttpResponse', testutils.MockedHttpResponse) as HttpResponse: to get the desired result.  I think you may also want to use new_callable=testutils.MockedHttpResponse as a kwarg to patch.


text:
Q: Damaged USB after using RUFUS I made a bootable Linux USB . Everything works fine after the install i tried to reuse my usb to copy some files. Size of the USB is now 4mb "EFI partition".
I jumped to DISKPART to clean and set partition :
 Microsoft DiskPart version 10.0.22000.1

Copyright (C) Microsoft Corporation.
On computer: XXXXXXX

DISKPART> list disk

  Disk ###  Status         Size     Free     Dyn  Gpt
  --------  -------------  -------  -------  ---  ---
  Disk 0    Online         1863 GB  1024 KB        *
  Disk 1    Online           15 GB  1024 KB

DISKPART> select disk 1

Disk 1 is now the selected disk.

DISKPART> clean

DiskPart has encountered an error: A device which does not exist was specified.
See the System Event Log for more information.

DISKPART>

Tried with Disk management in windows

A: For anyone who have problems after using Rufus .
Re-open Rufus , connect your usb drive , select your usb drive and select
Non Bootable in Boot selection .
This fixed my problem.

A: Please install PowerISO (https://www.poweriso.com/) software, then connect your USB and open PowerISO. Choose Tools >> Clean USB option. It will format your USB as FAT32. After that format your USB manually choosing NTFS format. Everything will be fine.


text:
Q: Why is my sound cutting out in my WPF application? So this is strange...in my C#, WPF app, I have a button that, when clicked, plays a short audio clip that acts as help text. About 50% of the time it works beautifully...the other 50% it gets cut off and I can't figure out why. Even the point at which it is being cut off varies.
I thought that, maybe, the code was going out of scope or something and then stopping so I put it in another thread...that didn't work at all...so now I am not sure what to do.
Here is the code of my button click event.
try
{
    string path = System.IO.Path.Combine(ConfigurationManager.AppSettings["MediaPath"], Global.Language);
    path = System.IO.Path.Combine(path, "visitorTypes.mp3");

    if (Global.PlaySound)
    {
        string p = path.ToString();
        MediaPlayer mplayer = new MediaPlayer();
        mplayer.Open(new Uri(p, UriKind.Absolute));
        mplayer.Play();
    }

    //a bunch of other code

}
catch (Exception ex)
{
    Util.HandleError(ex);
}

Thoughts?

A: It could be that mplayer is being garbage collected because it has local scope. Try making the media player object a member variable of a class that has application lifetime.


text:
Q: Gearman: troubles with first use I tried to start with Gearman. After downloading and setting it, gearman_version() works. But, when I start server and try to init worker like so:
php myFileName.php &

I see the code:

And when I init the client, I see code too. What am I doing wrong?

A: i don`t know why, but the examples from youtube was not correct in my case. The first scripts, which worked I get from http://php.net/manual/ru/gearman.examples-reverse-bg.php

A: You likely have short open tags disabled on your install. Notice, running a php file that doesn't actually contain any PHP will just echo the contents of the file.
>$ echo 'hello' > text.php
>$ php text.php
hello
>$

You can verify the setting for your install with the following
>$ php -i | grep "short_open_tag"
short_open_tag => On => On

If tags are On you're all set.


text:
Q: C++ heapsort confusion This might be a weird question but I'm trying to figure out why the following code works.
It seems as though this code should be used where the heap elements index starts at 1 but it's starting at 0 and the sort is completed correctly.
I say that because the left child is calculated as (element*2) and the right child is (element*2 + 1). This would make the left child for the element with index 0 also have index 0.
#include <iostream>
using namespace std;

void siftDown(int numbers[], int root, int bottom) {
    int done, maxChild, temp;
    done = 0;
    while ((root*2 <= bottom) && (!done)) {
        if (root*2 == bottom)
            maxChild = root * 2;
        else if (numbers[root*2] > numbers[root*2 + 1])
            maxChild = root * 2;
        else
            maxChild = root * 2 + 1;

        if (numbers[root] < numbers[maxChild]) {
            temp = numbers[root];
            numbers[root] = numbers[maxChild];
            numbers[maxChild] = temp;
            root = maxChild;
        } else {
            done = 1;
        }
    }
}

void heapSort(int numbers[], int n) {
    int i, temp;

    for (i = n/2; i >= 0; i--) {
        siftDown(numbers, i, n - 1);
    }

    for (i = n-1; i >= 1; i--) {
        temp = numbers[0];
        numbers[0] = numbers [i];
        numbers [i] = temp;
        siftDown(numbers, 0, i-1);
    }
}

int main() {
    int cases;
    int n;
    int count;

    cin >> cases;

    for (int i=0; i < cases; i++) {
        cin >> n;
        int array[n];
        for (int j=0; j < n; j++) {
            cin >> array[j];
        }

        heapSort(array, n);
        for (int k=0; k < n; k++) {
            cout << array[k];
        }
        cout << endl;
    }
}

A: For the case when root = 0, there are two sub-cases: numbers[0] > numbers[1], or not. In the first, maxchild is set to 0. The next "if" clause - effectively "numbers[0] < numbers[0]" - necessarily evaluates to false, and so "done" is set to 1 and the loop terminates.
If numbers[1] >= numbers[0], then maxchild is set to 1. The next clause becomes "numbers[0] < numbers[1]" which may be true or may be false if numbers[0] == numbers[1]. If it is false, the loop terminates as before. If it is true, numbers[0] and numbers[1] are swapped - thus the larger number correctly moves to the top of the heap - and root becomes 1, the loop continues and in this case you understand how it works.
I think it's easiest to consider this case as a heap where the root only has one child (and all other nodes have two children as normal).


text:
Q: get value from custom UITableViewCell I have a custom UITableViewCell that has a UISegmentedControl object. My UITableView (questionnaire form) has 6 of this custom cell (6 segmented controls). I am having trouble getting the selectedSegmentIndex of the segment controls. My guess is that the cells are being released after the table is generated. I am getting the values using the following code:
MyCustomCell *q1 = (MyCustomCell *)[tableView cellForRowAtIndexPath:[NSIndexPath indexPathWithIndex:0]];

int segmentIndex = (int) q1.segmentedController.selectedSegmentIndex;

the int segmentIndex is always giving the same value of 0 no matter what the selected index is.

A: You must use the right method to initialize your index path for the section and row you want use, otherwise row and section properties won't be correctly set, and you will get the same cell each time :
+(NSIndexPath *)indexPathForRow:(NSUInteger)row inSection:(NSUInteger)section;.
The code looks like :
// getting the cell at third row of first section
NSIndexPath *ip = [NSIndexPath indexPathForRow:2 inSection:0];
MyCustomCell *q1 = (MyCustomCell *)[tableView cellForRowAtIndexPath:ip];
int segmentIndex = (int) q1.segmentedController.selectedSegmentIndex;

You could also consult : NSIndexPath UIKit Additions Reference for more information.


text:
Q: Confidence intervals on a cutpoint of ROC curve Can one estimate and calculate a confidence interval for the value of a cutpoint obtained from the ROC curve?
for example, using the pROC package in R:
> library(pROC)
> data(aSAH)
> roc1 <- roc(aSAH$outcome,
            aSAH$s100b, percent=TRUE,
            # arguments for ci
            ci=TRUE, boot.n=100, ci.alpha=0.9, stratified=FALSE,
            # arguments for plot
            plot=TRUE, auc.polygon=TRUE, max.auc.polygon=TRUE, grid=TRUE,
            print.auc=TRUE, show.thres=TRUE)

with confidence intervals:
> ci.thresholds(roc1)

will produce:
95% CI (2000 stratified bootstrap replicates):
 thresholds  sp.low sp.median sp.high se.low se.median se.high
       -Inf   0.000      0.00    0.00 100.00    100.00  100.00
      0.065   6.944     13.89   22.22  92.68     97.56  100.00
      0.075  12.500     22.22   31.94  80.49     90.24   97.56
      0.085  20.830     30.56   41.67  77.99     87.80   97.56
      0.095  27.780     38.89   50.00  70.73     82.93   92.68
      0.105  37.500     48.61   59.72  65.85     78.05   90.24
      0.115  43.060     54.17   65.28  60.98     75.61   87.80
      0.135  47.220     58.33   69.44  53.66     68.29   80.49
      0.155  58.330     69.44   80.56  51.22     65.85   80.49
      0.205  70.830     80.56   88.89  48.78     63.41   78.05
      0.245  73.580     81.94   90.28  43.90     58.54   73.17
      0.290  73.610     83.33   91.67  34.15     51.22   65.85
      0.325  76.350     84.72   93.06  29.27     46.34   60.98
      0.345  79.170     87.50   94.44  29.27     43.90   58.54
      0.395  80.560     88.89   95.83  26.83     41.46   56.10
      0.435  83.330     90.28   95.87  24.39     39.02   53.66
      0.475  90.280     95.83  100.00  19.51     34.15   48.78
      0.485  93.060     97.22  100.00  17.07     31.71   46.34
      0.510 100.000    100.00  100.00  14.63     29.27   43.90

QUESTION
Why there is no CI on thresholds?
UPDATE
I realised how to specify the best cutpoint to be not youden, but topleft?
rocobj <- plot.roc(aSAH$outcome,
                   aSAH$s100b,
                   main="Confidence intervals",
                   percent=TRUE,  ci=TRUE, print.auc=TRUE)
# print the AUC (will contain the CI)
ciobj <- ci.se(rocobj,
               specificities=seq(0, 100, 5))
plot(ciobj, type="shape", col="#1c61b6AA")
plot(ci(rocobj, of="thresholds", thresholds="best", best.method="topleft"))

A: You fixed the thresholds. They cannot vary in the boostrap.
Let's simplify and look at only one threshold:
> ci.thresholds(roc1, thresholds = 0.205)
95% CI (2000 stratified bootstrap replicates):
 thresholds sp.low sp.median sp.high se.low se.median se.high
      0.205  70.83     80.56   88.89  48.78     63.41   78.05

By doing that, you fixed the threshold to 0.205 and asked: how much can my sensibility and specificity vary at that threshold? The threshold is your fixed point. It has no uncertainty associated with it. You implicitly did the same by asking for all thresholds, even though you didn't spell it out.
If you want a CI on the threshold you have to reformulate the question, for instance how uncertain is the "best" threshold?
> ci.coords(roc1, x="best", ret="threshold")
95% CI (2000 stratified bootstrap replicates):
                           2.5%   50% 97.5%
threshold best: threshold 0.155 0.205 0.485

Now of course you could ask: let's now fix the sensitivity at X = 0.9, and see how the threshold varies there. But this is more tricky than it sounds: you see, most of the ROC curve is actually a line between discrete points. Most points on the ROC curve actually fall between two thresholds. To calculate a threshold for an arbitrary point, you would need to interpolate a threshold value there. This is doable, but requires some parametric assumptions about the distribution of thresholds. Are you doing a linear interpolation? That would be pretty bad for most datasets I've ever seen.
So far, pROC is not able to reliably calculate a threshold at an arbitrary coordinate, so questions like how uncertain is the threshold at a fixed sensitivity X? result in errors or missing values. It's a can of worms I tried to open but I never reached anything useful.


text:
Q: Data Truncation exceptions and Spring MVC Context
I have a 3 layer architecture web application based on Spring Framework:
DAO<--Service<--Web application
The current DAO implementation uses Springs jdbcTemplate. The web application is built with Spring MVC.
Question
Which technique is appropiate to stop data truncation exceptions coming from the DAO layer? Is it correct to cut the inputs in the service layer? Should we  rely on validators in the controllers or services? Should we just throw exceptions in the service layer?

A: If you are using spring , then you create a class that implements validator. Here is something that will help you out.


text: Q: Run a code in python 2 in jupyter notebook in python 3 My jupyter notebook is runing python 3 and need to run a code writen in python 2. I remember that is possible in python 2 to make a call from the future and run a codenin python 3. Is it possible to do the reverse?


text:
Q: SSH times outs after few secs between two Virtual Machines created under GCE Created two VM under Google Compute Engine and trying to do SSH for transferring files between them using SCP. But SSH times outs after few sec between two virtual machines
Tried all the flags options in sshd_config and ssh_config, but still its not working


text:
Q: Disable plugin function to use my own I have copied a function from a plugin because I intend to run the same function with some minor changes.
So, to prevent the plugin function running and also mine, I am trying to disable the plugins function.
Plugin function code
/* new product */
function um_activity_new_woo_product( $post_id ) {
....
}
add_action('save_post', 'um_activity_new_woo_product', 99999, 1 );

I thought to try the below, but has not stopped the function from running:
add_filter( 'um_activity_new_woo_product',  '__return_false' );
Any ideas or changes to try?

A: You can use remove_action() to remove a function from a specified action hook. Documentation
remove_action( string $tag, callable $function_to_remove, int $priority = 10 )

This function removes a function attached to a specified action hook. This method can be used to remove default functions attached to a specific filter hook and possibly replace them with a substitute.
So in your case,
// Remove the function from 'save_post' action
remove_action('save_post', 'um_activity_new_woo_product', 99999 );

// Add your own function my_activity_new_woo_product(), to 'save_post' action
add_action('save_post', 'my_activity_new_woo_product', 99999, 1 );

I hope this may help.


text:
Q: Android: multiple intents to gmail I have one link to gmail.When I click to the link the intent open two or more windows with gmail. I think maybe this is the main problem "Intent.ACTION_SEND".
Thanks in advance.
// TextView button for Email address
emailLink.setOnTouchListener(new View.OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        //email address
        String emailAddress = "some_email@gmail.com";
        String subject = "Write a topic";

        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.putExtra(Intent.EXTRA_EMAIL, new String[]{emailAddress});
        intent.putExtra(Intent.EXTRA_SUBJECT, subject);
        intent.setType("text/plain");
        startActivity(intent);

        return true;
    }
});

A: Replace
 intent.setType("text/plain");

with
 // need this to prompts email client only
 intent.setType("message/rfc822");

A: try this
Intent intent= new Intent(android.content.Intent.ACTION_SEND);
                    intent.setType("application/octet-stream");

A: Did you add logs to see if your onTouch is called multiple times ?
Try to replace setOnTouchListener by setOnClickListener.
I think that setOnTouchListener is called for ACTION_DOWN + ACTION_UP (when you click and when your remove your finger from the TextView)


text:
Q: SQLite and android I am new to android and I am creating an app that stores students info. I am not able to validate login using SQLITE. When I run the below code it directs me to the login page but I get the error "Unfortunately yourapp has stopped".
public class LoginActivity extends Activity {
    final EditText txt_usn = (EditText) findViewById(R.id.usn);
    final EditText txt_psw = (EditText) findViewById(R.id.password);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
    }
       public void loginListener(View v){
           DBAdapter db= new DBAdapter(getBaseContext());
           db.open();
           db.InsertData("1cr11is004", "rai123");
           Cursor cur = db.fetchStudent( txt_usn.getText().toString() , txt_psw.getText().toString());
           System.out.println("cur.getCount()   "+cur.getCount());
           if(cur.getCount()!=0)
            {
                String usn=cur.getString(1);
                if(usn.equals("1cr11is004"))
                {   }else{  }
                System.out.println("Query succedded");
                Toast.makeText(getBaseContext(), "Success! Valid USN and password", Toast.LENGTH_LONG).show();

                db.close();
            }
            else
                Toast.makeText(getBaseContext(), "Please enter Valid USN and password", Toast.LENGTH_LONG).show();

       }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.login, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_login,
                    container, false);
            return rootView;
        }
    }

}

And below is the DBAdapter.java
public class DBAdapter {
        private static final String DATABASE_NAME = "Student_Info";
        private static final int DATABASE_VERSION = 2;
        private static final String DATABASE_CREATE_STUDENTS = "create table Students (ID integer primary key autoincrement, "
                + "USN varchar, Password varchar);";
        private static final String DATABASE_SELECT_STUDENTS="students";
        public static final String Student_ID = "ID";
        public static final String Student_USN = "USN";
        public static final String Student_PASSWORD = "Password ";
        private final Context context;
        private DatabaseHelper DBHelper;
        private SQLiteDatabase db;

        public DBAdapter(Context ctx)
        {
            this.context = ctx;
            DBHelper = new DatabaseHelper(context);
        }
        private static class DatabaseHelper extends SQLiteOpenHelper
        {
            DatabaseHelper(Context context)
            {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            }

            public void onCreate(SQLiteDatabase db)
            {
                System.out.println("Creating table");

                db.execSQL(DATABASE_CREATE_STUDENTS);
                //I commented this line after my initial run since
                //I wanted to add users using SQLite Browser and the
                //table need only be created once.
            }

            public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
                //empty method

            }
        }
        public DBAdapter open() throws SQLException
        {
            db = DBHelper.getWritableDatabase();
            return this;
        }
        public void close()
        {
            DBHelper.close();
        }
        public Cursor fetchStudent(String usn, String password)
        {
               Cursor myCursor = db.query(DATABASE_SELECT_STUDENTS,
                          new String[] { Student_ID, Student_USN, Student_PASSWORD },
                         Student_USN + "='" + usn + "' AND " +
                         Student_PASSWORD + "='" + password + "'", null, null, null, null);

               if (myCursor != null) {
                    myCursor.moveToFirst();
               }
               return myCursor;
          }
        public void InsertData(String usn, String password)
        {
            String sql="INSERT INTO students (USN,Password) VALUES('"+usn+"','"+password+"')";
            db.execSQL(sql);
        }

}

This Is The Error shown by logcat

04-18 02:04:33.010: W/dalvikvm(757): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
04-18 02:04:33.110: E/AndroidRuntime(757): FATAL EXCEPTION: main
04-18 02:04:33.110: E/AndroidRuntime(757): java.lang.IllegalStateException: Could not execute method of the activity
04-18 02:04:33.110: E/AndroidRuntime(757):  at android.view.View$1.onClick(View.java:3591)
04-18 02:04:33.110: E/AndroidRuntime(757):  at android.view.View.performClick(View.java:4084)
04-18 02:04:33.110: E/AndroidRuntime(757):  at android.view.View$PerformClick.run(View.java:16966)
04-18 02:04:33.110: E/AndroidRuntime(757):  at android.os.Handler.handleCallback(Handler.java:615)
04-18 02:04:33.110: E/AndroidRuntime(757):  at android.os.Handler.dispatchMessage(Handler.java:92)
04-18 02:04:33.110: E/AndroidRuntime(757):  at android.os.Looper.loop(Looper.java:137)
04-18 02:04:33.110: E/AndroidRuntime(757):  at android.app.ActivityThread.main(ActivityThread.java:4745)
04-18 02:04:33.110: E/AndroidRuntime(757):  at java.lang.reflect.Method.invokeNative(Native Method)
04-18 02:04:33.110: E/AndroidRuntime(757):  at java.lang.reflect.Method.invoke(Method.java:511)
04-18 02:04:33.110: E/AndroidRuntime(757):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
04-18 02:04:33.110: E/AndroidRuntime(757):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-18 02:04:33.110: E/AndroidRuntime(757):  at dalvik.system.NativeStart.main(Native Method)
04-18 02:04:33.110: E/AndroidRuntime(757): Caused by: java.lang.reflect.InvocationTargetException
04-18 02:04:33.110: E/AndroidRuntime(757):  at java.lang.reflect.Method.invokeNative(Native Method)
04-18 02:04:33.110: E/AndroidRuntime(757):  at java.lang.reflect.Method.invoke(Method.java:511)
04-18 02:04:33.110: E/AndroidRuntime(757):  at android.view.View$1.onClick(View.java:3586)
04-18 02:04:33.110: E/AndroidRuntime(757):  ... 11 more
04-18 02:04:33.110: E/AndroidRuntime(757): Caused by: java.lang.NullPointerException
04-18 02:04:33.110: E/AndroidRuntime(757):  at com.abhineel.studentinfo.LoginActivity.loginListener(LoginActivity.java:39)
04-18 02:04:33.110: E/AndroidRuntime(757):  ... 14 more
04-18 02:04:33.250: W/ActivityManager(163):   Force finishing activity com.abhineel.studentinfo/.LoginActivity
04-18 02:04:33.310: W/WindowManager(163): Failure taking screenshot for (164x246) to layer 21015
04-18 02:04:33.850: W/ActivityManager(163): Activity pause timeout for ActivityRecord{4132cda8 com.abhineel.studentinfo/.LoginActivity}

A:
04-18 02:04:33.110: E/AndroidRuntime(757): Caused by: java.lang.NullPointerException
04-18 02:04:33.110: E/AndroidRuntime(757):  at com.abhineel.studentinfo.LoginActivity.loginListener(LoginActivity.java:39)

The LogCat states there is an null reference exception at line 39 in the method loginListener
You need to look there.


text:
Q: I want to loop through an array and modify attributes Here is my code
var input_buttons = ["#one","#two","#three"];
var substr = input_buttons.split(',');
for(var i=0; i< substr.length; i++)
{
   substr.attr('value', '');
}

Why doesn't this work?

A: Your first problem is calling split(',') on an array. However, if you just want to set the values of all those to a blank string you can do:
$('#one,#two,#three').val('');

If you want to set different values you'd need to loop through:
$('#one,#two,#three').each(function() {
  // this == the HTML node (not a jQuery element)
  this.value = someValue; // someValue would set outside
};

A: You already have an array, there is nothing to split, this only works on strings. You'd also have to pass the ID to jQuery before you can cal attr. In this case val is even better.
var input_buttons = ["#one","#two","#three"];
for(var i=input_buttons.length; i--;) {
   $(input_buttons[i]).val('');
}

But shorter would be using the multiple selector:
$('#one, #two, #three').val('');

or if you already have the array, create a string by joining the IDs:
$(input_buttons.join(',')).val('');

A: I'm wondering why you are calling:
var substr = input_buttons.split(',');

By the nature of your input_buttons, you already have an array. All you should have to do is:
var input_buttons = ["#one","#two","#three"];
for(var i=0; i< substr.length; i++)
{
   $(input_buttons[i]).attr('value', '');
}

A: var input_buttons = ["#one","#two","#three"];
$.each(input_buttons, function(idx, value) {
    $(value).val('');
});

Or even better and shorter:
$('#one, #two, #three').val('');

You could also give those elements a common class name and then use this:
$('.className').val('');

A: your array contains just the id but not the actual object
try this
var input_buttons = ["#one","#two","#three"];

for(var i=0; i< input_buttons.length; i++)
{
   $(input_buttons[i]).removeAttr('value');
}

A: Try the following to remove an attribute:
var input_buttons = ["#one","#two","#three"];
for(var i=0; i< input_buttons.length; i++)
{
   $(input_buttons[i]).removeAttr('value');
}

The reason your code does not work is in the overloading of jQuery functions.  .attr('value', '') evaluates to .attr('value'), which returns the value of value as opposed to setting it.  The reason is that '' evaluates to false.

A: input_buttons is already an array - don't split it.
To use .attr you need it to be a jquery object, so call $(input_buttons[i]).attr


text:
Q: if statement displaying in text box without executing calculation I'm new at this. The input is showing in the text box but not making the calculation for the if statement.

$w.onReady(function () {
$w("#generatequote").onClick((event) => {

var SR = Number($w("#SR").value);
    if (SR<100) {
        $w("#quotetext").value = SR * 2;
    }

    //first try- does not calculate
    $w("#quotetext").value = fin  + "\n" + (name + "\n" + email + "\n" + phonenumber + "\n" + address + "\n"
    + ($w("#quotetext").value = SR))

    //Second Try- does not calculate
    $w("#quotetext").value = fin  + "\n" + (name + "\n" + email + "\n" + phonenumber + "\n" + address + "\n"
    + ($w("#SR").value = SR))

I have also tried replacing "#quotetext" in the if statement with "#SR" but it displays nothing
This is the code displaying the additional else statements
var SR = Number($w("#SR").value);
if (SR<100) {
$w("#quotetext").value = SR * 2;
}
else if (SR>=100&&SR<300) {
$w("#quotetext").value = SR * 1.5;
    }
    else if (SR>=300&&SR<600) {
        $w("#quotetext").value * 1.25;
    }
    else if(SR>=600) {
        $w("#SR").value = ("SR");
    }
    $w("#quotetext").value = fin  + "\n" + (name + "\n" + email + "\n" + phonenumber + "\n" + address + "\n" + ($w("#SR").value = SR))

A: You are reassigning your $w("#quotetext").value after the if statement ends. Either put the next code in else blocks or the previous outputs won't be shown as they will get replaced by later ones.
Just don't reassign the $w("#quotetext").value after your if statements end, or use a variable in your if statements instead of using $w("#quotetext").value
var SR = Number($w("#SR").value);
if (SR<100) {
    SR = SR * 2;
}
else if (SR>=100&&SR<300) {
    SR = SR * 1.5;
    }
    else if (SR>=300&&SR<600) {
        SR= SR * 1.25;
    }
    else if(SR>=600) {
        SR = ("SR");
    }
    $w("#quotetext").value = fin  + "\n" + (name + "\n" + email + "\n" + phonenumber + "\n" + address + "\n" + (SR))


text:
Q: composer require failing to install new package Yii2 My OS : Ubuntu 20.0
My PHP Version : PHP 7.4.15
I'm working on a project based on Yii2 frame work, I'm trying to add a new package called "kartik-date-time-picker" using the below command :
composer require kartik-v/yii2-widget-datetimepicker "dev-master"

But it fails and giving me the output like :
./composer.json has been updated
Loading composer repositories with package information
Warning from https://repo.packagist.org: You are using an outdated version of Composer. Composer 2.0 is now available and you should upgrade. See https://getcomposer.org/2
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested package sunhater/kcfinder (locked at dev-master) is satisfiable by sunhater/kcfinder[dev-master] but these conflict with your requirements or minimum-stability.
  Problem 2
    - Installation request for filipajdacic/yii2-cpanel-email-creator * -> satisfiable by filipajdacic/yii2-cpanel-email-creator[dev-master].
    - Removal request for filipajdacic/yii2-cpanel-email-creator == 9999999-dev
  Problem 3
    - robregonm/yii2-pdf dev-master requires php ^5.6 || ~7.0.0 || ~7.1.0 || ~7.2.0 || ~7.3.0 -> your PHP version (7.4.15) does not satisfy that requirement.
    - robregonm/yii2-pdf dev-master requires php ^5.6 || ~7.0.0 || ~7.1.0 || ~7.2.0 || ~7.3.0 -> your PHP version (7.4.15) does not satisfy that requirement.
    - robregonm/yii2-pdf dev-master requires php ^5.6 || ~7.0.0 || ~7.1.0 || ~7.2.0 || ~7.3.0 -> your PHP version (7.4.15) does not satisfy that requirement.
    - Installation request for robregonm/yii2-pdf dev-master -> satisfiable by robregonm/yii2-pdf[dev-master].

Installation failed, reverting ./composer.json to its original content.

How I can solve this problem ? I'm running on PHP 7.4.15 Version and Ubuntu 20.0 Operating system.
my composer.json :
{
    "name": "yiisoft/yii2-app-advanced",
    "description": "Yii 2 Advanced Project Template",
    "keywords": ["yii2", "framework", "advanced", "project template"],
    "homepage": "http://www.yiiframework.com/",
    "type": "project",
    "license": "BSD-3-Clause",
    "support": {
        "issues": "https://github.com/yiisoft/yii2/issues?state=open",
        "forum": "http://www.yiiframework.com/forum/",
        "wiki": "http://www.yiiframework.com/wiki/",
        "irc": "irc://irc.freenode.net/yii",
        "source": "https://github.com/yiisoft/yii2"
    },
    "minimum-stability": "stable",
    "require": {
        "php": ">=5.6.0",
        "yiisoft/yii2": "~2.0.14",
        "yiisoft/yii2-bootstrap": "~2.0.0",
        "yiisoft/yii2-swiftmailer": "~2.0.0 || ~2.1.0",
        "dmstr/yii2-adminlte-asset": "^2.6",
        "kartik-v/yii2-export": "*",
        "kartik-v/yii2-widget-datepicker": "@dev",
        "kartik-v/yii2-field-range": "*",
        "2amigos/yii2-multi-select-widget": "*",
        "yii2mod/yii2-rbac": "*",
        "robregonm/yii2-pdf": "dev-master",
        "2amigos/yii2-ckeditor-widget" : "*",
        "kartik-v/yii2-editable": "dev-master",
        "kartik-v/yii2-widget-select2": "dev-master",
        "wbraganca/yii2-dynamicform": "*",
        "filipajdacic/yii2-cpanel-email-creator": "*"
    },
    "require-dev": {
        "yiisoft/yii2-debug": "~2.1.0",
        "yiisoft/yii2-gii": "~2.1.0",
        "yiisoft/yii2-faker": "~2.0.0",
        "codeception/codeception": "^4.0",
        "codeception/module-asserts": "^1.0",
        "codeception/module-yii2": "^1.0",
        "codeception/module-filesystem": "^1.0",
        "codeception/verify": "~0.5.0 || ~1.1.0",
        "symfony/browser-kit": ">=2.7 <=4.2.4"
    },
    "config": {
        "process-timeout": 1800,
        "fxp-asset": {
            "enabled": false
        }
    },
    "repositories": [
        {
            "type": "composer",
            "url": "https://asset-packagist.org"
        }
    ]
}


text:
Q: Replacing all occurrences of words in a text file according to user input Let's say I have a text file with the following:
dog
dog
cat
dog
bird
cat

I would ask the user what dog, cat, and bird should be replaced with. For example, dog = red, cat = yellow, and bird = green. My text file then is the following:
red
red
yellow
red
green
yellow

How can I go about identifying unique words, and ask the user what to replace each unique word with?
I know if I do:
content = open('tags.txt' 'r').readlines()
content_set = set(content)

I would remove duplicate entries.
How about asking a user what to replace these words with? And then go on replacing these words?
Here is my previous code, which opens a csv file and inserts contents into a text file:
import csv

csv_location = input("Location of CSV: ")
csv_location_get = csv_location.replace('\\','/')

with open(csv_location_get, 'r') as csv_file:
    reader = csv.reader(csv_file)
    next(reader)
    for row in reader:
        # sku_row = row[0]
        category_row = row[6].split(';')
        category_split = category_row[0]

        with open('tags.txt', 'a') as txt_file:
            txt_file.write(category_split + '\n')

    content_old = open('tags.txt', 'r').readlines()

    content_new = set(content_old)

print(content_new)

A: You can do it very easily
First the text file that is be worked on has to be asked by the file in prompt or in command line so that and file can be opened and edited. -- like
open file (filename)
test1.txt (enter)
Then you can display the option available to the user -- like
1) Change all the occurrence of the particular word / letter
2) Save and exit
3) display file text (print the file)

based on uesr input -- (for your program input will be 1)

here you have 2 options

First option
Prompt the user for entering the word to change its occurrence in the file with the another word.

Second option (most likely your choice)
display word by word unique
like this
id      value     count
1-->   dog     (25 places)
2-->   cat    ( 2 places)
enter the number and the new word to change all the occurrence
id new_Value
1 red
then you can change read the file for all the occurrence and change it with given word.
and then again prompt user with the option

1) Change all the occurrence of the particular word / letter
2) Save and exit
3) display file text (print the file)
then user may view or he may save and exit
you can do these things in copy or temporary text document of the original and when the user saves and exit make the changes to the original one
Thanks

A: i do not know how to change the text file but you can create new one as you wish.
my solution is that : i would create two arraylist one contains all words with repetions if there is, and one contains all words without repetion. Liket that:
list1 : {dog, dog, cat, dog, bird, cat}
list2 : {dog, cat, bird}
Then i would print every word and ask for what user want to replace them with one by one.
After that with one "for loop" and "if statement", i would change them


text:
Q: Is there a Linux Equivalent of Macrium Reflect? I am using dell precision 3520 running ubuntu 18.04 lts. I am trying to replace my HDD with SSD. I would like to have all my data transferred to the new disk. On Windows there is Macrium Reflect to do this (if there is a way of using Macrium in ubuntu, please tell me). How would I do this in linux?

A: Clonezilla Live is one equivalent of Macrium Reflect and provides a GUI, which may be considered easier than doing the same job with dd. Both are Open Source, free as in beer.

A: StorageCraft's ShadowProtect SPX covers both Windows and Linux systems including Ubuntu 18.04 and 20.04. I've used it for years and find it to be both convenient and reliable for Enterprise environments and small networks. Sorry this answer came so late.