问:
Updates to core data object from SyncTable pull, not calling NSFeatchedResults delegate methods
I am using NSFetchedResultsController to track and load UITableView with two sections(based on available true or false) using data from coredata entity. Coredata entity is populated by azure syncTable pull method. I call fetchedDataController?.performFetch() from ViewDidLoad() method in VC.
Data is divided into two sections - section 1 available is false, section2- avaliable is true in the entity data.

Here is code snippet of NSFRC initialization:

```<code>lazy var fetchedDataController: NSFetchedResultsController<Product>? = {

        let req = NSFetchRequest<NSFetchRequestResult>(entityName: "Product")

        req.sortDescriptors = [NSSortDescriptor(key: "available", ascending: true),     NSSortDescriptor(key: "createdAt", ascending: false)]
        guard let dbContext = self.appDelegate?.managedObjectContext else { return nil }

        let controller = NSFetchedResultsController(fetchRequest: req, managedObjectContext: dbContext, sectionNameKeyPath: "available", cacheName: nil) as? NSFetchedResultsController<Product>

        controller?.delegate = self
        return controller
    }()
</code>```

Issues:
1. Even there is update in entity row data FRC delegate methods are not fired automatically. Like I changed available from true to false in the backend and did a SyncTable.pull, I can see that coredata table is updated with latest data( I opened the .sql file and able to see the data)

To overcome workaround I called perform fetch every time I do a pull, in this case when I scroll down to section 2 app is crashing with index error, that means it is not updating the table section and rows properly.

Delegate methods implementation:

```<code> func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {

   self.tableView.beginUpdates()
}

    func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        self.tableView.endUpdates()
    }

    func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
        let sectionIndexSet = IndexSet(integer: sectionIndex)
        switch type {
            case .insert:
                self.tableView.insertSections(sectionIndexSet, with: .fade)
            case .update:
                self.tableView.reloadSections(sectionIndexSet, with: .fade)
            case .delete:
                self.tableView.deleteSections(sectionIndexSet, with: .fade)
            default: break
        }
    }

    func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
        switch type {
            case .insert:
                if let newIndex = newIndexPath {
                    self.tableView.insertRows(at: [newIndex], with: .fade)
                }
            case .update:
                if let index = indexPath {
                    self.tableView.reloadRows(at: [index], with: .fade)
                }
            case .move:
                if let index = indexPath {
                    self.tableView.deleteRows(at: [index], with: .fade)
                    if let newIndex = newIndexPath {
                        self.tableView.insertRows(at: [newIndex], with: .fade)
                    }
                }
            case .delete:
                if let index = indexPath {
                    self.tableView.deleteRows(at: [index], with: .fade)
                }
            default: break
        }
    }
</code>```

I am stuck into this any help is appreciated.

答: A fetchedResultsController monitors a particular context - not the sql file.  If you have more than one contexts in the app, then changes from one may not be merged into the other.  So even if the sql files is updated the context will not be.  When you create the context make sure to set the viewContext's automaticallyMergesChangesFromParent = true.

Body:
I am using NSFetchedResultsController to track and load UITableView with two sections(based on available true or false) using data from coredata entity. Coredata entity is populated by azure syncTable pull method. I call fetchedDataController?.performFetch() from ViewDidLoad() method in VC.
Data is divided into two sections - section 1 available is false, section2- avaliable is true in the entity data.

Here is code snippet of NSFRC initialization:

lazy var fetchedDataController: NSFetchedResultsController<Product>? = {

        let req = NSFetchRequest<NSFetchRequestResult>(entityName: "Product")

        req.sortDescriptors = [NSSortDescriptor(key: "available", ascending: true),     NSSortDescriptor(key: "createdAt", ascending: false)]
        guard let dbContext = self.appDelegate?.managedObjectContext else { return nil }

        let controller = NSFetchedResultsController(fetchRequest: req, managedObjectContext: dbContext, sectionNameKeyPath: "available", cacheName: nil) as? NSFetchedResultsController<Product>

        controller?.delegate = self
        return controller
    }()

Issues:
1. Even there is update in entity row data FRC delegate methods are not fired automatically. Like I changed available from true to false in the backend and did a SyncTable.pull, I can see that coredata table is updated with latest data( I opened the .sql file and able to see the data)

To overcome workaround I called perform fetch every time I do a pull, in this case when I scroll down to section 2 app is crashing with index error, that means it is not updating the table section and rows properly.

Delegate methods implementation:

 func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {

   self.tableView.beginUpdates()
}

    func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        self.tableView.endUpdates()
    }

    func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
        let sectionIndexSet = IndexSet(integer: sectionIndex)
        switch type {
            case .insert:
                self.tableView.insertSections(sectionIndexSet, with: .fade)
            case .update:
                self.tableView.reloadSections(sectionIndexSet, with: .fade)
            case .delete:
                self.tableView.deleteSections(sectionIndexSet, with: .fade)
            default: break
        }
    }

    func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
        switch type {
            case .insert:
                if let newIndex = newIndexPath {
                    self.tableView.insertRows(at: [newIndex], with: .fade)
                }
            case .update:
                if let index = indexPath {
                    self.tableView.reloadRows(at: [index], with: .fade)
                }
            case .move:
                if let index = indexPath {
                    self.tableView.deleteRows(at: [index], with: .fade)
                    if let newIndex = newIndexPath {
                        self.tableView.insertRows(at: [newIndex], with: .fade)
                    }
                }
            case .delete:
                if let index = indexPath {
                    self.tableView.deleteRows(at: [index], with: .fade)
                }
            default: break
        }
    }

I am stuck into this any help is appreciated.


来源: stackexchange

问:
jQTouch - Cannot paste into input field: have anyone seen this?
Here is the HTML snippet:

```<code><input type="text" name="UPCtext" id="UPCtextBar" value="" placeholder="Type UPC number" class="UPCvalue"/>
</code>```

There are no events bind()'s or live()'s associated with this input field.

If I remove jQTouch it works as it should, so, have anyone been through this problem?

答:
I found a workaround:

```<code>function fixCopyPaste(el) {
    el.bind('paste', function(e) {
        var element = $(this).context;

        var text = $(this).val();
        var start = element.selectionStart;
        var pastedText = e.originalEvent.clipboardData.getData('text/plain');
        $(this).val(text.substring(0, element.selectionStart)
            +pastedText
            +text.substring(element.selectionEnd, text.length));
        element.selectionStart = start+pastedText.length;
        element.selectionEnd = element.selectionStart;
    });
}
</code>```

Call this function on the input element that you want to enable paste feature. E.g.:

```<code>fixCopyPaste($('#notes'));
</code>```

It can probably be extented to handle more than one element.

ContentLicense: CC BY-SA 2.5

Body:
Here is the HTML snippet:

<input type="text" name="UPCtext" id="UPCtextBar" value="" placeholder="Type UPC number" class="UPCvalue"/>

There are no events bind()'s or live()'s associated with this input field.

If I remove jQTouch it works as it should, so, have anyone been through this problem?

Body:
I found a workaround:

function fixCopyPaste(el) {
    el.bind('paste', function(e) {
        var element = $(this).context;

        var text = $(this).val();
        var start = element.selectionStart;
        var pastedText = e.originalEvent.clipboardData.getData('text/plain');
        $(this).val(text.substring(0, element.selectionStart)
            +pastedText
            +text.substring(element.selectionEnd, text.length));
        element.selectionStart = start+pastedText.length;
        element.selectionEnd = element.selectionStart;
    });
}

Call this function on the input element that you want to enable paste feature. E.g.:

fixCopyPaste($('#notes'));

It can probably be extented to handle more than one element.


问:
Something similar to distkey and sort key
can anyone explain functions similar to distkey and sortkey which i can use in datawarehouse, or any examples and sources which I can use, any sources or examples will be helpfull.</p>

答:
DISTKEY and SORTKEY are specific to AWS Redshift. DISTKEY controls how data is distributed across the nodes in the Redshift cluster, and SORTKEY is a form of indexing specific columns.

On Azure SQL Data Warehouse DISTKEY maps to the WITH (DISTRIBUTION = ?) clause of the CREATE TABLE statement. DISTKEY EVEN maps to ROUND_ROBIN, DISTKEY  maps to HASH() and there is no equivalent to DISTKEY ALL>

SQL Server Parallel Data Warehouse is very similar to Azure SQL Data Warehouse, except DISTKEY ALL maps to REPLICATE.

On both platforms, indexing (including a clustered columnstore index) replace the SORTKEY functionality.

Snowflake Elastic Data Warehouse manages to get great performance without having to worry about these concepts.

ContentLicense: CC BY-SA 3.0


问:
Get all class names starting with a specific prefix with JavaScript / jQuery
I want to extract classes based on specific prefix like "category-lifestyle" or "category-magazine".

The HTML markup looks like this:

```<code><article id="post-361" class="et_pb_post post-361 post type-post status-publish format-standard has-post-thumbnail hentry category-lifestyle category-magazine">

    Post content...

</article>
</code>```

答:
you can use the following selector:</p>

```<code>console.log(
   document.querySelectorAll("article[class*='category-lifestyle']")[0].innerHTML
);
</code>```

Body:
I want to extract classes based on specific prefix like "category-lifestyle" or "category-magazine".

The HTML markup looks like this:

    Post content...

Body:
you can use the following selector:

console.log(
   document.querySelectorAll("article[class*='category-lifestyle']")[0].innerHTML
);


问:
Best way to convert a decimal number to next non-decimal number in PHP
Example: if a number is: 3.2 then it will become 4

round($variable), function only do this, if the decimal value is 0.6 or higher.

Is their any function in PHP to do so? Currently, i am using this code to do what i want:

```<code>    if ($totalpages > round($totalpages))  // If the number is less than 0.06
{
$round1 = round($totalpages);
$round2 = $totalpages-round($totalpages);
$round3 = 1-$round2;
$round4 = $totalpages+$round3;
$totalpages = $round4; //
}
else
    $totalpages = round($totalpages);
</code>```

Is their any better way to do so?

答:
Your looking for ceil()

ceil — Round fractions up

Description

float ceil ( float $value ) Returns the next highest integer value by
  rounding up value if necessary.

http://php.net/manual/en/function.ceil.php

Body:
Example: if a number is: 3.2 then it will become 4

round($variable), function only do this, if the decimal value is 0.6 or higher.

Is their any function in PHP to do so? Currently, i am using this code to do what i want:

    if ($totalpages > round($totalpages))  // If the number is less than 0.06
{
$round1 = round($totalpages);
$round2 = $totalpages-round($totalpages);
$round3 = 1-$round2;
$round4 = $totalpages+$round3;
$totalpages = $round4; //
}
else
    $totalpages = round($totalpages);

Is their any better way to do so?


问:
asp.net mvc 2 web application inside a Web site?
I have a Asp.Net Web Site deployed as a WebSite inside IIS 7.5.

http://localhost/WebSite

Then I have a second Asp.Net MVC 2 web application which is deployed as Sub Application inside the above WebSite. So the mvc aplication should work on the following Url.

http://localhost/WebSite/MvcApp/

The web site works fine but when I browse the mvc Url http://localhost/WebSite/MvcApp/

It gives following error.

HTTP Error 403.14 - Forbidden The Web
  server is configured to not list the
  contents of this directory.

UPDATE: I have got this working. The issue was that I was missing the Web.Config inside the Views folder in the Asp.Net MVC 2 application.

答: From within IIS Manager, you can right click any folder in the tree to be converted to an application. Have you tried it?</p>


问:
If- satement and loops in an object arraylist
I'm doing a school project where I simulate a simple banking system where the user creates the account and can put a deposit, transfer money and delete accounts.

The method transaction should go through the arraylist, find the first account and the second account and transfer money but it jumps the code and says the account cannot be found. How is it possible to fix this problem

The code down below shows what happens in the method

```<code>public boolean transaction(String accountNumber, String newAccountNumber, double amount){
    for(int i = 0; i < bList.size(); i++){
        if(bList.get(i).getAccountNumber().equals(accountNumber)&& bList.get(i).getAccountNumber().equals(newAccountNumber)){
            bList.get(i).deposit(-amount);
            deposit(newAccountNumber, amount);
            return true;
        }
        else if(bList.get(i).getBalance()< amount){
            JOptionPane.showMessageDialog(null, "Du har inte tillräckligt med pengar");
            return false;
        }
        else if(!bList.get(i).getAccountNumber().equals(newAccountNumber) && bList.get(i).getAccountNumber().equals(accountNumber)){
            JOptionPane.showMessageDialog(null, "Kontot finns inte ");
            return false;
        }
        else if(!bList.get(i).getAccountNumber().equals(newAccountNumber)){
            JOptionPane.showMessageDialog(null, "kontot finns inte");
            return false;
        }
        else if(!bList.get(i).getAccountNumber().equals(accountNumber)){
            JOptionPane.showMessageDialog(null, "Kontot finns inte");
            return false;
        }

    }
    return false;
}
</code>```

The first if-statement should check if both accounts exsist and transfer money from the account that has money to the account that the user has selected but it skips the if-statement and says there is no account.

答:
As @eran wrote, you have an obvious error checking if the account has both the accountNumber and newAccountNumber which will of course only be true if you transact to and from the same account .

I think if you refactor the code a bit it would be simpler to debug your error:

```<code>public boolean transaction(String accountNumber, String newAccountNumber, double amount){
    Account fromAccount = getAccount(accountNumber);
    Account toAccount = getAccount(newAccountNumber);

    if (fromAccount == null || toAccount == null ) {
            // At least one of the accounts is missing
            JOptionPane.showMessageDialog(null, "Kontot finns inte ");
            return false;
    } else if (fromAccount.getBalance() < amount) {
           // Not enough funds
            JOptionPane.showMessageDialog(null, "Du har inte tillräckligt med pengar");
            return false;
    } else {
            fromAccount.deposit(-amount);
            deposit(newAccountNumber, amount);
            return true;
    }
    return false;
}

public Account getAccount(String accountNumber) {
    for (int i = 0; i < bList.size(); i++){
        if(bList.get(i).getAccountNumber().equals(accountNumber) {
            return bList.get(i);
        }
     }
     return null; // No account matches
}
</code>```

Body:
I'm doing a school project where I simulate a simple banking system where the user creates the account and can put a deposit, transfer money and delete accounts.

The method transaction should go through the arraylist, find the first account and the second account and transfer money but it jumps the code and says the account cannot be found. How is it possible to fix this problem

The code down below shows what happens in the method

public boolean transaction(String accountNumber, String newAccountNumber, double amount){
    for(int i = 0; i < bList.size(); i++){
        if(bList.get(i).getAccountNumber().equals(accountNumber)&& bList.get(i).getAccountNumber().equals(newAccountNumber)){
            bList.get(i).deposit(-amount);
            deposit(newAccountNumber, amount);
            return true;
        }
        else if(bList.get(i).getBalance()< amount){
            JOptionPane.showMessageDialog(null, "Du har inte tillräckligt med pengar");
            return false;
        }
        else if(!bList.get(i).getAccountNumber().equals(newAccountNumber) && bList.get(i).getAccountNumber().equals(accountNumber)){
            JOptionPane.showMessageDialog(null, "Kontot finns inte ");
            return false;
        }
        else if(!bList.get(i).getAccountNumber().equals(newAccountNumber)){
            JOptionPane.showMessageDialog(null, "kontot finns inte");
            return false;
        }
        else if(!bList.get(i).getAccountNumber().equals(accountNumber)){
            JOptionPane.showMessageDialog(null, "Kontot finns inte");
            return false;
        }

    }
    return false;
}

The first if-statement should check if both accounts exsist and transfer money from the account that has money to the account that the user has selected but it skips the if-statement and says there is no account.

Body:
As @eran wrote, you have an obvious error checking if the account has both the accountNumber and newAccountNumber which will of course only be true if you transact to and from the same account .

I think if you refactor the code a bit it would be simpler to debug your error:

public boolean transaction(String accountNumber, String newAccountNumber, double amount){
    Account fromAccount = getAccount(accountNumber);
    Account toAccount = getAccount(newAccountNumber);

    if (fromAccount == null || toAccount == null ) {
            // At least one of the accounts is missing
            JOptionPane.showMessageDialog(null, "Kontot finns inte ");
            return false;
    } else if (fromAccount.getBalance() < amount) {
           // Not enough funds
            JOptionPane.showMessageDialog(null, "Du har inte tillräckligt med pengar");
            return false;
    } else {
            fromAccount.deposit(-amount);
            deposit(newAccountNumber, amount);
            return true;
    }
    return false;
}

public Account getAccount(String accountNumber) {
    for (int i = 0; i < bList.size(); i++){
        if(bList.get(i).getAccountNumber().equals(accountNumber) {
            return bList.get(i);
        }
     }
     return null; // No account matches
}


问:
Use of BAL in 3 tier architecture?How to call methods from DAL to BAL
I am a newbie to 3 tier architecture and below is my DAL code

```<code>public static int Insert(string firstname, string lastname, DateTime dob, string gender,string email, string password)
    {
        // bool flag = false;
        SqlParameter pid;
        SqlParameter result;

        SqlConnection con = Generic.DBConnection.OpenConnection();

        try
        {

            SqlCommand cmd1 = new SqlCommand("Insertreg", con);
            cmd1.CommandType = CommandType.StoredProcedure;
            cmd1.Parameters.AddWithValue("@FirstName", firstname);
            cmd1.Parameters.AddWithValue("@LastName", lastname);
            cmd1.Parameters.AddWithValue("@Dob", dob);
            cmd1.Parameters.AddWithValue("@Gender", gender);
           cmd1.Parameters.AddWithValue("@EmailId", email);
            cmd1.Parameters.AddWithValue("@Password", password);
            result = cmd1.Parameters.Add("@result", System.Data.SqlDbType.Int);
            result.Direction = System.Data.ParameterDirection.Output;
            pid = cmd1.Parameters.Add("@id", System.Data.SqlDbType.Int);
            pid.Direction = System.Data.ParameterDirection.Output;
            return cmd1.ExecuteNonQuery();

            con.Close();

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
</code>```

this in BAL

```<code> public int insert(string firstname,string lastname,DateTime dob,string gender,string email,string password)
    {
      ProfileMasterDAL dal=new ProfileMasterDAL();
      try
      {
          return ProfileMasterDAL.Insert(firstname, lastname, dob, gender,email, password);
      }
      catch (Exception ex)
      {

          throw ex;
      }
        finally
      {
          dal = null;
      }

    }
</code>```

I my UI

```<code>  ProfileMasterBLL pmBLL = new ProfileMasterBLL();
 pmBLL.insert(firstname, lastname, dob, gender, mobile, country, state, email, password);
</code>```

Is this the correct way to code in 3 tier??I mean how to call methods from DAL to BAL and into UI?If not suggest me some good way.Thanks.

答:
```<code>using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.Text;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data.Odbc;
using System.IO;
using System.ComponentModel;

namespace dal
{

    /// <summary>
    /// Summary description for Data Access Layer
    /// </summary>
    public class DataAccess
    {
        public string strConnectionString;
        private DbConnection objConnection;
        private DbCommand objCommand;
        private DbProviderFactory objFactory = null;
        private bool boolHandleErrors=false;
        private string strLastError;
        private bool boolLogError=false;
        private string strLogFile;

        public DataAccess()
        {

            //strConnectionString = ;
            strConnectionString = objCommon.GetConnectionString;
            objFactory = OleDbFactory.Instance;
            objConnection = objFactory.CreateConnection();
            objCommand = objFactory.CreateCommand();
            objConnection.ConnectionString = strConnectionString;
            objCommand.Connection = objConnection;
        }

        public bool HandleErrors
        {
            get
            {
                return boolHandleErrors;
            }
            set
            {
                boolHandleErrors = value;
            }
        }

        public string LastError
        {
            get
            {
                return strLastError;
            }
        }

        public bool LogErrors
        {
            get
-            {
                return boolLogError;
            }
            set
            {
                boolLogError = value;
            }
        }

        public string LogFile
        {
            get
            {
                return strLogFile;
            }
            set
            {
                strLogFile = value;
            }
        }

        public int AddParameter(string name, object value)
        {
            DbParameter p = objFactory.CreateParameter();
            p.ParameterName = name;
            p.Value = value;
            return objCommand.Parameters.Add(p);
        }

        public int AddParameter(string name, object value, ParameterDirection direction)
        {
            DbParameter p = objFactory.CreateParameter();
            p.ParameterName = name;
            p.Value = value;
            p.Direction = direction;
            return objCommand.Parameters.Add(p);
        }

        public int AddParameter(string name, object value, DbType type)
        {
            DbParameter p = objFactory.CreateParameter();
            p.ParameterName = name;
            p.Value = value;
            p.DbType = type;
            return objCommand.Parameters.Add(p);
        }

        public int AddParameter(DbParameter parameter)
        {
            return objCommand.Parameters.Add(parameter);
        }

        public DbCommand Command
        {
            get
            {
                return objCommand;
            }
        }

        public void BeginTransaction()
        {
            try
            {
                if (objConnection.State == System.Data.ConnectionState.Closed)
                {
                    objConnection.Open();
                }
                objCommand.Transaction = objConnection.BeginTransaction();
            }
            catch (Exception Ex)
            {
                HandleExceptions(Ex);
            }
        }

        public void CommitTransaction()
        {
            objCommand.Transaction.Commit();
            objConnection.Close();
        }

        public void RollbackTransaction()
        {
            objCommand.Transaction.Rollback();
            objConnection.Close();
        }

        public int ExecuteNonQuery(string query)
        {
            return ExecuteNonQuery(query, CommandType.Text, ConnectionState.CloseOnExit);
        }

        public int ExecuteNonQuery(string query, CommandType commandtype)
        {
            return ExecuteNonQuery(query, commandtype, ConnectionState.CloseOnExit);
        }

        public int ExecuteNonQuery(string query, ConnectionState connectionstate)
        {
            return ExecuteNonQuery(query, CommandType.Text, connectionstate);
        }

        public int ExecuteNonQuery(string query, CommandType commandtype, ConnectionState connectionstate)
        {
            objCommand.CommandText = query;
            objCommand.CommandType = commandtype;
            int i = -1;
            try
            {
                if (objConnection.State == System.Data.ConnectionState.Closed)
                {
                    objConnection.Open();
                }
                i = objCommand.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                HandleExceptions(ex);
            }
            finally
            {
                objCommand.Parameters.Clear();
                if (connectionstate == ConnectionState.CloseOnExit)
                {
                    objConnection.Close();
                }
            }

            return i;
        }

        public object ExecuteScalar(string query)
        {
            return ExecuteScalar(query, CommandType.Text, ConnectionState.CloseOnExit);
        }

        public object ExecuteScalar(string query, CommandType commandtype)
        {
            return ExecuteScalar(query, commandtype, ConnectionState.CloseOnExit);
        }

        public object ExecuteScalar(string query, ConnectionState connectionstate)
        {
            return ExecuteScalar(query, CommandType.Text, connectionstate);
        }

        public object ExecuteScalar(string query, CommandType commandtype, ConnectionState connectionstate)
        {
            objCommand.CommandText = query;
            objCommand.CommandType = commandtype;
            object o = null;
            try
            {
                if (objConnection.State == System.Data.ConnectionState.Closed)
                {
                    objConnection.Open();
                }
                o = objCommand.ExecuteScalar();
            }
            catch (Exception ex)
            {
                HandleExceptions(ex);
            }
            finally
            {
                objCommand.Parameters.Clear();
                if (connectionstate == ConnectionState.CloseOnExit)
                {
                    objConnection.Close();
                }
            }

            return o;
        }

        public DbDataReader ExecuteReader(string query)
        {
            return ExecuteReader(query, CommandType.Text, ConnectionState.CloseOnExit);
        }

        public DbDataReader ExecuteReader(string query, CommandType commandtype)
        {
            return ExecuteReader(query, commandtype, ConnectionState.CloseOnExit);
        }

        public DbDataReader ExecuteReader(string query, ConnectionState connectionstate)
        {
            return ExecuteReader(query, CommandType.Text, connectionstate);
        }

        public DbDataReader ExecuteReader(string query, CommandType commandtype, ConnectionState connectionstate)
        {
            objCommand.CommandText = query;
            objCommand.CommandType = commandtype;
            DbDataReader reader = null;
            try
            {
                if (objConnection.State == System.Data.ConnectionState.Closed)
                {
                    objConnection.Open();
                }
                if (connectionstate == ConnectionState.CloseOnExit)
                {
                    reader = objCommand.ExecuteReader(CommandBehavior.CloseConnection);
                }
                else
                {
                    reader = objCommand.ExecuteReader();
                }

            }
            catch (Exception ex)
            {
                HandleExceptions(ex);
            }
            finally
            {
                objCommand.Parameters.Clear();
            }

            return reader;
        }

        public DataSet ExecuteDataSet(string query)
        {
            return ExecuteDataSet(query, CommandType.Text, ConnectionState.CloseOnExit);
        }

        public DataSet ExecuteDataSet(string query, CommandType commandtype)
        {
            return ExecuteDataSet(query, commandtype, ConnectionState.CloseOnExit);
        }

        public DataSet ExecuteDataSet(string query, ConnectionState connectionstate)
        {
            return ExecuteDataSet(query, CommandType.Text, connectionstate);
        }

        public DataSet ExecuteDataSet(string query, CommandType commandtype, ConnectionState connectionstate)
        {
            DbDataAdapter adapter = objFactory.CreateDataAdapter();
            objCommand.CommandText = query;
            objCommand.CommandType = commandtype;
            adapter.SelectCommand = objCommand;
            DataSet ds = new DataSet();

            try
            {
                adapter.Fill(ds);
            }
            catch (Exception ex)
            {
                HandleExceptions(ex);
            }
            finally
            {
                objCommand.Parameters.Clear();
                if (connectionstate == ConnectionState.CloseOnExit)
                {
                    if (objConnection.State == System.Data.ConnectionState.Open)
                    {
                        objConnection.Close();
                    }
                }
            }
            return ds;
        }

        private void HandleExceptions(Exception ex)
        {

            throw ex;

        }

        private void WriteToLog(string msg)
        {
            StreamWriter writer = File.AppendText(LogFile);
            writer.WriteLine(DateTime.Now.ToString() + " - " + msg);
            writer.Close();
        }

        public void Dispose()
        {
            objConnection.Close();
            objConnection.Dispose();
            objCommand.Dispose();
        }

        public enum Providers
        {
            SqlServer, OleDb, Oracle, ODBC, ConfigDefined
        }

        public enum ConnectionState
        {
            KeepOpen, CloseOnExit
        }

        public interface ILoadFromDataRow
        {
            bool LoadFromDataRow(DataRow row);
        }

    }

}
</code>```

Body:
I am a newbie to 3 tier architecture and below is my DAL code

public static int Insert(string firstname, string lastname, DateTime dob, string gender,string email, string password)
    {
        // bool flag = false;
        SqlParameter pid;
        SqlParameter result;

        SqlConnection con = Generic.DBConnection.OpenConnection();

        try
        {

            SqlCommand cmd1 = new SqlCommand("Insertreg", con);
            cmd1.CommandType = CommandType.StoredProcedure;
            cmd1.Parameters.AddWithValue("@FirstName", firstname);
            cmd1.Parameters.AddWithValue("@LastName", lastname);
            cmd1.Parameters.AddWithValue("@Dob", dob);
            cmd1.Parameters.AddWithValue("@Gender", gender);
           cmd1.Parameters.AddWithValue("@EmailId", email);
            cmd1.Parameters.AddWithValue("@Password", password);
            result = cmd1.Parameters.Add("@result", System.Data.SqlDbType.Int);
            result.Direction = System.Data.ParameterDirection.Output;
            pid = cmd1.Parameters.Add("@id", System.Data.SqlDbType.Int);
            pid.Direction = System.Data.ParameterDirection.Output;
            return cmd1.ExecuteNonQuery();

            con.Close();

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

this in BAL

 public int insert(string firstname,string lastname,DateTime dob,string gender,string email,string password)
    {
      ProfileMasterDAL dal=new ProfileMasterDAL();
      try
      {
          return ProfileMasterDAL.Insert(firstname, lastname, dob, gender,email, password);
      }
      catch (Exception ex)
      {

          throw ex;
      }
        finally
      {
          dal = null;
      }

    }

I my UI

  ProfileMasterBLL pmBLL = new ProfileMasterBLL();
 pmBLL.insert(firstname, lastname, dob, gender, mobile, country, state, email, password);

Is this the correct way to code in 3 tier??I mean how to call methods from DAL to BAL and into UI?If not suggest me some good way.Thanks.


问:
Grep: Using the w command?
I'm needing some help please to find lines in a file that do not contain the whole word a.
I have tried  with grep -wv '\ba\b' but had no luck.

答:
With GNU grep:</p>

```<code>grep -v '\ba\b' file
</code>```

Title: Grep: Using the w command?

Body:
With GNU grep:

grep -v '\ba\b' file


问:
SQL WHERE Clause Condition Not working
This is my table:

```<code>City1      City2

London     New York
New York   London
Mumbai     London
New York   Mumbai
</code>```

This is, what i want:

If someone select: London + New York, then all the rows, which contain both London+New York will get displayed. No matter, what comes first.

I want this to display, if someone select: London & New York

```<code>London     New York
New York   London
</code>```

This is my current code:

```<code>WHERE City1='London' AND City2='New York';\
</code>```

It only display this:

```<code>London     New York
</code>```

答:
Specifically for two comparisons...</p>

```<code>SELECT *
  FROM my_table
 WHERE LEAST(col1,col2) = LEAST('val1','val2')
   AND GREATEST(col1,col2) = GREATEST('va1l','val2');
</code>```

Title: SQL WHERE Clause Condition Not working

Body:
This is my table:

City1      City2

London     New York
New York   London
Mumbai     London
New York   Mumbai

This is, what i want:

If someone select: London + New York, then all the rows, which contain both London+New York will get displayed. No matter, what comes first.

I want this to display, if someone select: London & New York

London     New York
New York   London

This is my current code:

WHERE City1='London' AND City2='New York';\

It only display this:

London     New York

Body:
Specifically for two comparisons...

SELECT *
  FROM my_table
 WHERE LEAST(col1,col2) = LEAST('val1','val2')
   AND GREATEST(col1,col2) = GREATEST('va1l','val2');


问:
Persistence object cannot find persistence unit from persistence.xml
Environment: Windows 7, NetBean 6.9 (the one including GlassFish v3, Java EE 6), MySQL server

I've created tables in MySQL database and using NetBean's capability by right click on the project and choose "create entity from database" (Sorry if the wording is wrong because my NetBean is in Japanese)

This will create Entities.

Now I went to test if I can access DB through Entity Manager.

Tmp.java

```<code>package local.test.tmp;
import Resources.Users;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.EntityManager;
import javax.persistence.Query;

import java.util.List;
/**
 *
 * @author m-t
 */
public class Tmp {

    private static EntityManagerFactory factory;
    private static final String WEB_PU = "WebApplication1PU";

    public static void main(String args[]) {
        factory = Persistence.createEntityManagerFactory(WEB_PU);
        EntityManager em = factory.createEntityManager();
        //read existing entries and write to concole
        Query q = em.createQuery("select * from users");

        List<Users> userList = q.getResultList();
        for(Users u : userList) {
            System.out.println(u);
        }
    }
}
</code>```

persistence.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <!--   orignal
  <persistence-unit name="WebApplication1PU" transaction-type="JTA">
    <jta-data-source>masatoJNDI</jta-data-source>
    <properties/>
  </persistence-unit>
  -->

  <persistence-unit name="WebApplication1PU" transaction-type="JTA">
    <jta-data-source>masatoJNDI</jta-data-source>
    <properties>
        <property name="toplink.jdbc.user" value="masato" />
        <property name="toplink.jdbc.password" value="foobar" />
    </properties>
  </persistence-unit>
</persistence>
</code>```

When I run Tmp.java, I can see it fails at:

```<code>factory = Persistence.createEntityManagerFactory(WEB_PU);
</code>```

Error msg:

```<code>Exception in thread "main" javax.persistence.PersistenceException: No Persistence
provider for EntityManager named WebApplication1PU
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:84)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at local.test.tmp.Tmp.main(Tmp.java:24)
</code>```

I've checked the spelling of persistence unit "WebApplication1PU" in test code matches with with persistence.xml and it is correct.

persistence.xml is located ... it's in Japanese I don't know how in English :(

Let me try..

```<code>project
 |-------web page
 |-------test package
 |-------lib
 |-------enterprise bean
 |-------*** file  //blah file, I can't translate..
               |-----MNIFEST.MF
               |-----faces-cofig.xml
               |-----persistence.xml  //HERE!!
</code>```

Since the failure is at the beginning where Factory tries to locate persistence unit in persistence.xml, I am totally confused. Is there anything I should be verifying?

please let me know if you need more clarification.

UPDATE

I've tried suggested possible solutions but no luck.. Same error message is returned.
Yes, netbean 6.9 default provider is toplink.

What I did:

Added provider to persistence.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

  <persistence-unit name="NoJSFPU" transaction-type="JTA">
    <provider>oracle.toplink.essentials.PersistenceProvider</provider>
    <jta-data-source>masatoJNDI</jta-data-source>

    <properties>
        <property name="toplink.jdbc.url" value="jdbc:mysql://localhost:3306/mytest"/>
        <property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver"/>
        <property name="toplink.jdbc.user" value="masato" />
        <property name="toplink.jdbc.password" value="mocha123" />
    </properties>
  </persistence-unit>
</persistence>
</code>```

Seems like most of people are being success with my situation. I am now start thinking there may be problem with how I run the test file or where the file is located?

Tmp.java that I executes from netbean is located at:

```<code>project
|------web page
|------source package
|          |-----------local.test.session
           |-----------local.test.tmp
                           |------------------Tmp.java //HERE
</code>```

I'm not sure if it matters though.

UPDATE 2

I've added toplink lib containing toplink-essential.jar and toplink-essential-agent.jar to the lib directory of my project and now I'm getting new error on top of original one but I believe I'm getting closer.

Looks like version attribute in persistence.xml has an issue...???

```<code>Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named WebApplication1PU: Provider named oracle.toplink.essentials.PersistenceProvider threw unexpected exception at create EntityManagerFactory:
oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException
Local Exception Stack:
Exception [TOPLINK-30005] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while searching for persistence archives with ClassLoader: sun.misc.Launcher$AppClassLoader@f6a746
Internal Exception: Exception [TOPLINK-30004] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while processing persistence.xml from URL: file:/C:/Users/m-takayashiki/Documents/NetBeansProjects/NoJSF/build/web/WEB-INF/classes/
Internal Exception:
(1. cvc-complex-type.3.1: Value '2.0' of attribute 'version' of element 'persistence' is not valid with respect to the corresponding attribute use. Attribute 'version' has a fixed value of '1.0'.)
        at oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException.exceptionSearchingForPersistenceResources(PersistenceUnitLoadingException.java:143)
        at oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider.createEntityManagerFactory(EntityManagerFactoryProvider.java:169)
        at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:110)
        at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:83)
        at local.test.tmp.Tmp.main(Tmp.java:24)
</code>```

UPDATE 3

After some research, find out version number needs to be 1.0 compliant so did I applied the fix and got new error.

```<code> <?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
  <persistence-unit name="NoJSFPU" transaction-type="JTA">
    <provider>oracle.toplink.essentials.PersistenceProvider</provider>
    <jta-data-source>masatoJNDI</jta-data-source>
    <class>local.test.session.Addresses</class>
    <class>local.test.session.Users</class>
    <properties>
        <property name="toplink.jdbc.url" value="jdbc:mysql://localhost:3306/mytest"/>
        <property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver"/>
        <property name="toplink.jdbc.user" value="masato" />
        <property name="toplink.jdbc.password" value="mocha123" />
    </properties>
  </persistence-unit>
</persistence>
</code>```

It's weird because I already specified class in persistence.xml above :(

```<code>Exception in thread "main" javax.persistence.PersistenceException: Exception [TOPLINK-7060]
 (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.ValidationException
Exception Description: Cannot acquire data source [masatoJNDI].
Internal Exception: javax.naming.NoInitialContextException: Need to specify class name in
 environment or system property, or as an applet parameter, or in an application resource
file:  java.naming.factory.initial
</code>```

UPDATE 4

I don't think this is called "solved" but after long try, I decided to just run my test code in the web app instead of running individually from netbean. I had to create web.xml myself since GlassFish does not provide it. (I see sun-web.xml but it wasn't the substitution) Then created servlet, define mapping in the web.xml and added my test code snippet to the servlet and tried on the browser. It worked, successfully obtained data from database.

I wonder what is the reason why it wasn't working when I try running just the Tmp.java (my test file) from Netbean...

答:
Please specify the <provider> for your <persistence-unit>:

```<code><!-- EclipseLink -->
<provider>
  org.eclipse.persistence.jpa.PersistenceProvider
</provider>

<!-- Hibernate -->
<provider>
  org.hibernate.ejb.HibernatePersistence
</provider>

<!-- Toplink -->
<provider>
 oracle.toplink.essentials.PersistenceProvider
</provider>
</code>```

And make your persistence-unit name is correct and file path is also in correct context path.

Body:
Environment: Windows 7, NetBean 6.9 (the one including GlassFish v3, Java EE 6), MySQL server

I've created tables in MySQL database and using NetBean's capability by right click on the project and choose "create entity from database" (Sorry if the wording is wrong because my NetBean is in Japanese)

This will create Entities.

Now I went to test if I can access DB through Entity Manager.

Tmp.java

package local.test.tmp;
import Resources.Users;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.EntityManager;
import javax.persistence.Query;

import java.util.List;
/**
 *
 * @author m-t
 */
public class Tmp {

    private static EntityManagerFactory factory;
    private static final String WEB_PU = "WebApplication1PU";

    public static void main(String args[]) {
        factory = Persistence.createEntityManagerFactory(WEB_PU);
        EntityManager em = factory.createEntityManager();
        //read existing entries and write to concole
        Query q = em.createQuery("select * from users");

        List<Users> userList = q.getResultList();
        for(Users u : userList) {
            System.out.println(u);
        }
    }
}

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

  <persistence-unit name="WebApplication1PU" transaction-type="JTA">
    <jta-data-source>masatoJNDI</jta-data-source>
    <properties>
        <property name="toplink.jdbc.user" value="masato" />
        <property name="toplink.jdbc.password" value="foobar" />
    </properties>
  </persistence-unit>
</persistence>

When I run Tmp.java, I can see it fails at:

factory = Persistence.createEntityManagerFactory(WEB_PU);

Error msg:

Exception in thread "main" javax.persistence.PersistenceException: No Persistence
provider for EntityManager named WebApplication1PU
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:84)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at local.test.tmp.Tmp.main(Tmp.java:24)

I've checked the spelling of persistence unit "WebApplication1PU" in test code matches with with persistence.xml and it is correct.

persistence.xml is located ... it's in Japanese I don't know how in English :(

Let me try..

project
 |-------web page
 |-------test package
 |-------lib
 |-------enterprise bean
 |-------*** file  //blah file, I can't translate..
               |-----MNIFEST.MF
               |-----faces-cofig.xml
               |-----persistence.xml  //HERE!!

Since the failure is at the beginning where Factory tries to locate persistence unit in persistence.xml, I am totally confused. Is there anything I should be verifying?

please let me know if you need more clarification.

UPDATE

I've tried suggested possible solutions but no luck.. Same error message is returned.
Yes, netbean 6.9 default provider is toplink.

What I did:

Added provider to persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

  <persistence-unit name="NoJSFPU" transaction-type="JTA">
    <provider>oracle.toplink.essentials.PersistenceProvider</provider>
    <jta-data-source>masatoJNDI</jta-data-source>

    <properties>
        <property name="toplink.jdbc.url" value="jdbc:mysql://localhost:3306/mytest"/>
        <property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver"/>
        <property name="toplink.jdbc.user" value="masato" />
        <property name="toplink.jdbc.password" value="mocha123" />
    </properties>
  </persistence-unit>
</persistence>

Seems like most of people are being success with my situation. I am now start thinking there may be problem with how I run the test file or where the file is located?

Tmp.java that I executes from netbean is located at:

project
|------web page
|------source package
|          |-----------local.test.session
           |-----------local.test.tmp
                           |------------------Tmp.java //HERE

I'm not sure if it matters though.

UPDATE 2

I've added toplink lib containing toplink-essential.jar and toplink-essential-agent.jar to the lib directory of my project and now I'm getting new error on top of original one but I believe I'm getting closer.

Looks like version attribute in persistence.xml has an issue...???

Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named WebApplication1PU: Provider named oracle.toplink.essentials.PersistenceProvider threw unexpected exception at create EntityManagerFactory:
oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException
Local Exception Stack:
Exception [TOPLINK-30005] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while searching for persistence archives with ClassLoader: sun.misc.Launcher$AppClassLoader@f6a746
Internal Exception: Exception [TOPLINK-30004] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while processing persistence.xml from URL: file:/C:/Users/m-takayashiki/Documents/NetBeansProjects/NoJSF/build/web/WEB-INF/classes/
Internal Exception:
(1. cvc-complex-type.3.1: Value '2.0' of attribute 'version' of element 'persistence' is not valid with respect to the corresponding attribute use. Attribute 'version' has a fixed value of '1.0'.)
        at oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException.exceptionSearchingForPersistenceResources(PersistenceUnitLoadingException.java:143)
        at oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider.createEntityManagerFactory(EntityManagerFactoryProvider.java:169)
        at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:110)
        at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:83)
        at local.test.tmp.Tmp.main(Tmp.java:24)

UPDATE 3

After some research, find out version number needs to be 1.0 compliant so did I applied the fix and got new error.

 <?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
  <persistence-unit name="NoJSFPU" transaction-type="JTA">
    <provider>oracle.toplink.essentials.PersistenceProvider</provider>
    <jta-data-source>masatoJNDI</jta-data-source>
    <class>local.test.session.Addresses</class>
    <class>local.test.session.Users</class>
    <properties>
        <property name="toplink.jdbc.url" value="jdbc:mysql://localhost:3306/mytest"/>
        <property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver"/>
        <property name="toplink.jdbc.user" value="masato" />
        <property name="toplink.jdbc.password" value="mocha123" />
    </properties>
  </persistence-unit>
</persistence>

It's weird because I already specified class in persistence.xml above :(

Exception in thread "main" javax.persistence.PersistenceException: Exception [TOPLINK-7060]
 (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.ValidationException
Exception Description: Cannot acquire data source [masatoJNDI].
Internal Exception: javax.naming.NoInitialContextException: Need to specify class name in
 environment or system property, or as an applet parameter, or in an application resource
file:  java.naming.factory.initial

UPDATE 4

I don't think this is called "solved" but after long try, I decided to just run my test code in the web app instead of running individually from netbean. I had to create web.xml myself since GlassFish does not provide it. (I see sun-web.xml but it wasn't the substitution) Then created servlet, define mapping in the web.xml and added my test code snippet to the servlet and tried on the browser. It worked, successfully obtained data from database.

I wonder what is the reason why it wasn't working when I try running just the Tmp.java (my test file) from Netbean...

Body:
Please specify the <provider> for your <persistence-unit>:

<!-- EclipseLink -->
<provider>
  org.eclipse.persistence.jpa.PersistenceProvider
</provider>

<!-- Hibernate -->
<provider>
  org.hibernate.ejb.HibernatePersistence
</provider>

<!-- Toplink -->
<provider>
 oracle.toplink.essentials.PersistenceProvider
</provider>

And make your persistence-unit name is correct and file path is also in correct context path.


问:
Returning zero results on multiple conditions codeigniter
I am currently doing a airline reservation. The fields/radio button/dropdown I have are: 2 radio button(One way, Round trip), 2 dropdown(From ,To:), 1 text field.

After filling up these fields and tried to click the "Search now". It returns no result.

NOTE: My columns on the flight table are: flight_name, flight_destination, flight_depart. I also tried to print/var_dump my variable inside of my search_result both model and controller, the value is correct/right

I also tried to print $table(it getting my flight table), $testing - getting my value, $testing2 and $testing3 is also correct but when I tried to print $query it is NULL/ retuns 0 result.

Model

```<code>public function search($table, $flight_from, $flight_to, $depart)
{
    $this->db->select('*');
    $table = $this->db->from($table);
    $testing = $this->db->where('flight_name',$flight_from)
    $testing2 = $this->db->where('flight_destination',$flight_to)
    $testing3 = $this->db->where('flight_depart',$depart);

    $query = $this->db->get();
    return $query->result();

}
</code>```

Controller

```<code>public function search()
    {
        $this->form_validation->set_error_delimiters('<div class="alert alert-danger" role="alert">', '</div>');
        $this->form_validation->set_rules('flight_from', 'Select depature', 'required|trim');
        $this->form_validation->set_rules('flight_to', 'Select Destination', 'required|trim');
        $this->form_validation->set_rules('depart', 'Date', 'required|trim');

        if ($this->form_validation->run() == FALSE)
        {
            $this->index();

        }
        else
        {
        $search_result = array(
            $flight_from = $_POST['flight_from'],
            $flight_to = $_POST['flight_to'],
            $depart = $_POST['depart']
        );
        $data['search_result'] = $this->CrudModel->search('flight',$flight_from,$flight_to,$depart);

        $this->load->view('result',$data);
        }
    }
</code>```

Question: How is it returning zero result? Even though there's an existing data. Is my query wrong?

答: Have you checked your POST variables values? Are they what you expected to be? Or you can dump the SQL statement executed behind and try to see if you get any results executing it from a SQL client.</p>

Body:
I am currently doing a airline reservation. The fields/radio button/dropdown I have are: 2 radio button(One way, Round trip), 2 dropdown(From ,To:), 1 text field.

After filling up these fields and tried to click the "Search now". It returns no result.

NOTE: My columns on the flight table are: flight_name, flight_destination, flight_depart. I also tried to print/var_dump my variable inside of my search_result both model and controller, the value is correct/right

I also tried to print $table(it getting my flight table), $testing - getting my value, $testing2 and $testing3 is also correct but when I tried to print $query it is NULL/ retuns 0 result.

Model

public function search($table, $flight_from, $flight_to, $depart)
{
    $this->db->select('*');
    $table = $this->db->from($table);
    $testing = $this->db->where('flight_name',$flight_from)
    $testing2 = $this->db->where('flight_destination',$flight_to)
    $testing3 = $this->db->where('flight_depart',$depart);

    $query = $this->db->get();
    return $query->result();

}

Controller

public function search()
    {
        $this->form_validation->set_error_delimiters('
', '
');
        $this->form_validation->set_rules('flight_from', 'Select depature', 'required|trim');
        $this->form_validation->set_rules('flight_to', 'Select Destination', 'required|trim');
        $this->form_validation->set_rules('depart', 'Date', 'required|trim');

        if ($this->form_validation->run() == FALSE)
        {
            $this->index();

        }
        else
        {
        $search_result = array(
            $flight_from = $_POST['flight_from'],
            $flight_to = $_POST['flight_to'],
            $depart = $_POST['depart']
        );
        $data['search_result'] = $this->CrudModel->search('flight',$flight_from,$flight_to,$depart);

        $this->load->view('result',$data);
        }
    }

Question: How is it returning zero result? Even though there's an existing data. Is my query wrong?


问:
SQL multiple insert with sleep
Is it possible to insert multiple data with delay kind of thing/sleep for a few second?
for example here, Im going to insert the values (1,2) into my user table. Then after 5 seconds, it will proceed to insert value (3,4) into the same table, wait for 5 seconds and finally insert (5,6) into the table.

```<code>INSERT INTO User (col1, col2)
VALUES (1, 2), (3, 4), (5, 6)
</code>```

Any suggestions are really appreciated!

答:
```<code><?php // da
$array = array(1, 2, 3, 4);
foreach ($array as $data) {
    mysqli_query($conn,"INSERT INTO ... SET data='".$data."'");
    sleep(1)
}
?>
</code>```

Something like that? I did not understand very well.

Title: SQL multiple insert with sleep

Body:
Is it possible to insert multiple data with delay kind of thing/sleep for a few second?
for example here, Im going to insert the values (1,2) into my user table. Then after 5 seconds, it will proceed to insert value (3,4) into the same table, wait for 5 seconds and finally insert (5,6) into the table.

INSERT INTO User (col1, col2)
VALUES (1, 2), (3, 4), (5, 6)

Any suggestions are really appreciated!

Body:
<?php // da
$array = array(1, 2, 3, 4);
foreach ($array as $data) {
    mysqli_query($conn,"INSERT INTO ... SET data='".$data."'");
    sleep(1)
}
?>

Something like that? I did not understand very well.


问:
codeigniter 404 function is not woking when function calling inside controller
I have set 404_override in route.php so that when there is no correspondent controller it will redirect to my error page

But my question is if there is no function inside the controller it is not redirecting properly

example: http:example.com/search/function_name
here search controller is there but the function_name not exist, how I can redirect to error page in this scenario ?

Your help will be really appreciate!

答: Create 'index' function in your error controller. Then you do not have to mention the function name in 404_override.</p>


问:
Django: issues with importing custom Python3 class
I'm new to Django (so this is likely a Python3 question). Also, I have read the other similar questions such as Error importing Python module.

I have a directory with the following structure:

-- my_class

-- -- __init__.py

-- -- custom_class_1.py

-- -- custom_class_2.py

where in the file custom_class_2.py there are the lines:

```<code>from custom_class_1 import Custom_Class_1
class Custom_Class_2:
    self.thing = Custom_Class_1()
</code>```

i.e. one class is built upon the others.

using the solution from the previously linked question

This causes the Django server to spit up this error:

```<code>from custom_class_1 import Custom_Class_1
ImportError: No module named 'Custom_Class_1'
</code>```

which makes me think I did not follow pythonic conventions when defining a class, built on another class (but all in the same directory).

What did I do wrong and how do I fix it?

答:
You could use a relative import (see PEP 328 for more details):

```<code>from .custom_class_1 import Custom_Class_1
</code>```

The . in front of custom_class_1 tells Python that the module custom_class_1 should be imported from the same directory.

Body:
I'm new to Django (so this is likely a Python3 question). Also, I have read the other similar questions such as Error importing Python module.

I have a directory with the following structure:

-- my_class

-- -- __init__.py

-- -- custom_class_1.py

-- -- custom_class_2.py

where in the file custom_class_2.py there are the lines:

from custom_class_1 import Custom_Class_1
class Custom_Class_2:
    self.thing = Custom_Class_1()

i.e. one class is built upon the others.

using the solution from the previously linked question

This causes the Django server to spit up this error:

from custom_class_1 import Custom_Class_1
ImportError: No module named 'Custom_Class_1'

which makes me think I did not follow pythonic conventions when defining a class, built on another class (but all in the same directory).

What did I do wrong and how do I fix it?

Body:
You could use a relative import (see PEP 328 for more details):

from .custom_class_1 import Custom_Class_1

The . in front of custom_class_1 tells Python that the module custom_class_1 should be imported from the same directory.


问:
How to display an image using URL?
The error is:
    "fatal error: unexpectedly found nil while unwrapping an Optional value"

I am doing the following in ViewController:

```<code>var imageURL:UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    let url = NSURL(string:"http://cdn.businessoffashion.com/site/uploads/2014/09/Karl-Lagerfeld-Self-Portrait-Courtesy.jpg")
    let data = NSData(contentsOfURL:url!)
    if data!= nil {
        imageURL.image = UIImage(data:data!)
    }
}
</code>```

I really don't understand why it will report an error on

```<code>imageURL.image = UIImage(data:data!)
</code>```

while I already told it not to proceed if data is nil.
It is not the problem of the link.
Nor is there problem with the "data". I tried to print it and it was not nil.

答:
It is pretty big possibility that you are using Alamofire and if so it is as simple as:

```<code>imageView.af_setImage(withURL: url)
</code>```

Title: How to display an image using URL?

Body:
The error is:
    "fatal error: unexpectedly found nil while unwrapping an Optional value"

I am doing the following in ViewController:

var imageURL:UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    let url = NSURL(string:"http://cdn.businessoffashion.com/site/uploads/2014/09/Karl-Lagerfeld-Self-Portrait-Courtesy.jpg")
    let data = NSData(contentsOfURL:url!)
    if data!= nil {
        imageURL.image = UIImage(data:data!)
    }
}

I really don't understand why it will report an error on

imageURL.image = UIImage(data:data!)

while I already told it not to proceed if data is nil.
It is not the problem of the link.
Nor is there problem with the "data". I tried to print it and it was not nil.

Body:
It is pretty big possibility that you are using Alamofire and if so it is as simple as:

imageView.af_setImage(withURL: url)


问:
login failed for user 'sa'.
I try to connect to sql-server by calling this class:

```<code>class DataCon
{
    public static SqlConnection Connection { get; private set; }

    public static void connectDB(string ip, string dbName, string user, string pw)
    {
        string connectionSt = "Server="+ip+";Database="+dbName+";User Id="+user+";Password="+pw+";";
        ConnectToSql(connectionSt);
    }

    private static void ConnectToSql(string connectionSt) {
        Connection = new SqlConnection(connectionSt);
        Connection.Open();
    }

    public static void connectDB(string ip, string dbName)
    {
        string connectionSt = "Server="+ip+";Database="+dbName+";Trusted_Connection=True;";
        ConnectToSql(connectionSt);
    }
}
</code>```

It work when using Windows Authentication but the Server Authentication that give login failed for user 'sa'.

On Sql server management studio I could login successfully with both Windows and Server Authentication with 'sa'.

This is the form I work with:

```<code>        private void btnConfirm_Click(object sender, EventArgs e)
    {
        try
        {
            string dbsName = "dbsStudent";
            string ip = "localhost";
            string user = txtUser.Text;
            string pw = txtUser.Text;

            if (cbAuthentication.SelectedIndex == 0)
                DataCon.connectDB(ip,dbsName);
            else
                DataCon.connectDB(ip,dbsName,user,pw);
            this.Hide();
            new ViewSt().Show();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
</code>```

答:
Maybe you should take a look about Integrated Security

Integrated Security When false, User ID and Password are specified in
  the connection. When true, the current Windows account credentials are
  used for authentication. Recognized values are true, false, yes, no,
  and sspi (strongly recommended), which is equivalent to true. If User
  ID and Password are specified and Integrated Security is set to true,
  the User ID and Password will be ignored and Integrated Security will
  be used.

So probably if you want to use user "sa" to log in to a DB you should take a look about setting Integrated security to false in your connection string and try to work it out :)

If you have any question leave me a comment here.

Title: login failed for user 'sa'.

Body:
I try to connect to sql-server by calling this class:

class DataCon
{
    public static SqlConnection Connection { get; private set; }

    public static void connectDB(string ip, string dbName, string user, string pw)
    {
        string connectionSt = "Server="+ip+";Database="+dbName+";User Id="+user+";Password="+pw+";";
        ConnectToSql(connectionSt);
    }

    private static void ConnectToSql(string connectionSt) {
        Connection = new SqlConnection(connectionSt);
        Connection.Open();
    }

    public static void connectDB(string ip, string dbName)
    {
        string connectionSt = "Server="+ip+";Database="+dbName+";Trusted_Connection=True;";
        ConnectToSql(connectionSt);
    }
}

It work when using Windows Authentication but the Server Authentication that give login failed for user 'sa'.

On Sql server management studio I could login successfully with both Windows and Server Authentication with 'sa'.

This is the form I work with:

        private void btnConfirm_Click(object sender, EventArgs e)
    {
        try
        {
            string dbsName = "dbsStudent";
            string ip = "localhost";
            string user = txtUser.Text;
            string pw = txtUser.Text;

            if (cbAuthentication.SelectedIndex == 0)
                DataCon.connectDB(ip,dbsName);
            else
                DataCon.connectDB(ip,dbsName,user,pw);
            this.Hide();
            new ViewSt().Show();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }


问:
Unity: How to make a sprite move using Vector3.Lerp() without StartCoroutine
I want to move a sprite using Vector3.Lerp() without StartCoroutine.
Starting and target points want to set in the script.
I drag & drop the sprite into the Unity Editor and run it.
However, the sprite doesn't move. Thanks.</p>

```<code>using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;

public class MyScript1 : MonoBehaviour {

public Sprite sprite;

GameObject gameObject;
SpriteRenderer spriteRenderer;
Vector3 startPosition;
Vector3 targetPosition;

void Awake()
{
    gameObject = new GameObject();
    spriteRenderer = gameObject.AddComponent<SpriteRenderer>();
}

private void Start()
{
    spriteRenderer.sprite = sprite;
    startPosition  = new Vector3(-300, 100, 0);
    targetPosition = new Vector3(100, 100, 0);
}
void Update()
{
    transform.position = Vector3.Lerp(startPosition, targetPosition , Time.deltaTime*2f);
}
}
</code>```

答:
Actually it does move but just a little and only once.

The problem is in lerp method itself: Passing Time.deltaTime*2f as the third parameter is wrong.

The third parameter of lerp method decides a point between startPosition and targetPosition and it should be between 0 and 1. it returns startPosition if 0 is passed and in your case it returns a point very very close to startPosition since you passed a very small number compared to the range (0..1)

I suggest you read the unity docs about this method

Something like this will work:

```<code>void Update()
{
    t += Time.deltaTime*2f;
    transform.position = Vector3.Lerp(startPosition, targetPosition , t);
}
</code>```

Body:
I want to move a sprite using Vector3.Lerp() without StartCoroutine.
Starting and target points want to set in the script.
I drag & drop the sprite into the Unity Editor and run it.
However, the sprite doesn't move. Thanks.

using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;

public class MyScript1 : MonoBehaviour {

public Sprite sprite;

GameObject gameObject;
SpriteRenderer spriteRenderer;
Vector3 startPosition;
Vector3 targetPosition;

void Awake()
{
    gameObject = new GameObject();
    spriteRenderer = gameObject.AddComponent<SpriteRenderer>();
}

private void Start()
{
    spriteRenderer.sprite = sprite;
    startPosition  = new Vector3(-300, 100, 0);
    targetPosition = new Vector3(100, 100, 0);
}
void Update()
{
    transform.position = Vector3.Lerp(startPosition, targetPosition , Time.deltaTime*2f);
}
}

Body:
Actually it does move but just a little and only once.

The problem is in lerp method itself: Passing Time.deltaTime*2f as the third parameter is wrong.

The third parameter of lerp method decides a point between startPosition and targetPosition and it should be between 0 and 1. it returns startPosition if 0 is passed and in your case it returns a point very very close to startPosition since you passed a very small number compared to the range (0..1)

I suggest you read the unity docs about this method

Something like this will work:

void Update()
{
    t += Time.deltaTime*2f;
    transform.position = Vector3.Lerp(startPosition, targetPosition , t);
}


问:
characters in for loop printing out too far away from values
I am very new to java and for loops. I would like my code to print out this

```<code>Andy      **
Kristy    **********
Amy       ***** `
</code>```

But my I am getting this instead

```<code>Andy          **
Kristy          **********
Amy          *****
</code>```

How do I change my for loop to stop the spacing from the names being this way? Thank you.

```<code>public static void drawChart(String name, int age) {
    System.out.print(name);
    for(int j = 1; j <= 10; j++) {
        System.out.print(" ");
    }

    for (int i=0; i<age; i++) {
        System.out.print("*");
    }

    System.out.println(" ");
}
</code>```

答:
Instead of printing 10 spaces, you can print a number of spaces with is a function of the name length:</p>

```<code>System.out.print(name);

for(int j = 1; j <= 20 - name.length(); j++) { // the value 20 should be
                                               // higher than the longest name
    System.out.print(" ");
}

for (int i=0; i<age; i++) {
    System.out.print("*");
}

System.out.println(" ");
</code>```

Body:
I am very new to java and for loops. I would like my code to print out this

Andy      **
Kristy    **********
Amy       ***** `

But my I am getting this instead

Andy          **
Kristy          **********
Amy          *****

How do I change my for loop to stop the spacing from the names being this way? Thank you.

public static void drawChart(String name, int age) {
    System.out.print(name);
    for(int j = 1; j <= 10; j++) {
        System.out.print(" ");
    }

    for (int i=0; i<age; i++) {
        System.out.print("*");
    }

    System.out.println(" ");
}

Body:
Instead of printing 10 spaces, you can print a number of spaces with is a function of the name length:

System.out.print(name);

for(int j = 1; j <= 20 - name.length(); j++) { // the value 20 should be
                                               // higher than the longest name
    System.out.print(" ");
}

for (int i=0; i<age; i++) {
    System.out.print("*");
}

System.out.println(" ");


问:
Are incrementers / decrementers (var++, var--) etc thread safe?
Inspired by this question: In Complexity Analysis why is ++ considered to be 2 operations?

Take the following psuedo code:

```<code>class test
{
   int _counter;
   void Increment()
   {
     _counter++;
   }
}
</code>```

Would this be considered thread safe on an x86 architechure? Further more are the Inc / Dec assembly instructions thread safe?

答:
No, incrementing is not thread-safe. Neither are the INC and DEC instructions. They all require a load and a store, and a thread running on another CPU could do its own load or store on the same memory location interleaved between those operations.

Some languages have built-in support for thread synchronization, but it's usually something you have to ask for, not something you get automatically on every variable. Those that don't have built-in support usually have access to a library that provides similar functionality.

OwnerDisplayName: Josh

Body:
Inspired by this question: In Complexity Analysis why is ++ considered to be 2 operations?

Take the following psuedo code:

class test
{
   int _counter;
   void Increment()
   {
     _counter++;
   }
}

Would this be considered thread safe on an x86 architechure? Further more are the Inc / Dec assembly instructions thread safe?

LastEditorDisplayName: Josh

OwnerDisplayName: Rob Kennedy

LastEditorDisplayName: Rob Kennedy


问:
How do you find a particular piece of functionality in a large codebase?
I was fascinated by the "press Tab to search site" feature in chromium, so naturally I wanted to see how exactly it was implemented in code.

A little background for anybody who aren't familiar with this. After navigating to some site, say wikipedia, and doing a search, chromium remembers the name of the query variable and will let you press tab and search the site directly from the address bar. Neat!

Problem is the codebase for chromium is huge and I've had no luck in finding the method/function that handles this.

How do you approach a large codebase when you are looking for the implementation of a particular piece of functionality? Any tricks for narrowing it down? Preferably it should not require building the software with debug symbols and following the flow through the program.

答:
There is no one size fits all approach to this sort of problem.  But for this one I would try these:

If there are any unique messages associated with the operation, grep all the source files for that string.  A common pitfall of this technique is that messages might be assembled from pieces within the application, so it is often helpful to grep for a unique short phrase—or even a single word—to identify the source of the message.  Once the text is found, then finding what references it often requires more text searches.

Trace execution from an easy-to-find point, like the command processing and dispatch loop.  I'd look for a Tab key case and follow where it leads.

Look at source code directory and filenames for hints.  Software is often constructed rationally, with good engineers dividing and conquering in a sensible way.


问:
Python: Split list in array
Just beginning with python and know enough to know I know nothing. I would like to find alternative ways of splitting a list into a list of dicts. Example list:

```<code>data = ['**adjective:**', 'nice', 'kind', 'fine',
        '**noun:**', 'benefit', 'profit', 'advantage', 'avail', 'welfare', 'use', 'weal',
        '**adverb:**', 'well', 'nicely', 'fine', 'right', 'okay']
</code>```

I would be able to get:

```<code>[{'**adjective**': ('nice', 'kind', 'fine'),
 '**noun**': ('benefit', 'profit', 'advantage', 'avail', 'welfare', 'use', 'weal'),
 '**adverb**': ('well', 'nicely', 'fine', 'right', 'okay')}]
</code>```

答:
And if there were keys without elements of a list after them ? , I thought.
So I added 'nada:' in front, 'nothing:' in the middle, and ’oops:’ at the end of the list named data.

Then, in these conditions,
the code 1 (in following) with groupy appears to give a completely false result,
the code 2 with defaultdict give a result in which keys 'nada:' , 'nothing:' , and ’oops:’ are absent.
They are also less fast than the simplest solution (code 3: Cameron, user506710)

I had an idea => codes 4 and 5.
Results are OK and executions are faster.

```<code>from time import clock

data = ['nada:',    # <<<=============
    'adjective:',
    'nice', 'kind', 'fine',
    'noun:',
    'benefit', 'profit', 'advantage', 'avail', 'welfare', 'use', 'weal',
    'nothing:', # <<<=============
    'adverb:',
    'well', 'nicely', 'fine', 'right', 'okay',
    'oops:'     # <<<=============
    ]

#------------------------------------------------------------
from itertools import groupby

te = clock()
dic1 = {}
for i, j in groupby(data, key=lambda x: x.endswith(':')):
    if i:
        key = next(j).rstrip(':')
        continue
    dic1[key] = list(j)
print clock()-te,'    groupby'
print dic1,'\n'

#------------------------------------------------------------
from collections import defaultdict
te = clock()
dic2 = defaultdict(list)
for s in data:
    if s.endswith(":"):
        key = s[:-1]
    else:
        dic2[key].append(s)
print clock()-te,'   defaultdict'
print dic2,'\n\n==================='

#=============================================================
te = clock()
dic4 = {}
for x in data:
    if x[-1] == ':' :
        start = x.rstrip(':')
        dic4[start] = []
    else:
    dic4[start].append(x)
print clock() - te
print dic4,'\n'

#------------------------------------------------------------
te = clock()
dic3 = {}
der = len(data)
for i,y in enumerate(data[::-1]):
    if y[-1]==':':
        dic3[y[0:-1]] = data[len(data)-i:der]
        der = len(data)-i-1
print clock()-te
print dic3,'\n'

    #------------------------------------------------------------
te = clock()
dic5 = {}
der = len(data)
for i in xrange(der-1,-1,-1):
    if data[i][-1]==':':
        dic5[data[i][0:-1]] = data[i+1:der]
        der = i
print clock() - te
print dic5

print '\ndic3==dic4==dic5 is',dic3==dic4==dic5
</code>```

Title: Python: Split list in array

Body:
Just beginning with python and know enough to know I know nothing. I would like to find alternative ways of splitting a list into a list of dicts. Example list:

data = ['**adjective:**', 'nice', 'kind', 'fine',
        '**noun:**', 'benefit', 'profit', 'advantage', 'avail', 'welfare', 'use', 'weal',
        '**adverb:**', 'well', 'nicely', 'fine', 'right', 'okay']

I would be able to get:

[{'**adjective**': ('nice', 'kind', 'fine'),
 '**noun**': ('benefit', 'profit', 'advantage', 'avail', 'welfare', 'use', 'weal'),
 '**adverb**': ('well', 'nicely', 'fine', 'right', 'okay')}]

Body:
And if there were keys without elements of a list after them ? , I thought.
So I added 'nada:' in front, 'nothing:' in the middle, and ’oops:’ at the end of the list named data.

Then, in these conditions,
the code 1 (in following) with groupy appears to give a completely false result,
the code 2 with defaultdict give a result in which keys 'nada:' , 'nothing:' , and ’oops:’ are absent.
They are also less fast than the simplest solution (code 3: Cameron, user506710)

I had an idea => codes 4 and 5.
Results are OK and executions are faster.

from time import clock

data = ['nada:',    # <<<=============
    'adjective:',
    'nice', 'kind', 'fine',
    'noun:',
    'benefit', 'profit', 'advantage', 'avail', 'welfare', 'use', 'weal',
    'nothing:', # <<<=============
    'adverb:',
    'well', 'nicely', 'fine', 'right', 'okay',
    'oops:'     # <<<=============
    ]

#------------------------------------------------------------
from itertools import groupby

te = clock()
dic1 = {}
for i, j in groupby(data, key=lambda x: x.endswith(':')):
    if i:
        key = next(j).rstrip(':')
        continue
    dic1[key] = list(j)
print clock()-te,'    groupby'
print dic1,'\n'

#------------------------------------------------------------
from collections import defaultdict
te = clock()
dic2 = defaultdict(list)
for s in data:
    if s.endswith(":"):
        key = s[:-1]
    else:
        dic2[key].append(s)
print clock()-te,'   defaultdict'
print dic2,'\n\n==================='

#=============================================================
te = clock()
dic4 = {}
for x in data:
    if x[-1] == ':' :
        start = x.rstrip(':')
        dic4[start] = []
    else:
    dic4[start].append(x)
print clock() - te
print dic4,'\n'

#------------------------------------------------------------
te = clock()
dic3 = {}
der = len(data)
for i,y in enumerate(data[::-1]):
    if y[-1]==':':
        dic3[y[0:-1]] = data[len(data)-i:der]
        der = len(data)-i-1
print clock()-te
print dic3,'\n'

    #------------------------------------------------------------
te = clock()
dic5 = {}
der = len(data)
for i in xrange(der-1,-1,-1):
    if data[i][-1]==':':
        dic5[data[i][0:-1]] = data[i+1:der]
        der = i
print clock() - te
print dic5

print '\ndic3==dic4==dic5 is',dic3==dic4==dic5


问:
Django Rest Framework: How to do nested serialization with ContentType
I have an application that has a Company, and this company can have 0 or multiple addresses. Companies are not the only 'models' that could have addresses. To achieve this, I use ContentTypes.

models.py

```<code>class Company(models.Model):
''' models a company in the system. '''

    number = models.CharField(_('Number'), unique=True, max_length=20)
    name = models.CharField(_('Name'), max_length=100)
    active = models.BooleanField(_('Active'), default=True)

    def _get_addresses(self):
        '''
        '''
        contentType = ContentType.objects.get(
            model=self.__class__.__name__.lower()
        )
        try:
            addresses = Address.objects.get(
                actor_type=contentType, actor_id=self.id
            )
        except Address.DoesNotExist:
            addresses = []
        return addresses
    addresses = property(_get_addresses)

class Address(Auditable):
    ''' models an address '''

    actor_type = models.ForeignKey(ContentType)
    actor_id = models.PositiveIntegerField()
    actor_object = fields.GenericForeignKey('actor_type', 'actor_id')
    _type = models.CharField(
        _('Address Type'),
        max_length=10,
        choices=sorted(TYPES.items())
    )
    active = models.BooleanField(default=True)
    address1 = models.CharField(_('Address 1'), max_length=50)
    address2 = models.CharField(
        _('Address 2'),
        max_length=50,
...
</code>```

This way, I could also have a Profile model and I could link multiple addresses to a Profile. However, my problem comes when I tried to implement the Serializers.

Serializers.py

```<code>class AddressSerializer(serializers.ModelSerializer):
    class Meta:
        model = Address
        fields = (
            '_type',
            'address1',
            'address2',
            'address3',
            'country',
            'state',
            'city'
        )

class CompanySerializer(serializers.ModelSerializer):

    addresses = AddressSerializer(required=False, many=True)

    class Meta:
        model = Company
        fields = (
            'number',
            'name',
            'addresses'
        )
</code>```

This implementation gives me this error. It says that it cannot iterate through Address model (which makes sense), but I'm not sure how to make my addresses iterable.

I would need to perform CRUD operations not only on the Company, but also on the nested Addresses.

Any suggestions/ideas on how to go about this?

答:
The following database schema is just a suggestion for the scenario prevailed.

```<code>class Details(models.Model):
    official_name = models.CharField(....)
    is_company = models.BooleanField(default=False)
    #something like that....

class Address(models.Model):
    owner = models.ForeignKey(Details, related_name='addresses')
    is_company = models.BooleanField(default=False)
    building_name = .....
    building_no = ......
    locality = ......
    #some other fields.....

class Company(models.Model):
    details = models.OneToOneField(Details, related_name='company')
    name = models.CharField(...)
    number = .....
    is_active = ........

class Profile(models.Model):
    details = models.OneToOneField(Details, related_name='profile')
    name = models.CharField(....)
    .........
</code>```

Here, each Company table and Profile table has a one to one relationship with a Details table. The Details table is related to the Address table with a Foreign key in it. So, each Company or Profile can have multiple addresses through the Details table.

So, the queries would be like,

For accessing addresses from the Company or Profile instances,

```<code>company.details.addresses.all()#or
profile.details.addresses.all()
</code>```

For reverse queries are simple as the tables contains the respective fields in them, for a given address the owner would be, address.owner.profile or address.owner.company which could be determined by a flag in the respective tables.

I know, designing the database like this is somewhat tiring. But, this does helps in serialization of the data into a better format.

Serializers can be as follows,

```<code>class DetailsSerializer(ModelSerializer):
    addresses = AddressSerializer(source='addresses', many=True)
    class Meta:
        model = Details
        fields = ('addresses',)

class AddressSerializer(ModelSerializer):
    class Meta:
        model = Address
        fields = '__all__'

class CompanySerializer(ModelSerializer):
    details = DetailsSerializer()
    class Meta:
        model = Company
        fields = ('details', .........)

class ProfileSerializer(ModelSerializer):
    details = DetailsSerializer()
    class Meta:
        model = Profile
        fields = ('details', .........)
</code>```

Body:
I have an application that has a Company, and this company can have 0 or multiple addresses. Companies are not the only 'models' that could have addresses. To achieve this, I use ContentTypes.

models.py

class Company(models.Model):
''' models a company in the system. '''

    number = models.CharField(_('Number'), unique=True, max_length=20)
    name = models.CharField(_('Name'), max_length=100)
    active = models.BooleanField(_('Active'), default=True)

    def _get_addresses(self):
        '''
        '''
        contentType = ContentType.objects.get(
            model=self.__class__.__name__.lower()
        )
        try:
            addresses = Address.objects.get(
                actor_type=contentType, actor_id=self.id
            )
        except Address.DoesNotExist:
            addresses = []
        return addresses
    addresses = property(_get_addresses)

class Address(Auditable):
    ''' models an address '''

    actor_type = models.ForeignKey(ContentType)
    actor_id = models.PositiveIntegerField()
    actor_object = fields.GenericForeignKey('actor_type', 'actor_id')
    _type = models.CharField(
        _('Address Type'),
        max_length=10,
        choices=sorted(TYPES.items())
    )
    active = models.BooleanField(default=True)
    address1 = models.CharField(_('Address 1'), max_length=50)
    address2 = models.CharField(
        _('Address 2'),
        max_length=50,
...

This way, I could also have a Profile model and I could link multiple addresses to a Profile. However, my problem comes when I tried to implement the Serializers.

Serializers.py

class AddressSerializer(serializers.ModelSerializer):
    class Meta:
        model = Address
        fields = (
            '_type',
            'address1',
            'address2',
            'address3',
            'country',
            'state',
            'city'
        )

class CompanySerializer(serializers.ModelSerializer):

    addresses = AddressSerializer(required=False, many=True)

    class Meta:
        model = Company
        fields = (
            'number',
            'name',
            'addresses'
        )

This implementation gives me this error. It says that it cannot iterate through Address model (which makes sense), but I'm not sure how to make my addresses iterable.

I would need to perform CRUD operations not only on the Company, but also on the nested Addresses.

Any suggestions/ideas on how to go about this?

Body:
The following database schema is just a suggestion for the scenario prevailed.

class Details(models.Model):
    official_name = models.CharField(....)
    is_company = models.BooleanField(default=False)
    #something like that....

class Address(models.Model):
    owner = models.ForeignKey(Details, related_name='addresses')
    is_company = models.BooleanField(default=False)
    building_name = .....
    building_no = ......
    locality = ......
    #some other fields.....

class Company(models.Model):
    details = models.OneToOneField(Details, related_name='company')
    name = models.CharField(...)
    number = .....
    is_active = ........

class Profile(models.Model):
    details = models.OneToOneField(Details, related_name='profile')
    name = models.CharField(....)
    .........

Here, each Company table and Profile table has a one to one relationship with a Details table. The Details table is related to the Address table with a Foreign key in it. So, each Company or Profile can have multiple addresses through the Details table.

So, the queries would be like,

For accessing addresses from the Company or Profile instances,

company.details.addresses.all()#or
profile.details.addresses.all()

For reverse queries are simple as the tables contains the respective fields in them, for a given address the owner would be, address.owner.profile or address.owner.company which could be determined by a flag in the respective tables.

I know, designing the database like this is somewhat tiring. But, this does helps in serialization of the data into a better format.

Serializers can be as follows,

class DetailsSerializer(ModelSerializer):
    addresses = AddressSerializer(source='addresses', many=True)
    class Meta:
        model = Details
        fields = ('addresses',)

class AddressSerializer(ModelSerializer):
    class Meta:
        model = Address
        fields = '__all__'

class CompanySerializer(ModelSerializer):
    details = DetailsSerializer()
    class Meta:
        model = Company
        fields = ('details', .........)

class ProfileSerializer(ModelSerializer):
    details = DetailsSerializer()
    class Meta:
        model = Profile
        fields = ('details', .........)


问:
PyTorch: access weights of a specific module in nn.Sequential()
When I use a pre-defined module in PyTorch, I can typically access its weights fairly easily. However, how do I access them if I wrapped the module in nn.Sequential() first? r.g:

```<code>class My_Model_1(nn.Module):
    def __init__(self,D_in,D_out):
        super(My_Model_1, self).__init__()
        self.layer = nn.Linear(D_in,D_out)
    def forward(self,x):
        out = self.layer(x)
        return out

class My_Model_2(nn.Module):
    def __init__(self,D_in,D_out):
        super(My_Model_2, self).__init__()
        self.layer = nn.Sequential(nn.Linear(D_in,D_out))
    def forward(self,x):
        out = self.layer(x)
        return out

model_1 = My_Model_1(10,10)
print(model_1.layer.weight)
model_2 = My_Model_2(10,10)
</code>```

How do I print the weights now?
model_2.layer.0.weight doesn't work.

答:
From the PyTorch forum, this is the recommended way:</p>

```<code>model_2.layer[0].weight
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When I use a pre-defined module in PyTorch, I can typically access its weights fairly easily. However, how do I access them if I wrapped the module in nn.Sequential() first? r.g:

class My_Model_1(nn.Module):
    def __init__(self,D_in,D_out):
        super(My_Model_1, self).__init__()
        self.layer = nn.Linear(D_in,D_out)
    def forward(self,x):
        out = self.layer(x)
        return out

class My_Model_2(nn.Module):
    def __init__(self,D_in,D_out):
        super(My_Model_2, self).__init__()
        self.layer = nn.Sequential(nn.Linear(D_in,D_out))
    def forward(self,x):
        out = self.layer(x)
        return out

model_1 = My_Model_1(10,10)
print(model_1.layer.weight)
model_2 = My_Model_2(10,10)

How do I print the weights now?
model_2.layer.0.weight doesn't work.

Body:
From the PyTorch forum, this is the recommended way:

model_2.layer[0].weight


问:
Docker-compose trouble to mount local volume
I've tried to setup a little apache to test my php stuff.
But the server won't let me access my files. (error 403)

I've mounted my stuff with

```<code>volumes:
- /home/<user>/Workspace/Symfony/<my_project>:/var/www/html:rw
</code>```

do I have to grant any permissions or something?
sry I'm not that familiar with docker... :-/

hope someone can help me :)

greets,
larusso

答:
According to Apache HTTPD documentation permissions should be 640 for files and 750 for directories.

Also for playing locally chmod 700 /var/www/html will work.

Body:
I've tried to setup a little apache to test my php stuff.
But the server won't let me access my files. (error 403)

I've mounted my stuff with

volumes:
- /home/<user>/Workspace/Symfony/<my_project>:/var/www/html:rw

do I have to grant any permissions or something?
sry I'm not that familiar with docker... :-/

hope someone can help me :)

greets,
larusso


问:
cypher query composite relationship match
with a graph successfully matching

```<code>MATCH (a:A)-[x:X]-(b:B)-[y:Y]-(c:C) RETURN *
</code>```

is it possible to return something like

```<code>(a:A)-[z:Z]-(c:C)
</code>```

which has a 'new' relationship z (let's call it 'linked via a B') that does not exist in the graph database, and that in effect represents a collapsing of

```<code>-[x:X]-(b:B)-[y:Y]-
</code>```

to

```<code>-[z:Z]-
</code>```

Note, that the relationship -[z:Z]- does not exist in the graph.

Possible? What would the cypher look like?

thanks

答:
This is possible with virtual relationships via APOC Procedures:</p>

```<code>MATCH (a:A)-[x:X]-(b:B)-[y:Y]-(c:C)
CALL apoc.create.vRelationship(a,'Z',{}, c) YIELD rel
RETURN a, rel, c
</code>```

Body:
with a graph successfully matching

MATCH (a:A)-[x:X]-(b:B)-[y:Y]-(c:C) RETURN *

is it possible to return something like

(a:A)-[z:Z]-(c:C)

which has a 'new' relationship z (let's call it 'linked via a B') that does not exist in the graph database, and that in effect represents a collapsing of

-[x:X]-(b:B)-[y:Y]-

to

-[z:Z]-

Note, that the relationship -[z:Z]- does not exist in the graph.

Possible? What would the cypher look like?

thanks

Body:
This is possible with virtual relationships via APOC Procedures:

MATCH (a:A)-[x:X]-(b:B)-[y:Y]-(c:C)
CALL apoc.create.vRelationship(a,'Z',{}, c) YIELD rel
RETURN a, rel, c