问:
Problems with match against
im trying to make a search engine with php and mysql and im using match agains.

However im having a problem (probably syntax) that is driving me crazy.

Here is the code:

```<code><?php
$busqueda= $_GET["words"];
require("conectdb.php");

if ($busqueda<>''){

   $trozos=explode(" ",$busqueda);
   $numero=count($trozos);
  if ($numero==1) {

   $cadbusca="SELECT * FROM post WHERE contenido LIKE '%$busqueda%' OR titulo LIKE '%$busqueda%'";
  } elseif ($numero>1) {

    $cadbusca="SELECT * , MATCH ( 'titulo', 'contenido' ) AGAINST ( '$busqueda' )  AS Score FROM post WHERE MATCH ( 'titulo', 'contenido' ) AGAINST ( '$busqueda' ) ORDER BY Score DESC";

}

$result=(mysql_query($cadbusca));
while($info = mysql_fetch_array($result))
{
  echo $info["id"]." ".$info["titulo"]." ".$info["contenido"];
}
}
?>
</code>```

here is the error after more than one word search:

```<code>Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home1/foodbook/public_html/search/wordsearch.php on line 19
</code>```

The fields are set to fulltext....

Thx

答:
The warning means that your query failed. If a query fails, mysql_query() returns boolean FALSE and you can retrieve the error message with mysql_error():

```<code>$res = mysql_query($cadbusca);
if ($res === FALSE) {
      die("Query failed: " . mysql_error());
}
</code>```

Your code is assuming the query succeeded and attempts to fetch a row from that false value, which is not a valid result handle. It is bad practice to assume a query will succeed. Even if the query string is syntactically valid, there's many many many other ways failure can occur, and you should check for success (or failure) at every step.

Title: Problems with match against

Body:
im trying to make a search engine with php and mysql and im using match agains.

However im having a problem (probably syntax) that is driving me crazy.

Here is the code:

<?php
$busqueda= $_GET["words"];
require("conectdb.php");

if ($busqueda<>''){

   $trozos=explode(" ",$busqueda);
   $numero=count($trozos);
  if ($numero==1) {

   $cadbusca="SELECT * FROM post WHERE contenido LIKE '%$busqueda%' OR titulo LIKE '%$busqueda%'";
  } elseif ($numero>1) {

    $cadbusca="SELECT * , MATCH ( 'titulo', 'contenido' ) AGAINST ( '$busqueda' )  AS Score FROM post WHERE MATCH ( 'titulo', 'contenido' ) AGAINST ( '$busqueda' ) ORDER BY Score DESC";

}

$result=(mysql_query($cadbusca));
while($info = mysql_fetch_array($result))
{
  echo $info["id"]." ".$info["titulo"]." ".$info["contenido"];
}
}
?>

here is the error after more than one word search:

Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home1/foodbook/public_html/search/wordsearch.php on line 19

The fields are set to fulltext....

Thx

Body:
The warning means that your query failed. If a query fails, mysql_query() returns boolean FALSE and you can retrieve the error message with mysql_error():

$res = mysql_query($cadbusca);
if ($res === FALSE) {
      die("Query failed: " . mysql_error());
}

Your code is assuming the query succeeded and attempts to fetch a row from that false value, which is not a valid result handle. It is bad practice to assume a query will succeed. Even if the query string is syntactically valid, there's many many many other ways failure can occur, and you should check for success (or failure) at every step.


来源: stackexchange

问:
python praw get comment and write in file format
I'm getting a subreddit's contents. The subreddit is AR.
I need to get post ID, title, post content, author, post date, score, comments, and comment ID, then write into txt file.
The problems I'm facing now are:

(1) Can I combine comments and comment ID into one file? Thus, it will be post ID, title, post content, author, post date, score, comments, and comment ID
(2) The selftext I got has breaklines, so in my output.txt shows like

```<code>blablabla

blablabla

blablabla
</code>```

For example, [this reddit][1] has multiple breaklines.
I want the content all in one line because the data will be transferred into csv/excel for future analysis.

My code:

```<code>import praw, datetime, os
reddit = praw.Reddit('bot1')
subreddit = reddit.subreddit('AR')
for submission in subreddit.top(limit=1):
    date = datetime.datetime.utcfromtimestamp(submission.created_utc)

    for comment in submission.comments:
        print("Comment author: ", comment.author)
        print("Comments: ", comment.body)
        indexFile_comment = open('path' + 'index_comments.txt', 'a+')
        indexFile_comment.write('"' + str(comment.author) + '"' + ', ' + '"' + str(comment.body) + '"' + '\n')
    print("Post ID: ", submission.id)
    print("Title: ", submission.title)
    print("Post Content: ", submission.selftext)
    print("User Name: ", submission.author)
    print("Post Date: ", date)
    print("Point: ", submission.score)
    indexFile = open('path' + 'index.txt', 'a+')
    indexFile.write('"' + str(submission.id) + '"' + ', ' + '"' + str(submission.title) + '"' + ', ' + '"' + str(submission.selftext) + '"' + ', ' + '"' + str(submission.author) + '"' + ', ' + '"' + str(date) + '"' + ', ' + '"' + str(submission.score) + '"' + '\n')
    print ("Successfuly writing in file")
    indexFile.close()
</code>```

答:
To get the submission in one line you can implement st.replace("\n"," ") in your code. Where the variable st is submission.selftext.

To get the comment ID you could do comment.id and to get the body comment.body within your for loop.

Edit:

In the first line, I have only added submission.id and submission.title but you can add the rest in the same manner. The loop adds the comments to end of the same string. After the for loop the I replace any new line characters with a space character. You can write record to a text file and when you go to the next submission you and append the next record to a new line in the text file.

```<code>record = str(submission.id) + " " + str(submission.title) + " "
for comment in submission.comments:
    record = record + comment.author + " " + comment.body + " "
record.replace("\n", " ")
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm getting a subreddit's contents. The subreddit is AR.
I need to get post ID, title, post content, author, post date, score, comments, and comment ID, then write into txt file.
The problems I'm facing now are:

(1) Can I combine comments and comment ID into one file? Thus, it will be post ID, title, post content, author, post date, score, comments, and comment ID
(2) The selftext I got has breaklines, so in my output.txt shows like

blablabla

blablabla

blablabla

For example, [this reddit][1] has multiple breaklines.
I want the content all in one line because the data will be transferred into csv/excel for future analysis.

My code:

import praw, datetime, os
reddit = praw.Reddit('bot1')
subreddit = reddit.subreddit('AR')
for submission in subreddit.top(limit=1):
    date = datetime.datetime.utcfromtimestamp(submission.created_utc)

    for comment in submission.comments:
        print("Comment author: ", comment.author)
        print("Comments: ", comment.body)
        indexFile_comment = open('path' + 'index_comments.txt', 'a+')
        indexFile_comment.write('"' + str(comment.author) + '"' + ', ' + '"' + str(comment.body) + '"' + '\n')
    print("Post ID: ", submission.id)
    print("Title: ", submission.title)
    print("Post Content: ", submission.selftext)
    print("User Name: ", submission.author)
    print("Post Date: ", date)
    print("Point: ", submission.score)
    indexFile = open('path' + 'index.txt', 'a+')
    indexFile.write('"' + str(submission.id) + '"' + ', ' + '"' + str(submission.title) + '"' + ', ' + '"' + str(submission.selftext) + '"' + ', ' + '"' + str(submission.author) + '"' + ', ' + '"' + str(date) + '"' + ', ' + '"' + str(submission.score) + '"' + '\n')
    print ("Successfuly writing in file")
    indexFile.close()

Body:
To get the submission in one line you can implement st.replace("\n"," ") in your code. Where the variable st is submission.selftext.

To get the comment ID you could do comment.id and to get the body comment.body within your for loop.

Edit:

In the first line, I have only added submission.id and submission.title but you can add the rest in the same manner. The loop adds the comments to end of the same string. After the for loop the I replace any new line characters with a space character. You can write record to a text file and when you go to the next submission you and append the next record to a new line in the text file.

record = str(submission.id) + " " + str(submission.title) + " "
for comment in submission.comments:
    record = record + comment.author + " " + comment.body + " "
record.replace("\n", " ")


问:
Bootstrap 3 fixed footer is breaking my mobile site
I'm using a fixed footer on my webpage.

On mobile, it is fixing to the bottom of the page and covering other content.

How can I change it so that the footer is fixed only on large/desktop screens?

答:
You can read about bootstrap 3 breakpoints here

Small screens are usually smaller than 768px, so if you don't want the footer fixed on small screens. you can change the position of the footer in the small screens using the media queries.

/*for mobile phones and tablets (both)*/
@media only screen and (min-width: 320px) and (max-width: 767px) {
  .navbar-fixed-bottom {
    position: static !important;
  }
}

/* for mobile phones only*/
@media only screen and (min-width: 320px) and (max-width: 480px) {
  .navbar-fixed-bottom {
    position: static !important;
  }
}
```

Or you can see one more solution here for the same.

You can check the mobile view of the website the developer tools the browser.

ContentLicense: CC BY-SA 4.0

Body:
You can read about bootstrap 3 breakpoints here

Small screens are usually smaller than 768px, so if you don't want the footer fixed on small screens. you can change the position of the footer in the small screens using the media queries.

/*for mobile phones and tablets (both)*/
@media only screen and (min-width: 320px) and (max-width: 767px) {
  .navbar-fixed-bottom {
    position: static !important;
  }
}

/* for mobile phones only*/
@media only screen and (min-width: 320px) and (max-width: 480px) {
  .navbar-fixed-bottom {
    position: static !important;
  }
}

Or you can see one more solution here for the same.

You can check the mobile view of the website the developer tools the browser.


问:
Database Controller: Login
I am very new to C# and it is not as easy as PHP. lol.

I'm doing a DB_Controller class where I put in the code for the Database connection. I also have a Login_Model class where I put the functions for Login.
I'm trying to build a some sort of MVC type concept, so that I can easily code in the future.

However, the code I constructed is not even working. lol. I am having an error which is InvalidOperationException was Unhandled - An unhandled exception of type 'System.InvalidOperationException' occurred in MySql.Data.dll

Below is my code:

LoginForm.cs

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MacoApp
{
    public partial class Login : Form
    {
        public Login()
        {
            InitializeComponent();
        }

        private void btn_login_Click(object sender, EventArgs e)
        {
            String user = txtbox_id.Text;
            String pass = txtbox_pin.Text;

            Boolean log = Login_Model.validate_login(user, pass);

            //Login Procedure
            if (log)
            {
                MessageBox.Show("Thank you for logging in!");
            }
            else
            {
                MessageBox.Show("Oops! Incorrect Login");
            }
        }
    }
}
</code>```

Login_Model.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;

namespace MacoApp
{
    class Login_Model
    {
        public static MySqlConnection connect;

        public static bool validate_login(string user, string pass)
        {
            DB_Controller.db_connection();
            MySqlCommand cmd = new MySqlCommand();
            cmd.CommandText = "Select * from users where username=@user and password=@pass";
            cmd.Parameters.AddWithValue("@user", user);
            cmd.Parameters.AddWithValue("@pass", pass);
            cmd.Connection = connect;
            MySqlDataReader login = cmd.ExecuteReader();
            if (login.Read())
            {
                connect.Close();
                return true;
            }
            else
            {
                connect.Close();
                return false;
            }
        }
    }
}
</code>```

DB_Controller.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;

namespace MacoApp
{
    class DB_Controller
    {

        public static void db_connection()
        {
            try
            {
                MySqlConnection connect;
                String conn = "Server=localhost;Database=macoapp;Uid=root;Pwd=;";
                connect = new MySqlConnection(conn);
                connect.Open();
            }
            catch (MySqlException e)
            {
                throw;
            }
        }
    }
}
</code>```

Your help is much appreciated.

答:
The mistake here is that DB_Controller class initiates and opens a DB connection. But data fetch is happening in Class Login_Model, where a new connection object (public static MySqlConnection connect) is used for the query. But this connection object is never initialised or opened before data fetch.
So the solution is either:

Initiate and open the connection in Login_Model class or

Return the connection you created in DB_Controller to Login_Model class and use it. I believe this is what you tried to do.

Title: Database Controller: Login

Body:
I am very new to C# and it is not as easy as PHP. lol.

I'm doing a DB_Controller class where I put in the code for the Database connection. I also have a Login_Model class where I put the functions for Login.
I'm trying to build a some sort of MVC type concept, so that I can easily code in the future.

However, the code I constructed is not even working. lol. I am having an error which is InvalidOperationException was Unhandled - An unhandled exception of type 'System.InvalidOperationException' occurred in MySql.Data.dll

Below is my code:

LoginForm.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MacoApp
{
    public partial class Login : Form
    {
        public Login()
        {
            InitializeComponent();
        }

        private void btn_login_Click(object sender, EventArgs e)
        {
            String user = txtbox_id.Text;
            String pass = txtbox_pin.Text;

            Boolean log = Login_Model.validate_login(user, pass);

            //Login Procedure
            if (log)
            {
                MessageBox.Show("Thank you for logging in!");
            }
            else
            {
                MessageBox.Show("Oops! Incorrect Login");
            }
        }
    }
}

Login_Model.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;

namespace MacoApp
{
    class Login_Model
    {
        public static MySqlConnection connect;

        public static bool validate_login(string user, string pass)
        {
            DB_Controller.db_connection();
            MySqlCommand cmd = new MySqlCommand();
            cmd.CommandText = "Select * from users where username=@user and password=@pass";
            cmd.Parameters.AddWithValue("@user", user);
            cmd.Parameters.AddWithValue("@pass", pass);
            cmd.Connection = connect;
            MySqlDataReader login = cmd.ExecuteReader();
            if (login.Read())
            {
                connect.Close();
                return true;
            }
            else
            {
                connect.Close();
                return false;
            }
        }
    }
}

DB_Controller.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;

namespace MacoApp
{
    class DB_Controller
    {

        public static void db_connection()
        {
            try
            {
                MySqlConnection connect;
                String conn = "Server=localhost;Database=macoapp;Uid=root;Pwd=;";
                connect = new MySqlConnection(conn);
                connect.Open();
            }
            catch (MySqlException e)
            {
                throw;
            }
        }
    }
}

Your help is much appreciated.


问:
Permutation of Actionscript 3 Array
Greetings,

This is my first post and I hope someone out there can help. I am an educator and I designed a quiz using Actionscript 3 (Adobe Flash) that is to determine all the different ways a family can have three children.

I have two buttons that enter either the letter B (for boy) or G (for girl) into an input text field named text_entry. I then have a submit button named enter_btn that checks to see if the entry into the input text is correct. If the input is correct, the timeline moves to the next problem (frame labeled checkmark); if it is incorrect the timeline moves to the end of the quiz (frame 62).

The following code works well for any particular correct single entry (ie: BGB). I need to write code in which all eight correct variations must be entered, but they can be entered in any order (permutation):

ie:
BBB,BBG,BGB,BGG,GBB,GBG,GGB,GGG; or

BGB,GGG,BBG,BBB,GGB,BGB,GGB,BGG; or

GGB,GGG,BBG,BBB,GGB,BGB,BGB,BGG; etc...

there are over 40,000 ways to enter these eight ways of having three children. Help!

```<code>baby_B.addEventListener(MouseEvent.CLICK, letterB);
function letterB(event:MouseEvent)
{
text_entry.appendText("B");
}

baby_G.addEventListener(MouseEvent.CLICK, letterG);
function letterG(event:MouseEvent)
{
text_entry.appendText("G");
}

enter_btn.addEventListener(MouseEvent.CLICK, check);
function check(event:MouseEvent):void {
var solution_S:Array=["BBB","BBG","BGB","BGG","GBB","GBG","GGB","GGG "];

if(solution_S.indexOf(text_entry.text)>=0)
{
gotoAndStop("checkmark");
}
else
{
gotoAndPlay(62);
}
}
</code>```

If you know the correct code, please write it out for me.  Thanks!

答:
Try this:</p>

```<code>import flash.text.TextField;
import flash.events.MouseEvent;
import flash.display.Sprite;

var correctAnswers : Array = [ "BBB", "BBG", "BGB", "GBB", "BGG", "GGB", "GBG", "GGG" ];
var answersSoFar : Array;
var textField : TextField; //on stage
var submitButton : Sprite; //on stage
var correctAnswerCount : int;

//for testing
textField.text = "BBB,BBG,BGB,GBB,BGG,GGB,GBG,GGG";
//textField.text = "BGB,BBB,GGG,BBG,GBB,BGG,GGB,GBG,";
//textField.text = "BBB,BBG, BGB,GBB,BGG, GGB, GBG,   GGG";
//textField.text = "BBB,BBG,BGB,GBB,BGG,GGB,GBG";
//textField.text = "BBB,BBG,BGB,GBB,BGG,GGB,GBG,GGG,BBG";

submitButton.addEventListener( MouseEvent.CLICK, onSubmit );

function onSubmit( event : MouseEvent ) : void
{
    var answers : Array = getAnswersArray( textField.text );

    answersSoFar = [];
    correctAnswerCount = 0;

    for each ( var answer : String in answers )
        if ( answerIsCorrect( answer ) ) correctAnswerCount++;

    if ( correctAnswerCount == correctAnswers.length ) trace( "correct" );
    else trace( "incorrect" );
}

function getAnswersArray( string : String ) : Array
{
    string = removeInvalidCharacters( string );
    return string.split( "," );
}

function removeInvalidCharacters( string : String ) : String
{
    var result : String = "";

    for ( var i : int, len = string.length; i < len; i++ )
        if ( string.charAt( i ) == "B" || string.charAt( i ) == "G" || string.charAt( i ) == "," )
            result += string.charAt( i );

    return result;
}

function answerIsCorrect( answer : String ) : Boolean
{
    if ( answerIsADuplicate( answer ) ) return false;
    else answersSoFar.push( answer );

if ( answerIsInListOfCorrectAnswers( answer ) ) return true;
    return false;
}

function answerIsInListOfCorrectAnswers( answer : String ) : Boolean
{
    if ( correctAnswers.indexOf( answer ) == -1 ) return false;
    return true;
}

function answerIsADuplicate( answer : String ) : Boolean
{
    if ( answersSoFar.indexOf( answer ) == -1 ) return false;
    return true;
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Permutation of Actionscript 3 Array

Body:
Greetings,

This is my first post and I hope someone out there can help. I am an educator and I designed a quiz using Actionscript 3 (Adobe Flash) that is to determine all the different ways a family can have three children.

I have two buttons that enter either the letter B (for boy) or G (for girl) into an input text field named text_entry. I then have a submit button named enter_btn that checks to see if the entry into the input text is correct. If the input is correct, the timeline moves to the next problem (frame labeled checkmark); if it is incorrect the timeline moves to the end of the quiz (frame 62).

The following code works well for any particular correct single entry (ie: BGB). I need to write code in which all eight correct variations must be entered, but they can be entered in any order (permutation):

ie:
BBB,BBG,BGB,BGG,GBB,GBG,GGB,GGG; or

BGB,GGG,BBG,BBB,GGB,BGB,GGB,BGG; or

GGB,GGG,BBG,BBB,GGB,BGB,BGB,BGG; etc...

there are over 40,000 ways to enter these eight ways of having three children. Help!

baby_B.addEventListener(MouseEvent.CLICK, letterB);
function letterB(event:MouseEvent)
{
text_entry.appendText("B");
}

baby_G.addEventListener(MouseEvent.CLICK, letterG);
function letterG(event:MouseEvent)
{
text_entry.appendText("G");
}

enter_btn.addEventListener(MouseEvent.CLICK, check);
function check(event:MouseEvent):void {
var solution_S:Array=["BBB","BBG","BGB","BGG","GBB","GBG","GGB","GGG "];

if(solution_S.indexOf(text_entry.text)>=0)
{
gotoAndStop("checkmark");
}
else
{
gotoAndPlay(62);
}
}

If you know the correct code, please write it out for me.  Thanks!

Body:
Try this:

import flash.text.TextField;
import flash.events.MouseEvent;
import flash.display.Sprite;

var correctAnswers : Array = [ "BBB", "BBG", "BGB", "GBB", "BGG", "GGB", "GBG", "GGG" ];
var answersSoFar : Array;
var textField : TextField; //on stage
var submitButton : Sprite; //on stage
var correctAnswerCount : int;

//for testing
textField.text = "BBB,BBG,BGB,GBB,BGG,GGB,GBG,GGG";
//textField.text = "BGB,BBB,GGG,BBG,GBB,BGG,GGB,GBG,";
//textField.text = "BBB,BBG, BGB,GBB,BGG, GGB, GBG,   GGG";
//textField.text = "BBB,BBG,BGB,GBB,BGG,GGB,GBG";
//textField.text = "BBB,BBG,BGB,GBB,BGG,GGB,GBG,GGG,BBG";

submitButton.addEventListener( MouseEvent.CLICK, onSubmit );

function onSubmit( event : MouseEvent ) : void
{
    var answers : Array = getAnswersArray( textField.text );

    answersSoFar = [];
    correctAnswerCount = 0;

    for each ( var answer : String in answers )
        if ( answerIsCorrect( answer ) ) correctAnswerCount++;

    if ( correctAnswerCount == correctAnswers.length ) trace( "correct" );
    else trace( "incorrect" );
}

function getAnswersArray( string : String ) : Array
{
    string = removeInvalidCharacters( string );
    return string.split( "," );
}

function removeInvalidCharacters( string : String ) : String
{
    var result : String = "";

    for ( var i : int, len = string.length; i < len; i++ )
        if ( string.charAt( i ) == "B" || string.charAt( i ) == "G" || string.charAt( i ) == "," )
            result += string.charAt( i );

    return result;
}

function answerIsCorrect( answer : String ) : Boolean
{
    if ( answerIsADuplicate( answer ) ) return false;
    else answersSoFar.push( answer );

if ( answerIsInListOfCorrectAnswers( answer ) ) return true;
    return false;
}

function answerIsInListOfCorrectAnswers( answer : String ) : Boolean
{
    if ( correctAnswers.indexOf( answer ) == -1 ) return false;
    return true;
}

function answerIsADuplicate( answer : String ) : Boolean
{
    if ( answersSoFar.indexOf( answer ) == -1 ) return false;
    return true;
}


问:
JavaMail Exchange server MimeContent
I am using JavaMail api and I have to send email through Exchange server and then embed image on the email body. For this I am using ExchangeService for getting connected with Exchange server. Note: If it is SMTP, I would gone through Session and Authenticator.

The challenge I face here is I have to use EmailMessage for sending the mail finally. I dont have option to set the embed message(MIMEContent) in the EmailMessage and send it.

```<code>try{

                    ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
                    ExchangeCredentials credentials = new WebCredentials(userName, password, domain);
                    service.setCredentials(credentials);
                    service.setUrl(new URI(host));
                    EmailMessage msg = new EmailMessage(service);
                    msg.setSubject(subject); //email subject
                    msg.getFrom().setAddress(from);
                    msg.getToRecipients().add(to); //email receiver
                    MimeBodyPart messageBodyPart = new MimeBodyPart();
                    messageBodyPart.setContent(bodyStart, "text/html");

                    // creates multi-part
                    MimeMultipart multipart = new MimeMultipart();
                    multipart.addBodyPart(messageBodyPart);
                    MimeBodyPart imagePart = new MimeBodyPart();
                    imagePart.setHeader("Content-ID", "<123234325>");
                    imagePart.setDisposition(MimeBodyPart.INLINE);
                    imagePart.attachFile("C:/selenium/ma000xsspf01.png");
                    multipart.addBodyPart(imagePart);
                    msg.send(); //send email
}catch(Exception e){
}
</code>```

Someone please let know how shall i use object "msg" to set the image in it as a embedded one.

答:
Try along these lines:</p>

```<code>MimeMessage msg = new MimeMessage(objSession);
MimeBodyPart imagePart = new MimeBodyPart();
String origFileName = null;
origFileName = /* Get File Name here*/;

// set the byte content
DataSource fds = new ByteArrayDataSource(/*Get Image Stream or content array*/, "image/jpeg");
imagePart.setDataHandler(new DataHandler(fds));

// this header connects the html content to the image mime part
imagePart.addHeader("Content-ID", "<" + newContentId + ">");

// set the name of resource - after encoding it with Mime utility
imagePart.setFileName(MimeUtility.encodeText(origFileName, "utf-8", null).replaceAll("\r\n", ""));

// set disposition as inline
imagePart.setDisposition(MimeBodyPart.INLINE);

MimeMultipart relatedMail = new MimeMultipart("related");
relatedMail.addBodyPart(imagePart);
msg.setContent(relatedMail);
</code>```

Title: JavaMail Exchange server MimeContent

Body:
I am using JavaMail api and I have to send email through Exchange server and then embed image on the email body. For this I am using ExchangeService for getting connected with Exchange server. Note: If it is SMTP, I would gone through Session and Authenticator.

The challenge I face here is I have to use EmailMessage for sending the mail finally. I dont have option to set the embed message(MIMEContent) in the EmailMessage and send it.

try{

                    ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
                    ExchangeCredentials credentials = new WebCredentials(userName, password, domain);
                    service.setCredentials(credentials);
                    service.setUrl(new URI(host));
                    EmailMessage msg = new EmailMessage(service);
                    msg.setSubject(subject); //email subject
                    msg.getFrom().setAddress(from);
                    msg.getToRecipients().add(to); //email receiver
                    MimeBodyPart messageBodyPart = new MimeBodyPart();
                    messageBodyPart.setContent(bodyStart, "text/html");

                    // creates multi-part
                    MimeMultipart multipart = new MimeMultipart();
                    multipart.addBodyPart(messageBodyPart);
                    MimeBodyPart imagePart = new MimeBodyPart();
                    imagePart.setHeader("Content-ID", "<123234325>");
                    imagePart.setDisposition(MimeBodyPart.INLINE);
                    imagePart.attachFile("C:/selenium/ma000xsspf01.png");
                    multipart.addBodyPart(imagePart);
                    msg.send(); //send email
}catch(Exception e){
}

Someone please let know how shall i use object "msg" to set the image in it as a embedded one.

Body:
Try along these lines:

MimeMessage msg = new MimeMessage(objSession);
MimeBodyPart imagePart = new MimeBodyPart();
String origFileName = null;
origFileName = /* Get File Name here*/;

// set the byte content
DataSource fds = new ByteArrayDataSource(/*Get Image Stream or content array*/, "image/jpeg");
imagePart.setDataHandler(new DataHandler(fds));

// this header connects the html content to the image mime part
imagePart.addHeader("Content-ID", "<" + newContentId + ">");

// set the name of resource - after encoding it with Mime utility
imagePart.setFileName(MimeUtility.encodeText(origFileName, "utf-8", null).replaceAll("\r\n", ""));

// set disposition as inline
imagePart.setDisposition(MimeBodyPart.INLINE);

MimeMultipart relatedMail = new MimeMultipart("related");
relatedMail.addBodyPart(imagePart);
msg.setContent(relatedMail);


问:
NgIf hide parent and show child
I have a case i want to achieve and I do not know if it is possible. Basically I have something like this.

```<code><div *ngIf = false>
...long code
    <div ngIf = true>
       ...long code
    </div>
</div>
</code>```

The Idea is to only show the child components and hide all the parents for some conditions.
How can I achieve something like this.

答:
As @Maximus suggested, you can hide portions of the parent's content instead of the parent itself.
So something like this

```<code><div> <!-- the parent -->
        <div *ngIf ="!someVariable">  <!-- contents of the parent -->
        ...long code
    <div ngIf ="someVariable"> <!-- the child -->
       ...long code
    </div>
</div>
</code>```

If you are going this route, I think the better way is to just remove the parent-child relationship and just have 2 divs.

```<code>     <div *ngIf ="!someVariable">  <!-- contents of the parent -->
        ...long code
     </div>
    <div ngIf ="someVariable"> <!-- the child -->
       ...long code
    </div>
</code>```

I think it is much simpler. Hope this helps.

Title: NgIf hide parent and show child

Body:
I have a case i want to achieve and I do not know if it is possible. Basically I have something like this.

...long code

       ...long code

The Idea is to only show the child components and hide all the parents for some conditions.
How can I achieve something like this.

Body:
As @Maximus suggested, you can hide portions of the parent's content instead of the parent itself.
So something like this

<div> <!-- the parent -->
        <div *ngIf ="!someVariable">  <!-- contents of the parent -->
        ...long code
    <div ngIf ="someVariable"> <!-- the child -->
       ...long code
    </div>
</div>

If you are going this route, I think the better way is to just remove the parent-child relationship and just have 2 divs.

     <div *ngIf ="!someVariable">  <!-- contents of the parent -->
        ...long code
     </div>
    <div ngIf ="someVariable"> <!-- the child -->
       ...long code
    </div>

I think it is much simpler. Hope this helps.


问:
How to use nested fragments with getChildFragmentManager()?
Edit: Hey guys I have deleted everything because I finally found the answer to my question (basically how to use a scrollview inside ViewPager inside a fragment). Here is my code for everything. I am a total noob so I don't really understand what is going on in my code but here it is:

Here is my pager adapter to make fragments go inside ViewPager(I think that is what happens) I took this code from online from CommonsGuy

import android.app.Fragment;
import android.app.FragmentManager;
import android.support.v13.app.FragmentPagerAdapter;
import java.util.List;

public class PagerAdapter extends FragmentPagerAdapter {

  private List < Fragment > fragments;

  public PagerAdapter(FragmentManager fm, List < Fragment > fragments) {
    super(fm);

    this.fragments = fragments;
  }

  @Override
  public Fragment getItem(int i) {
    return fragments.get(i);
  }

  @Override
  public int getCount() {
    return fragments.size();
  }
}```
</div>
</div>
</p>

<p><strong>Here is my code for the fragment that I will put the ViewPager on</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>public class RecipeFragment extends Fragment {

  public RecipeFragment() {
    // Required empty public constructor
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_recipe, container, false);

    List < Fragment > fragments = new Vector < > ();
    fragments.add(Fragment.instantiate(getActivity(), RecipeOverview.class.getName()));
    fragments.add(Fragment.instantiate(getActivity(), RecipeIngredients.class.getName()));
    fragments.add(Fragment.instantiate(getActivity(), RecipeProcedures.class.getName()));
    PagerAdapter adapter = new PagerAdapter(getChildFragmentManager(), fragments);
    ViewPager pager = (ViewPager) view.findViewById(R.id.pager);
    pager.setAdapter(adapter);

    return (view);
  }

}</code>```

And below are the xml files for RecipeFragment and the different fragments shown in the ViewPager respectively

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</android.support.v4.view.ViewPager>```
</div>
</div>
</p>

<p>Layout for mini fragments inside ViewPager. And the .java mini fragment file is just a normal fragment file. I also used nestedScrollView because scrollview say i am stupid person and not working properly.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><android.support.constraint.ConstraintLayout 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=".RecipeOverview">

    <android.support.v4.widget.NestedScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_margin="10dp">

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:padding="10dp"
                android:text="Ingredients"
                android:textStyle="bold"/>

            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="Some Button" />

            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="Some Button" />

            <Button
                android:id="@+id/button"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="Some Button" />

            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="Some Button" />

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:padding="10dp"
                android:text="Random Text"
                android:textStyle="bold"/>

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:padding="10dp"
                android:text="Fragment1"
                android:textStyle="bold"/>

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:padding="10dp"
                android:text="Random Text"
                android:textStyle="bold"/>

            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="Some Button" />

            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="Some Button" />

            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="Some Button" />

            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="Some Button" />

            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="Some Button" />

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:padding="10dp"
                android:text="Ingredients"
                android:textStyle="bold"/>

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:padding="10dp"
                android:text="Ingredients"
                android:textStyle="bold"/>

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:padding="10dp"
                android:text="Ingredients"
                android:textStyle="bold"/>

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:padding="10dp"
                android:text="Ingredients"
                android:textStyle="bold"/>

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:padding="10dp"
                android:text="Ingredients"
                android:textStyle="bold"/>

        </LinearLayout>

    </android.support.v4.widget.NestedScrollView>

</android.support.constraint.ConstraintLayout></code>```

答: The OnClick Methods(toFirst,toSecond) you defined in the Fragment needs to be defined in your Activity(Probably the MainActivity).</p>

Body:
Edit: Hey guys I have deleted everything because I finally found the answer to my question (basically how to use a scrollview inside ViewPager inside a fragment). Here is my code for everything. I am a total noob so I don't really understand what is going on in my code but here it is:

Here is my pager adapter to make fragments go inside ViewPager(I think that is what happens) I took this code from online from CommonsGuy

import android.app.Fragment;
import android.app.FragmentManager;
import android.support.v13.app.FragmentPagerAdapter;
import java.util.List;

public class PagerAdapter extends FragmentPagerAdapter {

  private List < Fragment > fragments;

  public PagerAdapter(FragmentManager fm, List < Fragment > fragments) {
    super(fm);

    this.fragments = fragments;
  }

  @Override
  public Fragment getItem(int i) {
    return fragments.get(i);
  }

  @Override
  public int getCount() {
    return fragments.size();
  }
}

Here is my code for the fragment that I will put the ViewPager on

public class RecipeFragment extends Fragment {

  public RecipeFragment() {
    // Required empty public constructor
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_recipe, container, false);

    List < Fragment > fragments = new Vector < > ();
    fragments.add(Fragment.instantiate(getActivity(), RecipeOverview.class.getName()));
    fragments.add(Fragment.instantiate(getActivity(), RecipeIngredients.class.getName()));
    fragments.add(Fragment.instantiate(getActivity(), RecipeProcedures.class.getName()));
    PagerAdapter adapter = new PagerAdapter(getChildFragmentManager(), fragments);
    ViewPager pager = (ViewPager) view.findViewById(R.id.pager);
    pager.setAdapter(adapter);

    return (view);
  }

}

And below are the xml files for RecipeFragment and the different fragments shown in the ViewPager respectively

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</android.support.v4.view.ViewPager>

Layout for mini fragments inside ViewPager. And the .java mini fragment file is just a normal fragment file. I also used nestedScrollView because scrollview say i am stupid person and not working properly.

<android.support.constraint.ConstraintLayout 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=".RecipeOverview">

    <android.support.v4.widget.NestedScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_margin="10dp">

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:padding="10dp"
                android:text="Ingredients"
                android:textStyle="bold"/>

            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="Some Button" />

            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="Some Button" />

            <Button
                android:id="@+id/button"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="Some Button" />

            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="Some Button" />

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:padding="10dp"
                android:text="Random Text"
                android:textStyle="bold"/>

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:padding="10dp"
                android:text="Fragment1"
                android:textStyle="bold"/>

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:padding="10dp"
                android:text="Random Text"
                android:textStyle="bold"/>

            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="Some Button" />

            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="Some Button" />

            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="Some Button" />

            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="Some Button" />

            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="Some Button" />

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:padding="10dp"
                android:text="Ingredients"
                android:textStyle="bold"/>

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:padding="10dp"
                android:text="Ingredients"
                android:textStyle="bold"/>

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:padding="10dp"
                android:text="Ingredients"
                android:textStyle="bold"/>

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:padding="10dp"
                android:text="Ingredients"
                android:textStyle="bold"/>

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:padding="10dp"
                android:text="Ingredients"
                android:textStyle="bold"/>

        </LinearLayout>

    </android.support.v4.widget.NestedScrollView>

</android.support.constraint.ConstraintLayout>


问:
Very basic objective-c question-how do I make different views share information?
So, basically, I have four different views that are switched via a tab bar at the bottom of the screen. I have a view controller set up for each one, and they all work fine. The only problem is that I have no idea how to share information between the different views-for example, I have an IBAction on one that takes the output of a UISegmentedControl and stores the selection as an integer (1,2,3,4). The problem is, I don't know how to access that integer from the first view controller (the one that actually does stuff with that information). I'm sure this is a very basic problem but my google-fu doesn't seem to be working here. Thanks!</p>

答:
Using the MVC method, information should not be stored in the view controllers. You should have a separate object which stores the information, the view controllers load it, and the views display it. The easiest way to do this would be to store the information in your application's delegate. Then, whenever the view controller needs to find/change some information, it can use [[UIApplication sharedApplication] delegate] to get the delegate, and load/change the information as needed. Load the information to update the display in viewDidLoad or viewWillDisplay:, and change it in action methods.

Edit Example:

DelegateClass.h

```<code>@interface DelegateClass : NSObject {
    //ivars
    float number1;
}
@property (assign) float number1;
...
@end
</code>```

DelegateClass.m

```<code>#import "DelegateClass.h"
@implementation DelegateClass
@synthesize number1;
...
@end
</code>```

MyViewController.m

```<code>#import "DelegateClass.h"
@implementation MyViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    DelegateClass *delegate = [[UIApplication sharedApplication] delegate];
    float number1 = delegate.number1;
    ...
}
- (IBAction)actionMethod:(id)sender {
    float number1 = sender.floatValue;//get new value
    ((DelegateClass*)[[UIApplication sharedApplication] delegate]).number1 = number1;
}
...
@end
</code>```

Body:
Using the MVC method, information should not be stored in the view controllers. You should have a separate object which stores the information, the view controllers load it, and the views display it. The easiest way to do this would be to store the information in your application's delegate. Then, whenever the view controller needs to find/change some information, it can use [[UIApplication sharedApplication] delegate] to get the delegate, and load/change the information as needed. Load the information to update the display in viewDidLoad or viewWillDisplay:, and change it in action methods.

Edit Example:

DelegateClass.h

@interface DelegateClass : NSObject {
    //ivars
    float number1;
}
@property (assign) float number1;
...
@end

DelegateClass.m

#import "DelegateClass.h"
@implementation DelegateClass
@synthesize number1;
...
@end

MyViewController.m

#import "DelegateClass.h"
@implementation MyViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    DelegateClass *delegate = [[UIApplication sharedApplication] delegate];
    float number1 = delegate.number1;
    ...
}
- (IBAction)actionMethod:(id)sender {
    float number1 = sender.floatValue;//get new value
    ((DelegateClass*)[[UIApplication sharedApplication] delegate]).number1 = number1;
}
...
@end


问:
Unable to add python to PATH
I am very new to python, but it seems like I should be able to activate the python environment by simply typing python. Unfortunately, I keep getting the error "'python' is not recognized as an internal or external command,
operable program or batch file." I can access python through it's path at C:\Python27\python, which works fine, but I can't seem to get the shortcut to work.

Details: I manually installed Python 2.7, and I run Windows 10. I have tried going to the Advanced System Settings to add the PATH manually, but with no result. None of the tutorials or help articles have suggestions for what to do if adding it manually fails. Is there any way I can fix this? It seems like a small thing, but it's really bugging me.

答:
Your path configuration is incorrect; your path should look like this:

C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program
  Files (x86)\MiKTeX 2.9\miktex\bin\;C:\Program Files\jEdit;C:\Program
  Files\Git\cmd;C:\Python27\;C:\Python27\Scripts;C:\Users\Maria\AppData\Local\Microsoft\WindowsApps;

After changing the path, make sure you restart the command prompt or any other application that needs to use Python (or you can just restart the computer).

Title: Unable to add python to PATH


问:
DML commit via jdbc
Hi I have executed the DML query via jbdc statement without giving autocommit and insert,update and delete happens . Can anyone help to understand how it works?

For example

Sample program

答:
In JDBC, autocommit property is enabled by default when the connection is created. You might need to disable the property explicitly if you want the transaction to be completed only after using commit() function.

For more information, refer the following link,

http://docs.oracle.com/javase/tutorial/jdbc/basics/transactions.html#disable_auto_commit

Title: DML commit via jdbc


问:
Creating new records in dataframe based on character
I have fields in a pandas dataframe like the sample data below.  The values in one of the fields are fractions with the form something/count(something).  I would like to split the values like the example output below, and create new records.  Basically the numerator and the denominator.  Some of the values even have multiple /, like count(something)/count(thing)/count(dog).  So I'd want to split that value in to 3 records.  Any tips on how to do this would be greatly appreciated.</p>

```<code>Sample Data:

SampleDf=pd.DataFrame([['tom','sum(stuff)/count(things)'],['bob','count(things)/count(stuff)']],columns=['ReportField','OtherField'])

Example Output:

OutputDf=pd.DataFrame([['tom1','sum(stuff)'],['tom2','count(things)'],['bob1','count(things)'],['bob2','count(stuff)']],columns=['ReportField','OtherField'])
</code>```

答:
You can use:

split with expand=True for new DataFrame

reshape by stack and reset_index

add Counter to ReportField column with convert to str by astype

remove helper column level_1 by drop

```<code>OutputDf = SampleDf.set_index('ReportField')['OtherField'].str.split('/',expand=True)
                   .stack().reset_index(name='OtherField')
OutputDf['ReportField'] = OutputDf['ReportField'] + OutputDf['level_1'].add(1).astype(str)
OutputDf = OutputDf.drop('level_1', axis=1)
print (OutputDf)
  ReportField     OtherField
0        tom1     sum(stuff)
1        tom2  count(things)
2        bob1  count(things)
3        bob2   count(stuff)
</code>```

Body:
I have fields in a pandas dataframe like the sample data below.  The values in one of the fields are fractions with the form something/count(something).  I would like to split the values like the example output below, and create new records.  Basically the numerator and the denominator.  Some of the values even have multiple /, like count(something)/count(thing)/count(dog).  So I'd want to split that value in to 3 records.  Any tips on how to do this would be greatly appreciated.

Sample Data:

SampleDf=pd.DataFrame([['tom','sum(stuff)/count(things)'],['bob','count(things)/count(stuff)']],columns=['ReportField','OtherField'])

Example Output:

OutputDf=pd.DataFrame([['tom1','sum(stuff)'],['tom2','count(things)'],['bob1','count(things)'],['bob2','count(stuff)']],columns=['ReportField','OtherField'])

Body:
You can use:

split with expand=True for new DataFrame

reshape by stack and reset_index

add Counter to ReportField column with convert to str by astype

remove helper column level_1 by drop

OutputDf = SampleDf.set_index('ReportField')['OtherField'].str.split('/',expand=True)
                   .stack().reset_index(name='OtherField')
OutputDf['ReportField'] = OutputDf['ReportField'] + OutputDf['level_1'].add(1).astype(str)
OutputDf = OutputDf.drop('level_1', axis=1)
print (OutputDf)
  ReportField     OtherField
0        tom1     sum(stuff)
1        tom2  count(things)
2        bob1  count(things)
3        bob2   count(stuff)