text:
Q: Put download button in gridview I have a table called tblfiles with columns
id             int

Name           varchar(50)
ContentType    varchar(50)
Data           varbinary(MAX)

the id is incremental, name is the name of the file being uploaded, Content type tells the type of the file being uploaded such as "application/PDF" or "application/ms-word" etc... and data is where the Binary data is being stored.
I have managed to upload data into the database.
I have added a gridview to display the data automatically binded (You know not manually which is only SELECT all from tblfiles) I want a column that will display a download hyperlink or button to download the file.
Remember all data is being stored in database not a folder!!
So How can I do this ??

A: Try to create the Grid event OnRowDataBound method to create the links that refer the file from database.
You can use regular links with the href of the file or you can create buttons for the grid. If you create the buttons, you should also create the method for the Grid RowCommand.
Check these links:
http://www.dotnetgallery.com/kb/resource17-RowDatabound-event-tips-and-tricks-in-Gridview-control.aspx
How to change in a Gridview on RowDataBound event the value of an Eval() field

A: You can have a page for files
ex: www.website.com/download.aspx?id=12
You'll then need to change the http header to say it's a file to download with the data of that file.
Response.AddHeader("Content-disposition", "attachment; filename=" & filename)
Response.ContentType = "application/PDF"
Response.BinaryWrite(binaryData)
Response.End()

An other option could be to create a temporary file.

A: YOu need to add a link which executes a method (either have a hyperlink column or a templated column that contains a hyperlink). The link should execute a method which does something along these lines:

*

*Loads the corresponding binary data in memory

*Writes the binary stream into the response using Response.BinayWrite.

Make sure the response object has contentType set to "application/octet-stream" (look it up for the correct spelling, not sure about it)
Make sure the response object has the following header: "Content-disposition", "attachment: filename=


text:
Q: Soap from Node.js How to generate soap request in node.js for the below xml
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:cred="http://credential.transport.v1.api.cmpublish.clickability.com" xmlns:tran="http://transport.v1.api.cmpublish.clickability.com">
   <soapenv:Header>
      <cred:credentials username="" password="" customerID=""/>
   </soapenv:Header>
   <soapenv:Body>
      <tran:getSubscriberByEmail>
         <email></email>
         <domainID></domainID>
      </tran:getSubscriberByEmail>
   </soapenv:Body>
</soapenv:Envelope>

A: If you've got a WSDL to point things at, I've found node-soap to be straight forward.
From their readme:
var soap = require('soap');
var url = 'http://example.com/wsdl?wsdl';
var args = {name: 'value'};
soap.createClient(url, function(err, client) {
    client.MyFunction(args, function(err, result) {
        console.log(result);
    });
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Retrieve Video Stream from Youtube Link I am currently working on a project to retrieve mp3 files from the audio of YouTube videos.
I started my project with some basic parsing of youtube links and came up with a regex to extract the id.
    private static string GetYoutubeID(string url)
    {
        var match = youtubeRegex.Match(url);

        if(match.Success)
        {
            return match.Groups[0].Value ?? throw new ArgumentException("url");
        }
        else
        {
            throw new ArgumentException(url);
        }
    }

Then i am using the id in a request like so:
    public static string GetResponse(string id)
    {
        using (WebClient client = new WebClient())
        {
            return client.DownloadString($"http://youtube.com/get_video_info?video_id={id}");
        }
    }

So now this call returns a string with tags like "status" and "errorcode". There is also one particular tag named "url_encoded_fmt_stream_map". In it I can find the urls to download the videos in various qualities.
For Exampe:

https%3A%2F%2Fr2---sn-h0jeened.googlevideo.com%2Fvideoplayback...

But my query seemed to fail and the result delivered me an empty "url_encoded_fmt_stream_map"-tag with "status=fail" and the "errorcode=150" which is "video unavailable".
From my understanding the libraries out there to help downloading youtube videos have some similar problems.
So my question is, is my method reliable? If so, what am I doing wrong?
And if it is not reliable, how can i reliably retrieve a link to a video stream?

A: I was able to fix my problem. After some more trying and searching I was able to change the request url to achieve a result.
For anyone interested:

https://www.youtube.com/get_video_info?video_id={id}

Can be changed to:

https://www.youtube.com/get_video_info?video_id={id}&el=detailpage

This returns a full answer for me and the error 150 does not occur anymore for me.


text:
Q: VBA: Efficient Vlookup from another Workbook I need to do a Vlookup from another workbook  on about  400000 cells with Vba. These cells are all in one Column.And shall be written into one Column.  I know already , how the Vlookup Works,  but  my runtime is much to high by using autofill. Do you have an Suggestion how i can approve it?

A: Dont use VLookup use Index Match: http://www.randomwok.com/excel/how-to-use-index-match/

A: If you are able to adjust what the data looks like a slight amount, you may be interested in using a binary search. Its been a while since I last used one (writing a code for group exercise check-in program). https://www.khanacademy.org/computing/computer-science/algorithms/binary-search/a/implementing-binary-search-of-an-array , was helpful in setting up the idea behind it.
If you are able to sort them in an order, say by last name (im not sure of what data you are working with) then add an order of numbers to use for the binary search.
Edit:
The reasoning for a binary search would be that with a binary search is that the computational time it takes. The amount of iterations it would take is log2(400000) vs 400000. So instead of 400000 possible iterations, it would take at most 19 times with a binary search, as you can see with the more data you use the binary search would yield much quicker times.
This would only be a beneficial way if you are able to manipulate the data in such a way that would allow you to use a binary search.
So, if you can give us a bit more background on what data you are using and any restrictions you have with that data we would be able to give more constructive feedback.


text:
Q: MySQL row size too large, but only in 5.7 When I use rake db:schema:load to create the following table on my laptop running MySQL 5.6.22, it loads fine:
  create_table "inv_audits", force: :cascade do |t|
    t.integer  "inv_node_id",         limit: 2,                         null: false
    t.integer  "inv_object_id",       limit: 4,                         null: false
    t.integer  "inv_version_id",      limit: 4,                         null: false
    t.integer  "inv_file_id",         limit: 4,                         null: false
    t.string   "url",                 limit: 16383
    t.string   "status",              limit: 18,    default: "unknown", null: false
    t.datetime "created",                                               null: false
    t.datetime "verified"
    t.datetime "modified"
    t.integer  "failed_size",         limit: 8,     default: 0,         null: false
    t.string   "failed_digest_value", limit: 255
    t.text     "note",                limit: 65535
  end

However, when I try to do the same thing on my desktop running 5.7.21, it fails with Mysql2::Error: Row size too large.
The generated SQL, from the trace, is:
CREATE TABLE `inv_audits` (
  `id`                  int(11) auto_increment PRIMARY KEY,
  `inv_node_id`         smallint                      NOT NULL,
  `inv_object_id`       int(11)                       NOT NULL,
  `inv_version_id`      int(11)                       NOT NULL,
  `inv_file_id`         int(11)                       NOT NULL,
  `url`                 varchar(16383),
  `status`              varchar(18) DEFAULT 'unknown' NOT NULL,
  `created`             datetime                      NOT NULL,
  `verified`            datetime,
  `modified`            datetime,
  `failed_size`         bigint DEFAULT 0              NOT NULL,
  `failed_digest_value` varchar(255),
  `note`                text
) ENGINE=InnoDB

Why would this fail in 5.7 but succeed in 5.6?
Both machines are 64-bit Macs running macOS High Sierra (10.13.4).

A: The characterset for the character type columns, in particular, the url VARCHAR column.
The length attribute on the datatype definition VARCHAR(16383) specifies a number of characters.
But the InnoDB row size limit is in bytes.
With a single-byte characterset (e.g. latin1) the column would have maximum number of bytes of 16383 (plus space for the hidden length). This would be fine.
With a multi-byte characterset e.g. utf8 (up to 3 bytes per character) or utf8mb4 (up to 4 bytes per character), the number of bytes required will blow past the maximum allowed bytes for InnoDB row.

On the 5.6 system, we can do a
 SHOW CREATE TABLE inv_audits

If there's no characterset/collation specified for the column, the default for the table is in effect.  (The characterset for the table can be specified, if it's not, it inherits the default set for the database.)
To get the table created on 5.7, as test,  cut the VARCHAR size down to 1/4 of the current value, and then take a look at the CREATE TABLE.
 SHOW CREATE TABLE inv_audits

And it's going to be a multi-byte characterset like utf8 or utf8mb4.

I'd bet the root cause of the issue is that the default characterset is different in 5.6 and 5.7.


text:
Q: tinymce - adjust this js to affect only 1 textarea Basically I use TinyMCE for my text areas for easier editing and someone constructed this JS for me to make a textarea only go to 255 characters.
The only problem is that it affects all textareas on a page its included on instead of a set one, I know no JS so I am wandering if one of you wizards could guide me to add a place I can set what textarea to affect?
<script type="text/javascript" src="/jscripts/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({
        mode : "textareas",
        theme : "advanced",
        plugins : "bbcode",
        theme_advanced_buttons1 : "bold,italic,underline,undo,redo,link,unlink,image,forecolor,styleselect,removeformat,cleanup,code",
        theme_advanced_buttons2 : "",
        theme_advanced_buttons3 : "",
        theme_advanced_toolbar_location : "bottom",
        theme_advanced_toolbar_align : "center",
        theme_advanced_styles : "Code=codeStyle;Quote=quoteStyle",
    theme_advanced_resizing : true,
    theme_advanced_path : false,
        content_css : "css/bbcode.css",
        entity_encoding : "raw",
        add_unload_trigger : false,
        remove_linebreaks : false,
        inline_styles : false,
        forced_root_block : '',
        convert_fonts_to_spans : false,
        theme_advanced_statusbar_location : "bottom",
    setup: function(ed) {
        ed.onKeyUp.add(function(ed, e) {
        // What is the max amount of characters you want
        var maxChars = 255;
        var content = tinyMCE.activeEditor.getContent();
        // Remove any BBCode tags from the count
        var strip = content.replace(/\[\/?(?:b|i|u|url|quote|code|img|color|size)*?.*?\]/img, '');
        // Set the text for what we want to display in the status bar
        var text = strip.split(' ').length + " Words, " + strip.length + " Characters"
        // Show the status bar message
                tinymce.DOM.setHTML(tinymce.DOM.get(tinyMCE.activeEditor.id + '_path_row'), text);
        // Is there more Characters than we want
        if (strip.length > maxChars)
        {
            // Show an alert (can comment out)
            alert("Sorry too many characters "  + strip);
            // Get all characters up to the limit
            cur = strip.substring(0,maxChars);
            // Replace content with the max amount
            tinyMCE.activeEditor.setContent(oldContent);
        }

        else
        {
            oldContent = content;

        }

            });

        }
});

A: All you need to do is
//find the id of the currently active editor
var editor_name=tinyMCE.activeEditor.editorId;

then
//provide regex for list of editors to be matched
var editors_to_be_matched = /first_editor|third_editor/;

find
//if active editor matches against the list of editors
var matched = editor_name.match(editors_to_be_matched);

if
//active editor does not matches return
if(!matched) return;

else
//do character count stuff
your code here

So here is how it would look like in your case
 ed.onKeyUp.add(function(ed, e) {
    var editor_name =tinyMCE.activeEditor.editorId;
    var editors_to_be_matched = /first_editor|third_editor/;
    var matched = editor_name.match(editors_to_be_matched);

    if(!matched) return;
    alert("Do character count stuff here");
    // your code here

    // What is the max amount of characters you want
    var maxChars = 255;
    var content = tinyMCE.activeEditor.getContent();
    ........
    ..........

        });

Here is a DEMO

A: to make tinymce work on only some textareas you should change mode to "exact" and specify html element IDs in element parameter like this:
tinyMCE.init({
        mode : "exact",
        elements : "elm1,elm2",
});

you can find more info about tinymce modes here: http://www.tinymce.com/wiki.php/Configuration:mode

A: Display Name here is the new code then can you check it over :), think i got it right.
<script type="text/javascript" src="/jscripts/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({
        mode : "textareas",
        theme : "advanced",
        plugins : "bbcode",
        theme_advanced_buttons1 : "bold,italic,underline,undo,redo,link,unlink,image,forecolor,styleselect,removeformat,cleanup,code",
        theme_advanced_buttons2 : "",
        theme_advanced_buttons3 : "",
        theme_advanced_toolbar_location : "bottom",
        theme_advanced_toolbar_align : "center",
        theme_advanced_styles : "Code=codeStyle;Quote=quoteStyle",
    theme_advanced_resizing : true,
    theme_advanced_path : false,
        content_css : "css/bbcode.css",
        entity_encoding : "raw",
        add_unload_trigger : false,
        remove_linebreaks : false,
        inline_styles : false,
        forced_root_block : '',
        convert_fonts_to_spans : false,
        theme_advanced_statusbar_location : "bottom",
    setup: function(ed) {
        ed.onKeyUp.add(function(ed, e) {
        // What is the max amount of characters you want
        var maxChars = 255;
        var content = tinyMCE.activeEditor.getContent();
        var editor_name = tinyMCE.activeEditor.editorId;
        var editors_to_be_matched = /tagline/;
        var matched = editor_name.match(editors_to_be_matched);

        if(!matched) return;

        // Remove any BBCode tags from the count
        var strip = content.replace(/\[\/?(?:b|i|u|url|quote|code|img|color|size)*?.*?\]/img, '');
        // Set the text for what we want to display in the status bar
        var text = strip.split(' ').length + " Words, " + strip.length + " Characters"
        // Show the status bar message
                tinymce.DOM.setHTML(tinymce.DOM.get(tinyMCE.activeEditor.id + '_path_row'), text);
        // Is there more Characters than we want
        if (strip.length > maxChars)
        {
            // Show an alert (can comment out)
            alert("Sorry too many characters "  + strip);
            // Get all characters up to the limit
            cur = strip.substring(0,maxChars);
            // Replace content with the max amount
            tinyMCE.activeEditor.setContent(oldContent);
        }

        else
        {
            oldContent = content;

        }

            });

        }
});
</script>


text:
Q: How do I adjust same position and size? How do I adjust those two buttons same position and size? I'm trying to create shopify store but don't know how to add the additional button to the slider
enter image description here

A: You can use align-items:center on parent div using flexbox.
.parent{
  display: flex;
  align-items: center;
}


text: Q: In zero dimensional graded module the degree $ 1$ component is non zero. I am reading the commutative algebra book by W. Bruns and H. Herzog. I am stuck at the Corollary 4.1.8 which comes from lemma 4.1.7. Actually in the corollary $d=0$ case does not come from the previous lemma. It requires an independent proof. So far it is clear to me that Hilbert polynomial is the $0$ polynomial. What I couldn't understand is $Q_M(1) $ is non zero in this case. I need some help. Many many thanks.


text:
Q: Not able to perform GET request by calling the fetch method on an instance of HttpClient in Aurelia I am trying to GET request by calling the fetch method on an instance of HttpClient in Aurelia.
app.html
<template>
   <button click.delegate = "getData()">GET</button>
</template>

app.js
import {HttpClient} from 'aurelia-fetch-client';

let client = new HttpClient();

export class App {

   getData() {
      httpClient.fetch('http://jsonplaceholder.typicode.com/posts/1')
      .then(response => response.json())
      .then(data => {
         console.log(data);
      });
   }
 }

main.js
export function configure(aurelia) {
  aurelia.use
    .standardConfiguration()
    .developmentLogging()
    .plugin('aurelia-history-browser');

  aurelia.start().then(() => aurelia.setRoot());
}

I have also installed fetch bower install fetch
Now while running the application using http-server -o -c-1, I am encountering the below error
"GET /aurelia-history-browser" Error (404): "Not found"

What is that I am missing.
Update
Finally I did, but no magic (missed import 'fetch';) It's not there in the official document.
import 'fetch';
import {HttpClient, json} from 'aurelia-fetch-client';

let httpClient = new HttpClient();

export class App {

    constructor() {

    this.UserRecords = this.fetchUserDataFromWebService();

    }

    fetchUserDataFromWebService()
    {
          var serverData = "";

         httpClient.fetch('http://jsonplaceholder.typicode.com/posts')
              .then(response => response.json())
              .then(data => {
                 serverData = data;
              });

              alert('Data Received from Server');
          return serverData;
    }
}

Only one problem: if I don't use the alert box, then I am receiving the error "Error: Value for 'UserRecords' is non-repeatable" . How to solve this?

A: answer for the question in your answer, try this:
export class App {

    constructor() {

    this.UserRecords = null;//.slice(0,5);
   this.fetchUserDataFromWebService();
    }

    fetchUserDataFromWebService()
    {
         httpClient.fetch('http://jsonplaceholder.typicode.com/posts')
              .then(response => response.json())
              .then(data => {
                 this.UserRecords = data;
              });

    }
}

A: Finally I did..but no magic (missed import 'fetch';) It's not there in the official document
import 'fetch';
import {HttpClient, json} from 'aurelia-fetch-client';

let httpClient = new HttpClient();

export class App {

    constructor() {

    this.UserRecords = this.fetchUserDataFromWebService();//.slice(0,5);

    }

    fetchUserDataFromWebService()
    {
          var serverData = "";

         httpClient.fetch('http://jsonplaceholder.typicode.com/posts')
              .then(response => response.json())
              .then(data => {
                 serverData = data;
              });

              alert('Data Received from Server');
          return serverData;
    }
}

Only one problem... if I don't use the alert box, then I am receiving the error "Error: Value for 'UserRecords' is non-repeatable" . How to solve this?


text:
Q: Add some indexes to a MySQL table in parallel with Qt I have a table which I want to insert some files into it and after that I will have 30,000,000 records. After inserting I will analyze the table repeatedly. So I added some indexes to my table to increase access time. But adding this indexes decreases inserting time and for 30 millions records it takes a long time. As the following links, at first I want to insert into my table without indexes and after that I want to add some indexes to the table in parallel (i.e. 8 threads).
enter link description here and
enter link description here
So I created a connection per thread, and executed each connection with a CREATE INDEX query in a separate thread but I see that indexes are added sequentially and since creating each index takes about 35 seconds so creating 8 indexes takes about 5 minutes (instead of 30 seconds). What is the problem?
This is my multi thread class:
indextodb.h
class IndexToDB : public QThread
{
    Q_OBJECT

private:
    QString connectionName_;
    QString str_;

public:
    IndexToDB();
    ~IndexToDB();
    void setParams(QString connectionName,QString str);

private slots:
    void run();
};

indextodb.cpp
IndexToDB::IndexToDB()
{

}

IndexToDB::~IndexToDB()
{

}

void IndexToDB::setParams(QString connectionName,QString str)
{
    connectionName_=connectionName;
    str_=str;

}

void IndexToDB::run()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL",this->connectionName_);
    db.setHostName("...");
    db.setDatabaseName("...");
    db.setUserName("...");
    db.setPassword("...");

    QSqlQuery query(db);
    query.prepare(this->str_);
    query.exec();
}

And I created the threads in mainwindow.cpp as follows:
IndexToDB ** itdb=new IndexToDB*[8];

itdb[0]=new IndexToDB();
itdb[0]->setParams("connection0","CREATE INDEX `index0` on tempTBL (`col1`,`col2`,`col3`);");
itdb[0]->start();

...

tdb[7]=new IndexToDB();
itdb[7]->setParams("connection7","CREATE INDEX `index7` on tempTBL (`col10`,`col12`);");
itdb[7]->start();

A: I don't think that this is a multi-threading problem, it's about table locks. From MySQL Documentation;

A CREATE INDEX or ALTER TABLE statement for an InnoDB table always waits for currently executing transactions that are accessing the table to commit or roll back.

So second thread will wait for first thread's transection.
You may consider of using InnoDB Fast Index Creation. From MySQL Documentation;

It is possible to create multiple indexes on a table with one ALTER TABLE statement. This is relatively efficient, because the clustered index of the table needs to be scanned only once


text:
Q: How to style html5 elements only? There may be any random structure for html markup:

  test

test

test

test

test

Now, how can I select only html5 elements?
I want to style all html5 elements descendent of id="five" only like padding: 0; font-size: 1.5em; etc. but other elements should contain it's own css.
I could write all html5 elements with comma separated tag but it would be so long method.
So, is there any way (single selector or selctor once) for selecting html5 elements only with css or jQuery?

In jQuery How can I select the html5 elements only?
if($(this).prop('tagName') == html5) alert('you need latest browser to run');

A: I would create a style sheet with the following inheritance:
 .html5 > article,
 .html5 > aside {
    display: block;
  }

and add all the relevant html tags based on reference and either use jquery to add a class or directly style these specific html5 elements.

A: Use a separate class like  Manish suggested See Below Example

  test

test

test

test

test

And Apply css to that Class in #five
#five .html5 {
  /*Add your css for html five element here*/

}


text:
Q: A situation regarding AVR and bad power grid voltage I have a question regarding the following situation:
Some poultry farm has taken some serious losses when their diesel generator died, only being able to provide backup for 45 minutes and killing several ten of thousand of chickens. The reason they had to switch to the generator was because the power grid voltage was oscilating wildly (even managing to activate the generator transfer switch several times previously). A technical lab has pinpointed the AVR card as the root of the malfunction. Here comes the trouble:
After an technical examination, the damage was traced to a malfunction of the AVR card of said generator. Here comes my trouble:
-Insurer A has refused payment because the damage was "caused by the electro-mechanical effort of the repeated activation and deactivation via transfer switch, forced by the oscilating voltage in the power grid". Thus the fault falls solely on the power grid operator.
-Insurer B is questioning this refusal as "the AVR card only regulates the output voltage of the generator, having no connection to the power grid. The damage caused is more probably due to insufficient maintenance or card age, as the repeated deactivation and activation would not be enough to put such stress on the card." Insurer B wants to cover the payment but demands the farm to install power line monitors and additional surge protection devices, perform maintance with more frequency .
-After the incident, the Insured has purchased a replacement AVR and 1 additional diesel generator.
Questions:
-Who is right: Insured A or B?
-Taking into account the poor performance of the power grid voltage, would the measures taken by the insured be enough to prevent or lower the chance of a repeat of thie incident? Is insurer B's advice regarding this matter sound? Would you suggest any other measures?
Thank you very much for your advice, as this area is not one of our expertise.

A: I suspect that both are wrong. The system that controls the transfer should be designed to prevent repeated activation and de-activation of the transfer switch. Once a transfer from the grid to the DG is initiated the load should remain connected to the DG for long enough after grid power is restored to assure that grid power is stable.
There is also the possibility that the AVR card is not sufficiently robust. I doubt that the card failed due to insufficient maintenance or card age. I would investigate the card age and the maintenance recommendations of the manufacturer.

A: There are at least two faults here, the power grid fluctuations and the generator failing.
A transfer switch is heavily interlocked to prevent the generator and grid being connected to the load at the same time (That is very much the point of the things), so the generator AVR should have no visibility of the grid because it is just not connected to it.
The generator automatic start logic can of course see the grid, but from the description it is the AVR that failed (Not the same thing).
A faulty AVR card might trip the generator off line, which actually would be very much working as designed in terms of failing safe, and faulty AVR is a perfectly reasonable root cause for the generator failure (And may or may not be related to age, maintenance, or anything else), but that is a separate question from what was going on with the grid.
So as I say, two faults, the grid and the generator, but they are not necessarily related.
Now standby power plants failing when needed is a common trick, and is why critical installations will test for a few hours a month (sometimes into a load bank), to catch problems and such things as blocked fuel filters and contaminated fuel. I would suggest such as being good practise with any diesel set, and in fact there is no reason not to actually run the facility off generator for a few hours a month to confirm correct operation (Actually shut down the grid feed and confirm generator startup, then leave it to run for a few hours).
You want the tests to be long enough to get the engines and alternators fully up to temperature and at a heavy enough load to show up any restrictions in the fuel supply.
Further, some simple alarm telemetry to send a text message to the farmer in the event of grid failure or generator failure (Also in the event of air temperature in the facility moving outside safe limits (Which is probably what killed the birds)) would be a worthwhile investment, knowing that the fans have stopped for ANY reason seems worthwhile.
Regards, Dan.


text:
Q: Query Not Working The simple query below is not working.  Any idea why?  When I echo the three variables, the correct values are returned, so I know I have variables.
Thanks in advance,
John
$comment = $_POST['comment'];
$uid = $_POST['uid'];
$subid = $_POST['submissionid'];

echo $comment;
echo $uid;
echo $subid;

mysql_connect("mysqlv12", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());

$query = sprintf("INSERT INTO comment VALUES (NULL, '%s', '%s', '%s', NULL, NULL)", $uid, $subid, $comment);

mysql_query($query);

A: The query looks fine on the surface. What are the values you're inserting? Do any of them have a single quote in them? I'd guess the comment field is the likeliest culprit for that. Your code is utterly vulnerable to SQL injection as it stands now. You should replace all the variable assignments as follows, for a bare minimum of security:
$comment = $_POST['comment'];

becomes
$comment = mysql_real_escape_string($_POST['comment']);

This will also incidentally take care of any single quotes that may be causing your query to fail. As well, you do need to check if the query succeeded:
mysql_query($query) or die (mysql_error());

which would immediately tell you if there were any problems (sql syntax error, database server died, connection failed, etc...)


text:
Q: Ruby On Rails Tutorial 10.3.1 User Index The sample test has names that will not pass validation.
require 'spec_helper'

describe UsersController do
  render_views

  describe "GET 'index'" do

    describe "for signed-in users" do

      before(:each) do
        @user = test_sign_in(Factory(:user))
        second = Factory(:user, :name => "Bob", :email => "another@example.com")
        third  = Factory(:user, :name => "Ben", :email => "another@example.net")

        @users = [@user, second, third]
      end

      it "should be successful" do
        get :index
        response.should be_success
      end

      it "should have the right title" do
        get :index
        response.should have_selector("title", :content => "All users")
      end

      it "should have an element for each user" do
        get :index
        @users.each do |user|
          response.should have_selector("li", :content => user.name)
        end
      end
    end
  end
  .
  .
  .
end

The name has to be six characters long.  Bob and Ben will not pass.
class User < ActiveRecord::Base
  attr_accessor :password
  attr_accessible :name, :email,:password,:password_confirmation

  email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  validates :name, :presence => true,
  :length   =>{ :within => 6..40}

The solution (albeit trivial) was to change the names to Bobbob and Benben.
I hope that is helpful for someone.
Best,
Evan


text:
Q: Selector not working on click button effect I would like to change the background color of an itemviewholder when its clicked. To that I tried to use "selector" and "state_pressed" on it but is not working.
In this test code I tried to do that with a button and a linearlayout just to test. I'm doing this way because in my real code the itemviewholder will be inside of a LinearLayout. The button is just to test too. I'm using API 16.
Why is not working(when I click on the button or on the linearlayout nothing happens) and how can I fix this?
colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
</resources>

drawable/item_effect.xml
<?xml version="1.0" encoding="utf-8"?>
<selector
    xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- default -->
    <item android:drawable="@color/colorAccent"/>

    <!-- pressed -->
    <item android:state_pressed="true"
        android:drawable="@color/colorPrimaryDark"/>

</selector>

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_centerHorizontal="true"
        android:background="@drawable/item_effect"></LinearLayout>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="@drawable/item_effect"/>

</RelativeLayout>

MainActivity.java
package br.com.roger.selectortest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

A: I believe it's because of your selector and how it's set up. The default item in the selector needs to be the last one. Try
<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- pressed -->
    <item android:state_pressed="true"
        android:drawable="@color/colorPrimaryDark"/>

    <!-- default -->
    <item android:drawable="@color/colorAccent"/>
</selector>


text:
Q: PFFacebookUtils.initializeFacebookWithApplicationLaunchOptions(launchOptions) giving compilation error I'm trying to integrate facebook login in my parse application. I followed every step mentioned in parse tutorial. In the below code, I'm getting compilation error.
 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.
    line1: Parse.setApplicationId("xxx", clientKey: "yyy")
    line2: PFFacebookUtils.initializeFacebookWithApplicationLaunchOptions(launchOptions)
    line3: PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions)
    line4: return true
}

In line 3, I'm getting error:

Value of optional type '[NSObject:AnyObject]' not unwrapped; did you
  mean to use '!' or '?'?

If I manually unwrap it using '!', because launchOptions can be nil, I get:

Fatal error: unexpectedly found nil while unwrapping an Optional value

If I check for nil, I get:

NSInternalInconsistencyException', reason: 'You must initialize
  PFFacebookUtils with a call to
  +initializeFacebookWithApplicationLaunchOptions

Any idea how to fix it?

A: It is a bug in ParseSDK. Until Parse fix this you can change the initialize function declaration at PFFacebookUtils.h header file
1) Go to PFFacebookUtils.h
2) change:

*

*(void)initializeFacebookWithApplicationLaunchOptions:(NSDictionary *)launchOptions;

To:

*

*(void)initializeFacebookWithApplicationLaunchOptions:(PF_NULLABLE NSDictionary *)launchOptions;

This answer was provided by Kiarash Akhlaghi at https://developers.facebook.com/bugs/1462780714012820/

A: The problem was a bug of ParseSDK, it does not accept nil launchOptions
According to the the answer provided by Roger Ingouacka at
https://developers.facebook.com/bugs/1462780714012820/
    if let launchOptions = launchOptions {
        PFFacebookUtils.initializeFacebookWithApplicationLaunchOptions(launchOptions)
    } else {
        PFFacebookUtils.initializeFacebookWithApplicationLaunchOptions([NSObject:AnyObject]())
    }

Notice the use of
[NSObject:AnyObject]()

A: This problem persisted untill I updated to Parse library 1.8.1.
I tried adjusting PFFacebookUtils.h, and a lot of other things, but that did not solve it. It was driving me insane.


text:
Q: how to find in jmeter response time breakdown How to see the response break down time in Jmeter ? I can see the response time taken for a particular request. My requirement is to see the response time break down like in FireBug.
How to do this in jmeter ?


text:
Q: Rails 4 Devise 3.1.1 ActionController::UnknownFormat in Devise::RegistrationsController#new I am working on a Rails 4 app using Devise 3.1.1 for user authentication. When I click on /users/sign_up.user link Rails throws following exception:
ActionController::UnknownFormat in Devise::RegistrationsController#new
ActionController::UnknownFormat

Rails.root: /home/rehan/odesk_work/kiefer-waight/ujoin/ujoin-www

Application Trace | Framework Trace | Full Trace
actionpack (4.0.0) lib/action_controller/metal/mime_responds.rb:372:in `retrieve_collector_from_mimes'
actionpack (4.0.0) lib/action_controller/metal/mime_responds.rb:327:in `respond_with'
devise (3.1.1) app/controllers/devise/registrations_controller.rb:8:in `new'
actionpack (4.0.0) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
actionpack (4.0.0) lib/abstract_controller/base.rb:189:in `process_action'
actionpack (4.0.0) lib/action_controller/metal/rendering.rb:10:in `process_action'
actionpack (4.0.0) lib/abstract_controller/callbacks.rb:18:in `block in process_action'
activesupport (4.0.0) lib/active_support/callbacks.rb:413:in `_run__890637270__process_action__callbacks'
....

I was actually on Devise 3.0.0.rc when started the app, I thought upgrading the devise to 3.1.1 might solve the problem, but it didn't. Couldn't find anything useful on SO/google/devise github project. Any idea how to work around it. Thanks!

A: @zeeshan's answer works, you can also the functions without the _user infix:
new_registration_path(resource_name)

new_session_path(resource_name)

new_password_path(resource_name)

A: I did not want to change default links produced by Devise which appended ".user" at the end of each link. Devise produced following links:
new_user_registration_path(resource_name) new_user_session_path(resource_name) new_user_password_path(resource_name)
resource_name, which is user, as parameter to the path in link_to method which tells it to use ".user" as format. So I just removed resource_name from each path. I wonder why Devise does this though!

A: I've just resolved this problem also.
The solution is to revert all paths to Devise default ones, meaning to say no _user infix.
Note that we are not able to test in console these code:
user = User.all.sample
app.new_registration_path(user)

because Devise use its helper to transform the url automatically internally so we cannot test from outside.

A: When you say you click on the /users/sign_up.user link, do you literally mean that exact path?  Because the .user on the end is telling it to try and respond with a user format, akin to pdf, xml, or json.  Remove that and see what happens.


text:
Q: Who is $\operatorname{Hom}_{\mathbb{Z}}(\mathbb{Z}^m,\mathbb{Z}^n)$ isomorphic to? The problem is:

Who is $\operatorname{Hom}_{\mathbb{Z}}(\mathbb{Z}^m,\mathbb{Z}^n)$ isomorphic to? (where $\operatorname{Hom}_{\mathbb{Z}}(\mathbb{Z}^m,\mathbb{Z}^n)=\{f:\mathbb{Z}^m\to\mathbb{Z}^n\mid f  \text{ homomorphism  of $\mathbb{Z}$-modules}\}$)

A: You might find useful the follow isomorphisms of abelian groups (and these are isomorphism of $R$-modules when $R$ is commutative):
$$\text{Hom}_R(L\oplus M,N)\cong \text{Hom}_R(L,N)\oplus \text{Hom}_R(M,N),$$
$$\text{Hom}_R(L,M\oplus N)\cong \text{Hom}_R(L,M)\oplus \text{Hom}_R(L,N).$$
So, $\text{Hom}_{\mathbb{Z}}(\mathbb{Z}^m,\mathbb{Z}^n)\cong\text{End}_{\mathbb{Z}}(\mathbb{Z})^{mn}.$ Do you know what $\text{End}_{\mathbb{Z}}(\mathbb{Z})$ is isomorphic to?

A: Hint:
Let $R$ be  any (commutative) ring. For any free $R$-module $F$ with basis $(x_i)_{i\in I}$, and any $R$-module $M$,
$$\operatorname{Hom}_R(F,M)\simeq M^I. $$

A: Hint:
Every $\mathbb{Z}$-linear map $$f:\mathbb{Z}^m\rightarrow\mathbb{Z}^n$$
can be expressed as a matrix, with entries $a_{i,j}\in\mathbb{Z}$. How many choices do you have for $a_{i,j}$?


text:
Q: Creating an anonymous object via LINQ from IObservable? I've inherited a byzantine API that accesses remote data via JSON, the queries themselves are dealt with via TPL which for reasons I won't go into is backing me into a corner.
So, I have an IObservable subscription, which I query as thus;
mcSub.Take(1).Subscribe(x => x.Markets.ForEach(i => i.Prices.AvailableToBuy.ForEach(t => tabPanel.textBox1.AppendText(i.Id + " Back \t" + t.Size + " @ " + t.Price))));

Obviously Markets and AvailableToBuy are lists, my question is - how can I create a LINQ query/object to extract i.Id, t.Size and t.Price?

A: I believe you can do it like this, by flattening twice (once the markets, and then the prices) in one collection with all prices:
//get all prices available to buy:
var pricesAvailableToBuy = mcSub.SelectMany(x => x.Markets)
                           .SelectMany(y => y.Prices.AvailableToBuy)
                           .Select(p => new { p.Id, p.Size, p.Price });

This gives you all prices for all markets in mcSub, while your initial statement works only on one market item (which also depends how it's called - if it's on a consumer worker task/thread then it makes sense).
Or, a similar formulation:
var pricesAvailableToBuy = mcSub.SelectMany(x => x.Markets.SelectMany(y => y.Prices.AvailableToBuy))
                           .Select(p => new { p.Id, p.Size, p.Price });

A: Woof.
That is one nasty honking subscribe/query blob. Let's see if we can clean that up somewhat...I see you're taking 1 from mcSub and subscribing to it, so I'll assume it's an enumerable of observables?
Let's first fake up some types I can refer to (I'll do my best to infer from your sample):
First, the data items:
public class Thing
{
    public List<Market> Markets {get; set;}
}
public class Market
{
    public Price Prices {get; set;}
}
public class Price
{
    public List<AvailablePrice> AvailableToBuy {get; set;}
}
public class AvailablePrice
{
    public string Id {get; set;}
    public int Size {get; set;}
    public decimal Price {get;set;}
}

Next, the thing that will generate an IEnumerable<IObservable<Thing>>, which I will ham-handedly hack together:
public IEnumerable<IObservable<Thing>> GetThingsObs()
{
    var rnd = new Random();
    return Enumerable.Range(0, 3).Select(_ => {
        return Observable.Create<Thing>(obs =>
        {
            var things = Enumerable.Range(0, 3).Select(i => new Thing()
            {
                Markets = Enumerable.Range(0, 3).Select<int, Market>(x =>
                {
                    return new Market()
                    {
                        Prices = new Price
                        {
                            AvailableToBuy = Enumerable.Range(0, 3)
                                .Select(y => new AvailablePrice { Id = string.Format("{0}:{1}:{2}", i, x, y), Size = rnd.Next(0, 10), Price = rnd.Next(0, 20) })
                                .ToList()
                        }
                    };
                }).ToList()
            });
            foreach(var thing in things)
                obs.OnNext(thing);

            // this bit is important, but I'll get back to it later
            obs.OnCompleted();
            return Disposable.Empty;
        });
    });
}

Ok, now that we've got something that'll (I hope) map somewhat to your data, let's query!
IF the observable is known to complete (the bit above I glossed over), you can transform an IObservable<T> into an IEnumerable<T> reasonably safely - If it does not complete, this will basically hang, so be careful!
var mcSub = GetThingsObs();
var query =
    // for each observable
    from obs in mcSub

    // this replaces your subscribe calls, but the observable MUST complete
    // for this to return properly!
    from thing in obs.ToEnumerable()

    // After that, it's just multiple SelectManys
    // (which is what the nested 'from x in y' calls get translated into)

    // For each market
    from market in thing.Markets
    // for each price thingy
    from price in market.Prices.AvailableToBuy
    // select out your stuff
    select new { price.Id, price.Size, price.Price };

That's the best guess I can make from the sample you've provided - if you can provide any more information/details, I'll take another shot at it if this doesn't work for ya.


text:
Q: Visual Studio 2015 crashing Recently installed VS 2015 on my windows 8.1 system. It keeps crashing and asks me for restart/debug. Even if I just keep the IDE open and leave it idle, its crashes after some time. These are the logs i found in event viewer and couldn't figure out anything.

Faulting application name: devenv.exe, version: 14.0.25123.0, time
  stamp: 0x56f22f32 Faulting module name:
  CrystalDecisions.CrystalReports_unloaded, version: 9.1.9800.0, time
  stamp: 0x3d802612 Exception code: 0xc0000005 Fault offset: 0x0001fe34
  Faulting process id: 0xf04 Faulting application start time:
  0x01d1c362423c7d96 Faulting application path: C:\Program Files
  (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe Faulting
  module path: CrystalDecisions.CrystalReports Report Id:
  1381257e-2f56-11e6-8282-648099c4e3f6 Faulting package full name:
  Faulting package-relative application ID:
Faulting application name: StandardCollector.Service.exe, version:
  14.0.25123.0, time stamp: 0x56f2261c Faulting module name: ntdll.dll, version: 6.3.9600.18233, time stamp: 0x56bb4ebb Exception code:
  0xc000000d Fault offset: 0x0000000000102ab0 Faulting process id:
  0x1ae0 Faulting application start time: 0x01d1c3404a4d066d Faulting
  application path: C:\Program Files (x86)\Microsoft Visual Studio
  14.0\Team Tools\DiagnosticsHub\Collector\StandardCollector.Service.exe Faulting module path: C:\WINDOWS\SYSTEM32\ntdll.dll Report Id:
  f0ec5ba2-2f50-11e6-8282-648099c4e3f6 Faulting package full name:
  Faulting package-relative application ID:


text:
Q: Getting "Null pointer exception" at the time of executing maven project using selenium webdriver When my code is executing first it execute the LoginTest.Java class after that it goes to the Main.Java but in these I get the null pointer exception, its not reading get the driver in method.
Can anyone please help me to resolve, I am beginner in this.
Thanks in advance..!!
LoginTest.Java class:
public class LoginTest {
    private static final String ADDRESS_TO_TEST = "http://www.gmail.com";

    private WebDriver driver;
    Main Login;
    HomePage homePage;

    @BeforeTest
    public void setUp() {

        FirefoxDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get(ADDRESS_TO_TEST);

    }

    @Test(priority = 0)
    public void testLoginPageAppear() {

        // Create Login Page object
        Login = new Main(driver);
        System.out.println("Login-->" + Login);
        Login.loginToGmail("abc@gmail.com", "abc");
        homePage = new HomePage(driver);
        // Verify home page
        Assert.assertTrue(homePage.getHOmePageEmailAddress().toLowerCase()
                .contains("Google Account: abc@gmail.com"));
    }
}

Main.Java Class:
package GmailLogin;

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

public class Main {

    /*
     * Reference
     * URL:http://www.guru99.com/page-object-model-pom-page-factory-in-
     * selenium-ultimate-guide.html
     */

    WebDriver driver;

    By email = By.id("Email");
    By nextButton = By.id("next");
    By password = By.id("Passwd");
    By signInButton = By.id("signIn");

    public Main(WebDriver driver) {
        System.out.println("Driver--->" + driver);
        this.driver = driver;
    }

    public void setEmailAddress(String strEmailAddress) {
        driver.findElement(email).sendKeys(strEmailAddress);

    }

    public void clickNextButton() {
        driver.findElement(nextButton).click();
    }

    public void setPassword(String strPassword) {
        driver.findElement(password).sendKeys(strPassword);
    }

    public void clickSignInButton() {
        driver.findElement(signInButton).click();
    }

    public void loginToGmail(String strEmailAddress, String strPassword) {

        System.out.println("Email-->" + strEmailAddress);
        System.out.println("Password-->" + strPassword);
        this.setEmailAddress(strEmailAddress);
        this.clickNextButton();
        this.setPassword(strPassword);
        this.clickSignInButton();
    }
}

Null pointer exception:
-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running TestSuite
Driver--->null
Login-->GmailLogin.Main@5940ce27
Email-->abc@gmail.com
Password-->abc
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 21.016 sec <<< FAILURE! - in TestSuite
testLoginPageAppear(GmailLogin.LoginTest)  Time elapsed: 0.047 sec  <<< FAILURE!
java.lang.NullPointerException
    at GmailLogin.LoginTest.testLoginPageAppear(LoginTest.java:47)

A: This line causes your driver object to be in method scope only:
FirefoxDriver driver = new FirefoxDriver();

Change it to
driver = new FirefoxDriver();

To fill your class attribute instead.


text:
Q: Estimating linear regression with OLS vs. ML Assume that I'm going to estimate a linear regression where I assume $u\sim N(0,\sigma^2)$. What is the benefit of OLS against ML estimation? I know that we need to know a distribution of $u$ when we use ML Methods, but since I assume $u\sim N(0,\sigma^2)$ whether I use ML or OLS this point seems to be irrelevant. Thus the only advantage of OLS should be in the asymptotic features of the $\beta$ estimators. Or do we have other advantages of the OLS method?

A: You are focusing on the wrong part of the concept in your question.  The beauty of least squares is that it gives a nice easy answer regaurdless of the distribution, and if the true distribution happens to be normal, then it is the maiximum likelihood answer as well (I think this is the Gauss-Markov thereom).  When you have a distribution other than the normal then ML and OLS will give different answers (but if the true distribution is close to normal then the answers will be similar).

A: Using the usual notations, the log-likelihood of the ML method is
$l(\beta_0, \beta_1 ; y_1, \ldots, y_n) = \sum_{i=1}^n \left\{ -\frac{1}{2} \log (2\pi\sigma^2) - \frac{(y_{i} - (\beta_0 + \beta_1 x_{i}))^{2}}{2 \sigma^2} \right\}$.
It has to be maximised with respect to $\beta_0$ and $\beta_1$.
But, it is easy to see that this is equivalent to minimising
$\sum_{i=1}^{n}  (y_{i} - (\beta_0 + \beta_1 x_{i}))^{2} $.
Hence, both ML and OLS lead to the same solution.
More details are provided in these nice lecture notes.

A: the only difference for finite samples is, that the ML-estimator for the residual variance is biased. It does not account for the number of regressors used in the model.


text:
Q: Excel/Visual Studio/C#. How to change the display name of a cell but keep the formula I have some code that those:
 void mActiveSheet_Change(Microsoft.Office.Interop.Excel.Range Target)
    {
           if (Target.Cells.Formula.ToString().StartsWith("=FR("))
                   ....
    }

So whenever someone uses my custom function "=FR" I can handle it.
That's fine but while the formula value for that cell is fine, the display value is "#NAME?"
I presume that's because Excel does not recognise what =FR is.
Is there a way that I can change the display name but not the formula so I can have something other then "#NAME?" displayed?
I tried Target.Cells.Value2 = "Boo"; but that also changes the formula

A: I think you got this upside down.
The real goal is not to hide #NAME? error; The goal is to create your own function which can be plugged into Excel as any other standard function, like SQRT() or ABS().
Search Google or MSDN for user defined function Excel C# - there are working examples.

A: You are correct about #NAME?.  That is the Excel error code that is displayed when a function is not recognized.  You can't suppress this.
One of the 'dirty tricks' that might work is to hide the message.  Detect the background color of the cell, and change the font color to match the background.  Unless the cell is highlighted (not just selected) this, in effect, hides the #NAME? error message.  After you handle your =FR function and return a result, then you can reset the font color to what it was before so the answer can be seen.


text:
Q: Bootstrap modal doesnt show with location.href I want the Bootstrap modal to pop up first and I will get some data from it and with that data I want to go a href location.

function callModal(curr){
    var currele = curr.id;
    alert(currele);

    switch (currele){

        case "add_resource":
        {
            $("#myModal").modal('show');
            window.location.href="add/resource";
            break;
        }
    }
}
<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Modal Example

          <button type="button" class="close" data-dismiss="modal">×</button>

Modal Header

Some text in the modal.

          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

add resouce

The issue is : only the href is being called, not the modal
If I remove the href call , then the modal is getting called fine, but together its not getting called.
** In the Code snippet , you can ignore the undefined href location error

A: The problem is that you redirect to the new location just after the modal open and there is no time for you to see it opening. When you redirect to a new location, all of your dom states are refreshed.

A: **Found the solution. Just using 2 separate functions would solve it. :) **

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Modal Example

            <button type="button" class="close" data-dismiss="modal">×</button>

Modal Header

Some text in the modal.

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

    add resouce

var direction = "Saurabh Adhikary is best";
function callModal(curr){

    var currele = curr.id;
    alert(currele);

    switch (currele){

        case "add_resource":
        {
            $("#myModal").modal('show');
            direction ="add/resource";
            break;
        }
}
}
function printer()
{
alert(direction);
location.href = direction;
}
<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Modal Example

          <button type="button" class="close" data-dismiss="modal">×</button>

Modal Header

Some text in the modal.

          <button type="button" onClick= printer() class="btn btn-default" data-dismiss="modal">Close</button>

add resouce


text:
Q: Non-isomorphic matroids with the same Tutte Polynomial Im currently reading Matroids: a geometric introduction by Gordon and McNulty. Chapter 9 talks about Tutte polynomials.
My question is this Suppose we have two matroids M1 and M2. Both matroids have the same Rank, number of elements in the Ground set, and the same number of Bases.
Is there such a thing as two non-isomorphic matroids to have the same Tutte polynomial in rank 1 or 2??
I've been playing around with matroids in Rank 1, rank 2 and rank 3.
So far I've only been able to get the same polynomial in rank 3.

A: Matroids of ranks $1$ and $2$ have simple descriptions, from which one can check that the Tutte polynomial determines the matroid in these cases.
A matroid of rank $1$ is always $\ell \geq 0$ loops together with $m \geq 1$ parallel elements; the corresponding Tutte polynomial is $T=y^{\ell} (x+y+y^2+\cdots+y^{m-1})$. Clearly, $\ell$ and $m$ can be recovered from $T$.
A matroid of rank $2$ is always $\ell \geq 0$ loops together with $k \geq 2$ parallel classes, of sizes $m_1$, $m_2$, ..., $m_k$. I get that the Tutte polynomial is
$$y^{\ell} \left[ x^2 + x \sum (1+y+\cdots+y^{m_i-1}) -2x + \mbox{polynomial in $y$} \right].$$
Again, we can read off $\ell$ and $m_1$, ..., $m_k$. I computed (hopefully correctly) using the recursion in Lemma 2.4 here.


text:
Q: Suggest me a better name for an API method Introduction:
I'm working on an API which provides access to Picasa, Flickr and some other image services.
I have a class WebAlbum (it provides access to nested photos, albums if allowed, and some meta information).
My API allows the user not only to read albums but it also allows them to create new albums. In the general case, in order to create new album, the API user should use a factory method, which creates an album and then call the method WebGallery#addAlbum (newAlbum).
But Flickr doesn't allow creation of empty albums, it requires at least one predefined photo in any new album (to make nice album preview probably). In Flickr terms this first photo is called the Primary Photo. So in order to create an album for Flickr, user should use a factory method, then add an image to the new album, and then call WebGallery#addAlbum (newAlbum).
Problem:
At the moment WebAlbum class has this method
public interface WebAlbum {

   ...

   public boolean requiresPrimaryPhoto ();
}

I can't leave this name because PrimaryPhoto is just a Flickr term. I can change it to
public interface WebAlbum {

   ...
   //with spaces: requires one added photo to create new album

   public boolean requiresOneAddedPhotoToCreateNewAlbum ();
}

Please suggest a shorter name which has the same meaning.

A: public boolean needsDefault;
or, more descriptive
public boolean needsDefaultImg;
EDIT
Another question you should ask yourself is if this property even should be exposed.  If you want to make the experience of managing albums consistent on all backends, then maybe your library could provide default images where required.  A logo for your app, maybe.  Users are unlikely to have empty albums for very long anyway.

A: I would go with
public boolean requiresDefaultImage;

or
public boolean requiresAlbumImage;

A: boolean isEmptyAlbumAllowed

A: I would use something like allowsEmptyAlbum or emptyAlbumPermitted
That being said, adding an extra method means that the user of the class needs to know that this could even be an issue and remember to make the check before adding the album. This could be an issue because most developers "want to get things done fast" and would not know about the differences between services.
Even adding a note in the documentation is not enough because many folks calling "addAlbum" would never read the documentation of the method since it seems straightforward (see my research for details).
Ideally, you would either be able to create different factories for each service (and provide the information there), or, if you have to use a single API, find a way of gracefully failing or maybe adding a placeholder image.

A: I think you can make it even shorter by removing the redundant Album portion.
public boolean canBeEmpty();

A: The short answer to your question:
boolean isDefaultPhotoRequired;

The longer answer: the default photo requirement isn't shared by all WebAlbums, so it's a perfect candidate for using inheritance.  Move that behavior to a Flickr specific subclass.  You could do something like add the creation of that defaultImage to a Flickr.init().

A:    public boolean requiresInitialPhoto ();

   public boolean doesOnePhotoExist ();

   public boolean needsOnePhoto ();

A: Create FlickerWebAlbum and PicasaWebAlbum classes. Each of them will represent behavior specific to each provider.


text:
Q: Handling null when binding to an Image in XAML I have an Image element in XAML. I bind the Source property to a string property in my ViewModel. However, sometimes the value is null and then I get errors in the debug window.
I read here: ImageSourceConverter error for Source=null that I could make a converter to return DependencyProperty.UnsetValue if the value is null.
Now I'm wondering if it is possible to do it directly in XAML? Perhaps by using a FallbackValue?
I have tried some variants but with no luck.
This is my Image element in XAML:
<Image Name="img" Source="{Binding Path=CurrentImageSource}" Stretch="None" />

And CurrentImageSource is just a string property on the DataContext.
The error message is:
System.Windows.Data Error: 23 :

Cannot convert '' from type '' to type
  'System.Windows.Media.ImageSource' for 'sv-SE' culture with default
  conversions; consider using Converter property of Binding.
  NotSupportedException:'System.NotSupportedException:
  ImageSourceConverter cannot convert from (null).

A: I used x:Null with TargetNullValue, that way you get an easy blank image...
<Image Source="{Binding LogoPath, TargetNullValue={x:Null}}" />

That way you don't need to mess around with Triggers or BitmapImages as static resources.

A: You can check for a null reference using a data trigger:
<Image Name="img" Stretch="None" >
    <Image.Style>
        <Style TargetType="{x:Type Image}">
            <Setter Property="Source" Value="{Binding CurrentImageSource}" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding CurrentImageSource}" Value="{x:Null}">
                    <Setter Property="Source" Value="/ImageNullRef;component/errorImage.png" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Image.Style>
</Image>

Whilst it is not possible to test directly whether two values differ, you can see whether a value is greater or smaller, etc. using this approach Mike Hillberg blogged about.

A: I haven't tested it, but I think this is what TargetNullValue is for:
<Image Name="img" Source="{Binding Path=CurrentImageSource, TargetNullValue=/ImageNullRef;component/errorImage.png}" Stretch="None" />

A: I just check the answer of Sascha Hennig. It runs well on my side. I just have a little modification on my side (remove /ImageNullRef; in image resource)
<BitmapImage x:Key='defaultImage' UriSource='component/errorImage.png' />

A: Assuming the source is a Uri, I had this problem too when the Image control is about to be unloaded. For some reason the Image's Source was being set to null by the Presentation framework. The ImageSourceConverter didn't know how to convert a null to a concrete ImageSource instance (ImageSource is abstract). That's why using TargetNulValue={x:Null} in the binding works - if Source is null it doesn't try to convert to an ImageSource.
Another option, instead of setting the Source property on the Image, use an explicit BitmapImageSource and set its UriSource.
<Image Name="img" Stretch="None">
  <Image.Source>
    <BitmapImage UriSource="{Binding Path=CurrentImageSource}"/>
  </Image.Source>
</Image>


text:
Q: Spring MVC always apply @Valid for all mappings for particular parameter object Let's say I would like to validate incoming ID parameter for all my RESTful methods (>50).
As an example I have:
@RequestMapping(
        value = "/{id}",
        method = RequestMethod.GET,
        produces = {"application/json"})
@ResponseStatus(HttpStatus.OK)
public
@ResponseBody
Metadata getMetadata(
        @PathVariable("id") Long id,
        HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    return metadataService.get(id);
}

I would like to reject all requests if id < 1. As a solution I've implemented:
@RequestMapping(
        value = "/{id}",
        method = RequestMethod.GET,
        produces = {"application/json"})
@ResponseStatus(HttpStatus.OK)
public
@ResponseBody
Metadata getMetadata(
        @Valid Id id,
        HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    return metadataService.get(id.asLong());
}

public class Id {

@Min(1)
@NotNull
private Long id;

public void setId(Long id) {
    this.id = id;
}

public Long asLong() {
    return id;
}

}

But now I have to implicitly put @Valid annotation for each and every method for Id argument, which seems quite redundant . Is there a way to tell Spring that if there's an Id object as an incoming parameter it should always be @Valid. Without putting annotation each time?
Thanks.

A: So I've ended up with solution like this:
public class CustomModelAttributeMethodProcessor extends ModelAttributeMethodProcessor {

public CustomModelAttributeMethodProcessor(boolean annotationNotRequired) {
    super(annotationNotRequired);
}

@Override
protected void bindRequestParameters(final WebDataBinder binder, final NativeWebRequest request) {
    HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class);
    ((ServletRequestDataBinder) binder).bind(servletRequest);
}

@Override
protected void validateIfApplicable(final WebDataBinder binder, final MethodParameter parameter) {
    if (binder.getTarget().getClass().equals(Id.class)) {
        binder.validate();
        return;
    }

    super.validateIfApplicable(binder, parameter);
}

}
And configuration:
@Configuration
@EnableWebMvc
public class ApplicationConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        super.addArgumentResolvers(argumentResolvers);
        argumentResolvers.add(new CustomModelAttributeMethodProcessor(true));
    }
}

A bit overhead to check class of each and every incoming parameter, but works as expected. Now @Valid annotation can be omitted as validation performs by custom processor.


text:
Q: split index overflow shell script I have a large file of 20,000 lines called big file and would like to split it into smaller files of 5 lines each. I am using the command
split --lines=5 bigfile - split_

This gives smaller files split_aa, split_ab etc. but soon runs out of 2 letter combinations. Can you tell me how I can split into files of the form split_aaa, split_aab etc. so that the output files don't run out of indices.

A: From the split(1) man page:

-a, --suffix-length=N
use suffixes of length N (default 2)


text:
Q: ) escaping quote is illegal? I am trying to play around with escape character.

The 2nd one produces illegal character in the dev console. Why? Why can't I use the escape character?
demo: http://jsfiddle.net/h7nnk/1/

A: Because \ is not an escape character in HTML.

Or, as per @mplungjan's comment:

Or, better still:


text:
Q: Passive Cell Balancing of an 2S3P Battery Pack I'm currently attempting to design a passive cell balancer for a 2S3P battery pack (pictured below).

Being new to power engineering I'm not sure where to start looking; I know I want to go with a "resistor bleeding balancer" design but that's about it. I'm looking for a recommended IC or design for a battery pack in this configuration and chemistry (LiFePO4). Also I'm not sure how I'd wire the balancing leads to the battery pack as shown too; can anyone point me in the right direction?

A: Any circuit that uses an IC - or anything other than resistors, capacitors and inductors - is not passive. So what you are looking for is an active circuit that uses resistors to remove excess charge from the cells.
The maximum charging voltage for LiFePO4 is 3.65V. During most of the charging cycle the voltage rises very slowly, then shoots up rapidly as each cell reaches full charge. Therefore the balancer only needs to limit the voltage on each cell to 3.65V.

With this method the cells are balanced separately without comparing one cell to another, so each cell can have its own independent balancer circuit. LiFePO4 balance modules are often supplied as a board that is simply wired across the cell (example).

The circuit is basically a voltage comparator which connects a high power resistor (or bank of resistors) across the cell when its terminals reach the threshold voltage. The resistor bypasses charging current around the cell so it charges slower than the other lower voltage cell(s). Ideally the bypass current should equal the charging current, though if the cells are not far out of balance it can be lower. An LED is often added to indicate when the balancer is active, and also tells you that the cell is fully charged.
Here is an example that uses a MAX921 comparator with voltage reference:-

For a 2S pack you need two balancers, one for each cell in series. In a 2S3P pack you can join the upper and lower rows of 3 cells in parallel, then you only need 2 balancer circuits for the whole pack.


text:
Q: Is there a specific R function for the derivative of modified Bessel function of the second kind? My problem is as it says in the title, I am trying to use the derivative (with respect to v) of the modified Bessel function of the second kind K_v(x) but with no success.
I read in one of the documentation that besselDK(v,x) would work as a derivative, apparently this is not a recognized function in R. I tried to use the expansion for the derivative, namely
besselK(v,x)*(1- (1/2v) -log(e*x/2v))

but this doesn't work to give me the correct plot as well. I am trying to plot a function which includes this.
P <- function(x) (1/2)*log(exp(1)/(2*pi*x^(2)))+(3*exp(1/x^(2))/(sqrt(2*pi*x^(2))))*besselK((1/x^(2)),1/2)*(log(exp(1)/x^(2)))
x <- seq(0.1,2,0.01)
plot(x, P(x), xlim=c(0,2), ylim=c(0,1.2), type="l")

From the code above, I get a straight line as a plot. In the correct plot, it should be a curve bending between 1 and 1.5, could someone please tell me the right way to go about it?

A: The derivative at nu = 1/2 is given here.
f <- function(nu,x){
  besselK(x, nu)
}

library(gsl) # for expint_E1
fprime <- function(x){
  sqrt(pi/2/x) * expint_E1(2*x) * exp(x)
}

nu <- 1/2
h <- 1e-6
x <- 2
(f(nu+h, x) - f(nu,x)) / h
## [1] 0.02474864
fprime(x)
## [1] 0.02474864


text:
Q: WSO2 IS 5.10 Set custom message while using expired reset password link I am using WSO2 IS 5.10 version. When I click on forgot password multiple times, previous links gets expired and only the latest link will redirect to enter email page.
If we click on a previous reset password link which is expired, then it gets redirected to black page.
I have to provide custom content in the page like " Link is expired".
How can we do that.

A: Once the password reset link is clicked the user will be redirected to https://<host>:<port>/accountrecoveryendpoint/confirmrecovery.do?<query-params> That is https://github.com/wso2/identity-apps/blob/master/apps/recovery-portal/src/main/webapp/password-recovery-confirm.jsp
There is a logic to validate the confirmation code and check whether the link is expired or not.
https://github.com/wso2/identity-apps/blob/bddc96bf2d805f86446847a8f30429c882581cfa/apps/recovery-portal/src/main/webapp/password-recovery-confirm.jsp#L61
NOTE: Refer to relevant tag for 5.10.0
In IS-5.10.0, once you click on expired password reset links received to your emails the following error message will be shown, not a blank page.

If you apply this fix https://github.com/wso2/identity-apps/pull/1663/files you can display a proper error message as Invalid password reset link.


text:
Q: Подпись к картинке не шире чем сама картинка. Как сделать? Хочется красиво оформит картинки на сайте. Есть такой вариант:http://jsfiddle.net/GREF7/1/
Если задать ширину изображение в стиле точно, то все нормально. Если ширину убрать, то подпись растягивается на всю возможную длину.

Можно ли как-нибудь сделать, что б и размер картинки не задавать фиксировано, и ширина подписи не была бы больше размера картинки?
A: Для родительского блока нужно прописать:
.wrapper
{
    display: table;
    width: 1px;
}

Тогда ширина будет подстраиваться под наибольший инлайн-блок, то есть как раз под картинку.
A: А приблизительно так подойдет?
A: Может такой вариант подойдет? При изменении размеров окна браузера, изображение будет уменьшаться/увеличиваться пропорционально.
A: Я бы наверно сделал как то так: http://jsfiddle.net/alpha9000/GF8P2/
Если для вас такой вариант конечно приемлем.
A: Оберните картинку и подпись в div, width=auto(если не поможет, поиграйтесь с параметром display), либо сделать табличный аналог


text:
Q: Avoid list view threshold on OR Filter Rest Call Good morning.
My problem, as usual, is the SharePoint Online Threshold.
I've a custom list with a lot of items (> 5.000) and I need to perform queries on this list by using REST API calls.
This list schema is: Title, Field1 and Field2.
Field1 and Field2 are Short Text INDEXED columns.
Well… I need to query this list by filtering by Field1 OR by Field2
https://asdasd.sharepoint.com/sites/xxxx/_api/web/lists/GetByTitle('Big01')/items?$filter=(Field1 eq 'Value1 53') or (Field2 eq 'Value2 25')
Despite both Field1 and Field2 are indexed fields and the result of this query is definitely less then 5.000 items (2 items), I get the threshold error.
{"odata.error":{"code":"-2147024860, Microsoft.SharePoint.SPQueryThrottledException","message":{"lang":"en-US","value":"The attempted operation is prohibited because it exceeds the list view threshold enforced by the administrator."}}}
If I perform query on single field like the follows, all works fine, but if I try to combine the two condition (OR), I get SPQueryThrottledException.
https:// asdasd.sharepoint.com/sites/ xxxx/_api/web/lists/GetByTitle('Big01')/items?$filter=(Field1 eq 'Value1 53')
https:// asdasd.sharepoint.com/sites/xxxx/_api/web/lists/GetByTitle('Big01')/items?$filter=(Field2 eq 'Value2 25')
Any ideas?
Thanks,
Sergio

A: OR filter condition in the Rest API will loop and filter the items with 2 times, so the total count to filter will exceed the list view threshold.
One Solution is to call the single filter with 2 Separated ajax call and combine the data.


text:
Q: Помогите ускорить код c++! Помогите пожалуйста ускорить код, для этой задачи:

Синхронизация (20 баллов)
Группа из n спутников  расположена на координатной прямой в точках с координатами 1, 2, ... n. Каждый спутник характеризуется мощностью генерируемого им сигнала pi. Если спутник в точке xi имеет мощность сигнала pi, то все спутники, находящиеся на расстоянии не большем чем pi, могут получить сигнал с этого спутника. Сам спутник свой сигнал не получает.
Для синхронизации работы, все спутники одновременно послали свои сигналы всем остальным спутникам, до которых их сигнал доходит. Требуется для каждого спутника определить от скольки других спутников он получил сигнал.
Input format
В первой строке находится число n -- количество спутников, 2 ≤ n ≤ 105. Во второй строке через пробел перечислены n целых чисел -- мощности соответствующих спутников. В i-ой позиции второй строки содержится мощность спутника, находящегося в точке i на координатной прямой. Все мощности -- целые числа в пределах от 1 до 109.
Output format
Вывести n чисел через пробел, характеризующие количество сигналов, полученных спутниками в процессе синхронизации. В i-ой позиции должно быть указано количество сигналов, полученных спутником, находящимся в точке i на координатной прямой.

#include <iostream>
#include <vector>

using namespace std;

int main(){
    int n;
    cin >> n;
    vector <int> a(n, -1);

    for (int i = 0; i < n; i++){
        int p;
        cin >> p;

        for (int j = max(0, i - p); j < min(n, i + p + 1); j++){
            a[j] += 1;
        }
    }

    for (int i = 0; i < n; i++){
        cout << a[i] << " ";
    }
}

A: Для каждого спутника создайте три структуры, содержащие:
{левая граница = pos[i] - power[i]; +1}
{pos[i]; 0}
{правая граница = pos[i] + power[i]; -1}

и объедините всё в один вектор или массив
Отсортируйте вектор по первому полю. При равенстве первого поля раньше идёт запись с +1.
Инициализируйте active_count = 0, пройдите по вектору.
Если второе поле ненулевое, добавляйте его к active_count
Если нулевое, то соответствующий спутник принимает данные с active_count - 1 других.
Сложность O(nlogn) обусловлена сортировкой, проход по списку линейный.


text:
Q: How do you mock out a static method of a domain object in Grails? have a Grails domain object that has a custom static function to grab data from the database
class Foo {
    /* member variables, mapping, constraints, etc. */

    static findByCustomCriteria(someParameter, List listParameter) {
        /* code to get stuff from the database... */

        /*
            Return value is a map
            ["one": "uno", "two": "due", "three": "tre"]
        */
    }

}

The static function findByCustomCriteria uses createCriteria() to build the query that pulls data from the Foo table, which means mockDomain(Foo) does not work properly when unit testing.  What I'm trying to do to work around this is use one of the general purpose methods of mocking to mock out findByCustomCriteria, but I can't get the syntax quite right.
I have a controller BarController that I'm trying to test, and buried in the call to BarController.someFunction() there is a call to Foo.findByCustomCriteria().
class BarControllerTest extends ControllerUnitTestCase {

    protected void setUp() {
        super.setUp()
    }

    protected void tearDown() {
        super.tearDown()
    }

    void testSomeFunction() {

        /* Mocking for Foo goes here */

        assertEquals("someValue", controller.someFunction())
    }
}

What would be a way to mock this out?
I've tried using new MockFor(), mockFor(), and metaClass, but I can't get it to work.

Edit:
Every time I tried to mock this out, I tried to mock it like so...
Foo.metaClass.'static'.findByCustomCriteria = { someParam, anotherParam ->
    ["one": "uno", "two": "due", "three": "tre"]
}

I guess I didn't include enough information initially.

A: In Grails 2.0 and higher, you can use the GrailsMock class like this
def mockControl = new GrailsMock(MyDomainClass)
mockControl.demand.static.get() {id -> return null}  // Static method
...
mockControl.verify()

See here.

A: I've encountered this scenario more than once, you need to modify the static metaClass of Foo:
Foo.metaClass.'static'.findByCustomCriteria = { someParameter, List listParameter ->
    ["one": "uno", "two": "due", "three": "tre"]
}

Typically I'll put it in the test setup, so I don't forget when it needs to be applied.


text:
Q: Here geocoding API returns 401 Unauthorized when calling from Google Cloud I was using Google cloud to call Here Geocoding API and got 401 Unauthorized. However, when I print out the request URI and visit it manually, I can get the correct Geocoding response. Is that because Google cloud ips are blacklisted on the service side?
I used the correct app_id and app_code in the request.

A: 401 error could be returned from HERE APIs if the header parameter "referrer" has a value which is not white-listed for the credentials. Either remove domain white-listing for the credentials from HERE Developer portal dashboard or update the header value to match the domain white-listed for the credentials.


text:
Q: If $0\neq t, x\in\mathbb{R}:\sum_{n=0}^\infty \sin^2(tx^n)<\infty$ (i.e. x is a Pisot number) is then $\sum_{n=0}^\infty-\log(1-\sin^2(tx^n))<\infty$? Suppose that $x\in\mathbb{R}$ is a Pisot number, i.e. for some $0\neq t\in\mathbb{R}:\sum_{n=0}^\infty \sin^2(tx^n)<\infty$. Do we then know that also $\sum_{n=0}^\infty -\log(1 - \sin^2(tx^n)) < \infty$ that is that if $\sum_{n=0}^\infty \sin^2(tx^n)$ converges, does also $\sum_{n=0}^\infty \log(\cos^2(tx^n))$ converge? A book I am reading on basically assumes this connection without proving it. Is there some suitable asymptotic bound that we could use for the logarithm?

A: Yes, in fact this is true for any sequence $a_n$ such that
$$\sum_{n=0}^\infty a_n<\infty$$
Note that this implies $a_n\to 0$. We also have
$$\lim_{n\to \infty} \frac{\log(1-a_n)}{a_n}=-\lim_{n\to \infty}\frac{\log(1+a_n)}{a_n}=-\lim_{h\to 0}\frac{\log(1+h)}{h}=-1$$
This implies
$$\sum_{n=0}^\infty -\log(1-a_n)\text{ converges iff }\sum_{n=0}^\infty a_n\text{ converges}$$
Also, you have $\cos^2(x)=1-\sin^2(x)$ which implies the second series is the negative of the first series.


text:
Q: Duvida em porcentagem em C O usuário tem que dar um valor que seria o preço do produto
e um valor que seria o desconto
Na hora de dar o valor final eu não consigo
já tentei algumas coisas
#include <stdio.h>

int main ()
{
    float preco, desc, end;
    printf("Qual o valor da compra? ");
    scanf("%f", &preco);

    printf("Qual o valor do desconto? ");
    scanf("%f", &desc);

    end = preco / desc;
    printf("O valor final e: %f", end);
}

A: O cálculo correto do valor com desconto é:
end = preco - ( preco * desc / 100 );

considerando que desc é o valor do desconto (em porcento) entre 0 e 100.

A: Sua fórmula para o calculo de desconto está errada, nesse caso, como você quer descontar o valor você precisa subtrair o preço pela multiplicação do preço pelo valor da porcentagem.
Nesse caso o seu código ficará assim:
int main ()
{
    float preco, desc;
    printf("Qual o valor da compra? ");
    scanf("%f", &preco);

    printf("Qual o valor do desconto? ");
    scanf("%f", &desc);

    printf("O valor final e: %.2f", preco - (preco * desc/100));
}

A saída ficará assim:
Qual o valor da compra? 10
Qual o valor do desconto? 5
O valor final e: 9.50

Note que retirei a variável end pois voce não precisa dela. Espero ter ajudado :)

A: Você pode fazer da seguinte maneira.
Descontando 10% no valor de R$30,00 temos:
30 * 0,90 = R$27,00
end = preco * porcentagem_do_desconto;
para acréscimos basta que o valor da porcentagem esteja dessa maneira "30 * 1.10"


text:
Q: How do I refresh a partial view every 3 seconds in MVC 4? I need to get a progress bar to update based on the number of jobs completed.  The number of jobs completed is stored on a jobs table of a SQL Server DB.  I need my ASP.NET MVC 4 application to query the DB every 3 seconds for the number of jobs compete and use this data to update the progress bar which is held in a partial view.  The timer works and it calls my the _getforStatus action in the StatusController, and it seems to call the EntityDB, but is never seems to call the view other than before the timer tells it to.  How do I get the progress bar to refresh every 3 seconds?
The header of my _Layout.cshtml view calls the initiation of the timer which is in the StatusController like so:
 <head>
      ...
       @Html.Action("InitTimer", 'Status")
      ...
 </head>

Also, in the _Layout view I call the partial view into a Jumbotron like so:
 <div class="jumbotron" id=progress">
      @{Html.RenderAction("_GetforStatus", "Status");}
 </div>

The Status controller is coded like so:
 public class StatusController : Controller
 {
      IntegrationDBEntities _db;

      Private Timer timer1;

      Public void initTimer()
      {
           timer1 = new Timer();
           timer1.elapsed += new ElapsedEventhandler(timer_Elapsed(;
           timer1.interval = 3000;
           timer1.Start();
       }

      Private void timer_Elapsed(Object sender, EventArgs e)
      {
           _GetforStatus();
      }

      [ChildActiononly]
      public PartialViewResult _GetforStatus(0
      {
           _db = new IntegrationDBEntities();
           ViewDataModel - _db.Jobs.ToList();
           return partialView();
      }

EDIT:
I also tried the following Ajax code.  I got no error, but my progress bar never updated:
 <script>
       function loadPartialView()  {
            $.ajax({
                 url:  '@url.Action("_GetforStatus', "Status")",
                 type:  'GET',
                 dataType:  'html',
                 success: function(result)  {
                      $('progress').html(result);
                 }
            });
        }

  $function () {
       loadPartialView();
       window.setInterval("loadPartialView()", 3000);
  });
 </script>

I'm not sure if it isn't working bc i haven't represented "Html.RenderAction" in JS correctly or what.

A: I think you need to make some changes to your ajax call.  Here is an example of how I do the call
$.ajax({
    url: '@Url.Action("Action", "Controller")',
    type: 'post',
    cache: false,
    async: true,
    data: { id: "frmUser" },
    success: function(result){
        $('.divPartial').html(result);
    }
});

on your controller I don't think you need the child action only.  Also you are returning an empty partial view object.  It should be
return partialView('_partialName', Model);

finally in your jquery to keep the call happening you need to retrigger the call.  Try something like this
$(document).ready(function(){
    function RefreshPartial(){
        //this will wait 3 seconds and then fire the load partial function
        setTimeout(function(){
            loadPartialView();
            //recall this function so that it will continue to loop
            RefreshPartial();
        }, 3000);
    }
    //initialize the loop
    RefreshPartial();
});


text:
Q: Android Lollipop BLE Peripheral: calling BluetoothLeAdvertiser.stopAdvertising(AdvertiseCallback) disconnects from connected central I wish to stop advertising when a central connects (and subscribes to a specific characteristic):
private final BluetoothGattServerCallback bleCallbacks = new BluetoothGattServerCallback() {
    @Override
    public void onDescriptorWriteRequest(BluetoothDevice device, int requestId, BluetoothGattDescriptor descriptor, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value){
        Log.v(DEBUG_TAG, "onDescriptorWriteRequest()...");

        BluetoothGattCharacteristic characteristic = descriptor.getCharacteristic();
        Log.v(DEBUG_TAG, "----- characteristic: " + characteristic.getUuid().toString());

        if (characteristic.equals(peripheralCharacteristic)){
            descriptor.setValue(value);
            if (bluetoothGattServer.sendResponse(device,
                    requestId,
                    BluetoothGatt.GATT_SUCCESS,
                    offset,
                    value)){
                central = device;
                stopAdvertising(); //causes disconnection
                return;
            }
        }

        bluetoothGattServer.sendResponse(device,
                requestId,
                BluetoothGatt.GATT_WRITE_NOT_PERMITTED,
                0,
                null);
    }
...
}

private void stopAdvertising(){
    if (bluetoothLeAdvertiser != null) {
        bluetoothLeAdvertiser.stopAdvertising(advertiseCallback);
    }
}

Upon calling stopAdvertising(), the central and peripheral disconnect
from logcat:

04-01 11:26:06.179    7068-7085/package.Class﹕ onDescriptorWriteRequest()...
04-01 11:26:06.179    7068-7085/package.Class﹕ ----- characteristic: 80a1a1a5-8b5b-e88b-9d24-2e609654b852
04-01 11:26:06.207    7068-7085/package D/BluetoothGattServer﹕ onServerConnectionState() - status=0 serverIf=5 device=00:07:80:2F:0F:A2

With stopAdvertising() commented, connection (and communication) with the central continues.
Has anyone encountered this issue with Android's BLE Peripheral Implementation? In iOS, there is no such issue.

A: You do not need to call stopAdvertising after entering a connection.
The Link Layer from the LE Controller has 5 states: "Idle", "Advertising", "Scanning", "Initiating" and "Connected".
When you advertise, you're in "Advertising" state. When it connects, it goes into "Connected" state.
Most likely, the stopAdvertising method assumes you are in "Advertising" state at the time of calling and, without checking this, does what it's supposed to do when you call it in "Advertising": it goes to "Idle" state.
So when you call it, the LL goes into "Idle" regardless of current state.
This seems like a bug in the BLE Host Stack from Android. The correct behaviour when you call stopAdvertising in a "Connected" state should be to return an error code (e.g. "Invalid state for this command") or simply ignore.

A: Bogdan's answer applies to Bluetooth LE 4.0. However 4.1 peripherals can connect to more than 1 central, so it makes sense for a peripheral to decide whether or not it wants to stop advertising once a connection is made without immediately losing that connection. This looks like a bug in Android L as recently as 5.1.1


text:
Q: Replacing repeated values in an array in C I'm coding a function in C to check if an array has any duplicate value, and if so replace it by any of the non-present ones. The array consists of numbers shuffled from 1 to Nmax:
unsigned char * NotRepeated (unsigned char *arr){

    unsigned char i, j, count, k, notrepeated[Nmax];

        k = 0;
        for (i = 0; i < Nmax ; i++){
            count = 0;
            for (j = 0; j < Nmax; j++){
                if (arr[j] != i + 1){
                    count++;
                }
                if (count == Nmax){
                    notrepeated[k] = i + 1;
                    k++;
                }
            }
        }
        k = 0;
        for (i = 0; i < Nmax - 1; i++){
            for (j = i + 1; j < Nmax; j++){

                if (arr[i] == arr[j]){
                    arr[j] = notrepeated[k];
                    k++;
                }
            }
        }
return arr
}

If I print the array notrepeated[k] I get almost all the array filled when the original array arr[j] seldomly has more than 2 repeated figures.
What am I doing wrong?
Thanks!


text:
Q: self.propertyName vs _propertyName in objective-c I understand the difference between the two: self.propertyName uses the accessor method whereas _propertyName accesses the instance variable directly.  So as I understand it, the only time you don't want to use the self.propertyName is inside the property's accessor method, since it would cause an infinite loop.  As long as I follow that rule, is it ok, and perhaps good for the sake of consistency, to use self.propertyName every time you need to get/set that property inside a class method?
Thanks so much for your wisdom!

A: Yes, you're spot on. Consistency is the most important thing out of all of this. My personal preference is to use the dot notation where ever possible, but use the direct instance variable if required (for example, within getter/setters).
Saying that, you want to be careful if you're in the properties setter method too, as self.property = val within setProperty: will also call an infinite loop; the solution being _property = val.

A: As well as setters and getters, you should avoid dot notation in your init and dealloc methods on the grounds that it's not safe to call published methods on a class that's half constructed or half destroyed.
The particular risk is that a subclass might have added logic into its accessors. If you call the accessor in dealloc then you'll call the subclass after it's deallocated itself. If you call the accessor in init then you'll call into the subclass before it's initialsed itself.
Much the same thing can also happen if you have any key-value observers — of you call a setter then they're alerted of the change and given a reference to you regardless of your current state. So it's not even safe if you strictly disallow subclassing.

A: proper use of properties will further consistency (as said) also allow for better subclassing :)

still... in some situations.. e.g. in a threading context where you want stuff to be atomic or so, you gotta fallback to the var


text:
Q: Use a socket accepted by the parent process, in a child process created before accepting the socket I am writing a crossplatform, multiprocess and multithreaded server using the "pre forking model" and the C language.
Depending on the mode (multiprocess or multithread), the server just started, creates a set of processes/threads whose task is to process the requests of clients that are accepted by the main server.
Because child processes are created before accepting a socket, they obviously do not inherit the accepted socket.
In win32 I solved, duplicating the socket.
How can I do in C linux?

A: Use an Unix domain socket instead of a pipe for any control communication between the parent and the child.  Unlike pipes, they are bidirectional. If you use a datagram socket, each send() corresponds to one recv() and vice versa (ie. message boundaries are retained), which makes passing structures and such easier.
The point is, you can pass descriptors between processes using an Unix domain socket.  The cmsg man page has example code.
Essentially, before you fork the child processes, you create an Unix domain socket pair, unique for each child process, for control communication between the parent and the child.  I recommend using an Unix domain datagram socket.
When the parent process wishes to hand off a connection to a child process, it sends the child a message, with an SCM_RIGHTS ancillary message containing the connected socket descriptor.  (The kernel will handle the details of copying the descriptor over; just note that the descriptor number may differ in the receiving process.)
This approach works not only in Linux, but in BSDs also.


text:
Q: Saving the state of a webview fragment I have a fragment that loads in a webview, when I change fragment and go back to this fragment the web page that the user has browsed to in the fragment is lost, what am I doing wrong?
Is the problem here in my fragement or is it how I am changing fragments? Does it matter that I am using a web view client?
public class FragmentA extends Fragment {

WebView myWebView;

@Override
public void onSaveInstanceState(Bundle outState) {
   super.onSaveInstanceState(outState);
   myWebView.saveState(outState);

}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
   super.onActivityCreated(savedInstanceState);
   myWebView.restoreState(savedInstanceState);

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle saved)
{
     View mainView = (View) inflater.inflate(R.layout.frag_a, group, false);
     myWebView = (WebView) mainView.findViewById(R.id.webview);
     myWebView.setWebViewClient(new MyWebViewClient());
     myWebView.getSettings().setPluginsEnabled(true);
     myWebView.getSettings().setBuiltInZoomControls(false);
     myWebView.getSettings().setSupportZoom(false);
     myWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
     myWebView.getSettings().setAllowFileAccess(true);
     myWebView.getSettings().setDomStorageEnabled(true);
     myWebView.loadUrl("http://www.bbc.co.uk");

     return mainView;
}

public class MyWebViewClient extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url.endsWith(".mp4"))
        {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.parse(url), "video/*");

            view.getContext().startActivity(intent);
            return true;
        }
        else {
            return super.shouldOverrideUrlLoading(view, url);
        }
    }

}

}

A: Please see your other question for a possible solution that will apply to this as well:
Changing fragments and saving web view states - going mad


text:
Q: How to load 2 functions with the same name from 2 python files with the same name? I am having an import problem. What I am trying to do is to import 2 functions with the same name from modules with the same name. Note that i am doing this in Pycharm.
I have the following directory structure:
test_import
|--foo.py
|--main.py
|--test
   |--foo.py

Code
foo.py in the test_import folder looks like:
def print_arg(x):
    print('print 1: {}'.format(x))

foo.py in the test folder looks like:
def print_arg(x):
    print('print 2: {}'.format(x))

Here is my code in main.py in which I am doing the imports of print_arg:
import sys
from foo import print_arg as print_arg
print_arg(1)
sys.path.insert(1, './test')
from foo import print_arg as print_arg_2
print_arg(1)
print_arg_2(1)

I expect this to print
print 1: 1
print 1: 1
print 2: 1

But it prints
print 1: 1
print 1: 1
print 1: 1

Somehow the second import does not work and print_arg_2 becomes a reference to print_arg. This is illustrated by doing the imports the other way around:
sys.path.insert(1, './test')
from foo import print_arg as print_arg_2
print_arg_2(1)
sys.path.pop(1)
from foo import print_arg
print_arg(1)
print_arg(1)
print_arg_2(1)

which prints:
print 2: 1
print 2: 1
print 2: 1

Changing the function name in test/foo.py to print_arg_2 does not work, it results in an error. It seems like a reference to foo.py in the project folder has been created and it tries to import from there instead of looking in other directories on sys.path
Traceback (most recent call last):
  File "C:\Users\jeroe\AppData\Local\Programs\Python\Python37\lib\site-packages\IPython\core\interactiveshell.py", line 3326, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-2-10fe80aec78f>", line 5, in <module>
    from foo import print_arg_2 as print_arg_2
ImportError: cannot import name 'print_arg_2' from 'foo' (C:\Users\jeroe\PycharmProjects\test_import\foo.py)

Changing the filename of foo.py in the test folder to e.g. foo2.py does work. However I prefer not to change the filename.
So I have 2 questions:

*

*Can somebody explain me what is going on here?

*What is a better way to import these 2 functions without having to change the file (module) name?

A: First of all, you have to add an empty __init__.py file inside the test folder, so the second foo file can be imported.
Secondly, you have to write the full relative path to the second file when importing it. Right now, you are importing both times the first foo file.
Just modify the second import line to:
from test.foo import print_arg as print_arg_2


text:
Q: Design question: Should the client both create the session and the socket? I have three classes:

*

*Client

*Session

*Socket
Both Session & Socket depeand on the Client to create both objects.
A Session depeands on a Socket and no sockets are created without a session.
Should the Client have a function that creates a Session pubically and a Socket privately?
Doesn't it violate the law of demeter?
EDIT:
Current code:
class Client
{
private:
  // Connection details
public:
  shared_ptr<Socket> createSocket(); // returns a new socket if the connection is opened
}

class Session
{
public:
  Session(Client &); // Accepts a client and gets a socket for i/o to the server
}

Now something tells me that the session shouldn't be responsible for getting the socket from the client and that the client should create the session.
Am I right?

A: It depends. All you are telling us about Client is that it creates both Session and Socket, nothing more.
If Client needs to use both, then there is no violation. If it only creates Socket in order to provide it to Session, I would say this is a violation and Session should get Socket itself.