问:
Rails: Delayed Job --> Not picking up 'from' field when sending asynchronous mail
I'm running 2.1.1, Rails 3, and having a heckuva time getting the delayed_job gem working. If I strip out handle_asynchronously on a mailer, everything works fine...but if I put it back in, I get:

undefined method `name' for nil:NilClass (where 'name' comes from @contact.name ...which works fine when handle_asynchronously is disabled).

If I strip out all the @contact template info, I get:

"A sender (Return-Path, Sender or From) required to send a message"?

Is this me doing something wrong or some sorta bug? Relevant code below (my@email.here replaced with legit email address)

```<code>class ContactMailer < ActionMailer::Base
  default :from => "my@email.here"

  def contact_mail(contact)
    @contact = contact
    mail(:to => ENV['MANAGER_EMAIL'], :subject => 'Delayed Job Test', :from => 'my@email.here', :content_type => 'text/plain')
  end

  handle_asynchronously :contact_mail, :run_at => Proc.new { 2.seconds.from_now }
end
</code>```

Any suggestions very appreciated.

答:
Try calling the method with the actual email address:

```<code>def contact_mail(contact_email)
  mail(:to => ENV['MANAGER_EMAIL'], :subject => 'Delayed Job Test', :from => contact_email, :content_type => 'text/plain')
end
</code>```

That's the only thing I can think of which might help without seeing your actual code.  Your error says you're calling name on a nil object, but I can't see anywhere where you're calling .name...

Body:
I'm running 2.1.1, Rails 3, and having a heckuva time getting the delayed_job gem working. If I strip out handle_asynchronously on a mailer, everything works fine...but if I put it back in, I get:

undefined method `name' for nil:NilClass (where 'name' comes from @contact.name ...which works fine when handle_asynchronously is disabled).

If I strip out all the @contact template info, I get:

"A sender (Return-Path, Sender or From) required to send a message"?

Is this me doing something wrong or some sorta bug? Relevant code below (my@email.here replaced with legit email address)

class ContactMailer < ActionMailer::Base
  default :from => "my@email.here"

  def contact_mail(contact)
    @contact = contact
    mail(:to => ENV['MANAGER_EMAIL'], :subject => 'Delayed Job Test', :from => 'my@email.here', :content_type => 'text/plain')
  end

  handle_asynchronously :contact_mail, :run_at => Proc.new { 2.seconds.from_now }
end

Any suggestions very appreciated.

Body:
Try calling the method with the actual email address:

def contact_mail(contact_email)
  mail(:to => ENV['MANAGER_EMAIL'], :subject => 'Delayed Job Test', :from => contact_email, :content_type => 'text/plain')
end

That's the only thing I can think of which might help without seeing your actual code.  Your error says you're calling name on a nil object, but I can't see anywhere where you're calling .name...


来源: stackexchange

问:
How to draw a rectangle with width programmatically determined in android
I am trying a draw a red rectangle covering 40% of the width of a white rectangle in android.

xml file is like this:

```<code><?xml version="1.0" encoding="utf-8"?>

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:id="@android:id/background"
    android:gravity="center_vertical|fill_horizontal">
    <shape android:shape="rectangle">
        <size android:height="10dp" />
        <solid android:color="@color/colorWhite" />
    </shape>
</item>
<item
    android:id="@+id/level_to_next"
    android:gravity="center_vertical|left">
    <shape android:shape="rectangle">
        <size android:height="10dp"
            android:width="0dp" />
        <solid android:color="@color/colorRed_80" />
    </shape>
</item>

</layer-list>
</code>```

However, setting width to item with id level_to_next has no effect in xml file. Red rectangle covers the whole width of white rectangle.

How can I control the width of the red rectangle?

答:
Try setting the height and width of both rectangles like the following. I changed the sizes to better see the rectangles on the screen, but you can change them to something else.</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@android:id/background"
        android:gravity="center_vertical|fill_horizontal">
        <shape android:shape="rectangle">
            <size android:height="100dp"
                android:width="100dp"  />
            <solid android:color="@color/colorWhite" />
        </shape>
    </item>
    <item
        android:id="@+id/level_to_next"
        android:gravity="center_vertical|left">
        <shape android:shape="rectangle">
            <size android:height="40dp"
                android:width="40dp" />
            <solid android:color="@color/colorRed_80" />
        </shape>
    </item>
</layer-list>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying a draw a red rectangle covering 40% of the width of a white rectangle in android.

xml file is like this:

<?xml version="1.0" encoding="utf-8"?>

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:id="@android:id/background"
    android:gravity="center_vertical|fill_horizontal">
    <shape android:shape="rectangle">
        <size android:height="10dp" />
        <solid android:color="@color/colorWhite" />
    </shape>
</item>
<item
    android:id="@+id/level_to_next"
    android:gravity="center_vertical|left">
    <shape android:shape="rectangle">
        <size android:height="10dp"
            android:width="0dp" />
        <solid android:color="@color/colorRed_80" />
    </shape>
</item>

</layer-list>

However, setting width to item with id level_to_next has no effect in xml file. Red rectangle covers the whole width of white rectangle.

How can I control the width of the red rectangle?

Body:
Try setting the height and width of both rectangles like the following. I changed the sizes to better see the rectangles on the screen, but you can change them to something else.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@android:id/background"
        android:gravity="center_vertical|fill_horizontal">
        <shape android:shape="rectangle">
            <size android:height="100dp"
                android:width="100dp"  />
            <solid android:color="@color/colorWhite" />
        </shape>
    </item>
    <item
        android:id="@+id/level_to_next"
        android:gravity="center_vertical|left">
        <shape android:shape="rectangle">
            <size android:height="40dp"
                android:width="40dp" />
            <solid android:color="@color/colorRed_80" />
        </shape>
    </item>
</layer-list>


问:
PHP: Time difference in seconds
I would like to get the total number of seconds based from the given time, for example the following given data below:</p>

```<code>$timein=04-01-2017 7:56:37 am;
$timeout=04-01-2017 5:15:17 pm;
$totalseconds= ?
</code>```

Title: PHP: Time difference in seconds

Body:
I would like to get the total number of seconds based from the given time, for example the following given data below:

$timein=04-01-2017 7:56:37 am;
$timeout=04-01-2017 5:15:17 pm;
$totalseconds= ?

Body:
PHP code demo

<?php
$time1=strtotime("04-01-2017 7:56:37 am");
$time2=strtotime("04-01-2017 5:15:17 pm");
echo $time2-$time1;


问:
What would be the best way in scala to convert between case classes?
I have a model class im getting back from an api inside my servcie, and when I return it to some client I want to use my own model to keep it simpler and cleaner for the client.

example :

```<code>case class ReturnedModel(succeed: Option[String], reason: Reason, transactionId: List[Int], opId: Option[Int])

case class MyReturnedModel(reason: String)
</code>```

I might need to do more of those in the future so I thought maybe there is a best practice to do it that I dont know of, thanks!

答:
Depending on your use case:

```<code>sealed trait IKnowAReason { def reason:String }

case class ReturnedModel(succeed: Option[String], reason: Reason,
  transactionId: List[Int], opId: Option[Int]) extends IKnowAReason
</code>```

Now replace uses of MyReturnedModel with IKnowAReason. Notice the sealed, it will ensure that there are no other implementations of IKnowAReason outside the same source file.

Body:
I have a model class im getting back from an api inside my servcie, and when I return it to some client I want to use my own model to keep it simpler and cleaner for the client.

example :

case class ReturnedModel(succeed: Option[String], reason: Reason, transactionId: List[Int], opId: Option[Int])

case class MyReturnedModel(reason: String)

I might need to do more of those in the future so I thought maybe there is a best practice to do it that I dont know of, thanks!

Body:
Depending on your use case:

sealed trait IKnowAReason { def reason:String }

case class ReturnedModel(succeed: Option[String], reason: Reason,
  transactionId: List[Int], opId: Option[Int]) extends IKnowAReason

Now replace uses of MyReturnedModel with IKnowAReason. Notice the sealed, it will ensure that there are no other implementations of IKnowAReason outside the same source file.


问:
Swift Protocol-Oriented Programming: Can Protocol Extension Property Have Same Name As Base Class Property
Scenario

I am working on an SDK that will be used in two separate projects. Both projects will be using CoreData and the SDK needs to be fed data that is present in both project's managed object model. To do this I am employing a protocol-oriented design to get the SDK the data it needs.

The project will start out with a NSManagedObject base class that contains it's properties...

```<code>// Project
class Tag: NSManagedObject {
var name: String!
var code: String!
var items: [Any]!
...
}
</code>```

These names are basic and simple. It would be nice to not have to change these when we conform this class to the protocol.

The SDK declares two protocols. The first protocol will be the data source the SDK will need to populate it's views. Some class in the project will conform to this and be the delegate...

```<code>// SDK
protocol SDKDataSource {
    func getTaggableObjects() -> [Taggable]
}

var delegate: SDKDataSource!
</code>```

The second protocol will be the ultimatum the SDK will make to it's project that the NSManagedObject it will be fed should conform to...

```<code>// SDK
protocol Taggable {
    var name: String { get }
    var code: String { get }
    var items: [Any] { get }
}
</code>```

In the project I will create an extension of the class and agree to conform that class to the Taggable protocol...

```<code>// Extension (in Project w/ SDK included)
extension Tag: Taggable {

    var name: String {
        get {
            self.name
        }
    }

    var code: String {
        get {
            self.code
        }
    }

    var items: [Any] {
        get {
            self.items
        }
    }
}
</code>```

This way when the SDK asks it's datasource to getTaggableObjects() the SDK will receive the objects from the Project's CoreData model that it can understand.

Question

Does the name of property in the protocol extension have to be different than the name of the property that is in the base class, or will doing the above work? It would be nice if I knew this is okay before I implement my design.

答:
I tried and it's yes.

```<code>protocol MyArray {
    var count: Int {get}
}

extension Array: MyArray {

}
</code>```

But you can't make different implementations for different protocols that have the same function or property.

Update

If protocol and base class have property with the same name but different type. You can make different implementations.

```<code>protocol MyArray {
    var count: Float {get}
}

extension Array: MyArray {
    var count: Float {
        get {
            return 0.0
        }
    }
}
</code>```

Body:
Scenario

I am working on an SDK that will be used in two separate projects. Both projects will be using CoreData and the SDK needs to be fed data that is present in both project's managed object model. To do this I am employing a protocol-oriented design to get the SDK the data it needs.

The project will start out with a NSManagedObject base class that contains it's properties...

// Project
class Tag: NSManagedObject {
var name: String!
var code: String!
var items: [Any]!
...
}

These names are basic and simple. It would be nice to not have to change these when we conform this class to the protocol.

The SDK declares two protocols. The first protocol will be the data source the SDK will need to populate it's views. Some class in the project will conform to this and be the delegate...

// SDK
protocol SDKDataSource {
    func getTaggableObjects() -> [Taggable]
}

var delegate: SDKDataSource!

The second protocol will be the ultimatum the SDK will make to it's project that the NSManagedObject it will be fed should conform to...

// SDK
protocol Taggable {
    var name: String { get }
    var code: String { get }
    var items: [Any] { get }
}

In the project I will create an extension of the class and agree to conform that class to the Taggable protocol...

// Extension (in Project w/ SDK included)
extension Tag: Taggable {

    var name: String {
        get {
            self.name
        }
    }

    var code: String {
        get {
            self.code
        }
    }

    var items: [Any] {
        get {
            self.items
        }
    }
}

This way when the SDK asks it's datasource to getTaggableObjects() the SDK will receive the objects from the Project's CoreData model that it can understand.

Question

Does the name of property in the protocol extension have to be different than the name of the property that is in the base class, or will doing the above work? It would be nice if I knew this is okay before I implement my design.

Body:
I tried and it's yes.

protocol MyArray {
    var count: Int {get}
}

extension Array: MyArray {

}

But you can't make different implementations for different protocols that have the same function or property.

Update

If protocol and base class have property with the same name but different type. You can make different implementations.

protocol MyArray {
    var count: Float {get}
}

extension Array: MyArray {
    var count: Float {
        get {
            return 0.0
        }
    }
}


问:
Having description and contact at Mercurial web page
Currently, I am in the progress of migrating CVS to Mercurial.

http://jstock.hg.sourceforge.net/hgweb/jstock/

I would like to have contact and description information in the mercurial page.

I look at https://www.mercurial-scm.org/wiki/PublishingRepositories#Putting_useful_information_in_the_index_page

But, it seems that, modification on C:\Projects\jstock\.hg\hgrc doesn't have any effect at all. push will not update anything in sourceforge server.

So, does this mean the only way is to remote access to sourceforge mercurial server and modify the hgrc file manually?

I try to ssh to the remote machine.

```<code>[yccheok@shell-22003 .hg]$ pwd
/home/scm_hg/j/js/jstock/jstock-cloud/.hg
[yccheok@shell-22003 .hg]$ ls -al
total 56
drwxrwsr-x 3 yccheok jstock 1024 Nov 30 15:29 .
drwxrwsr-x 3 yccheok jstock   80 Nov 30 15:13 ..
-rw-rw-r-- 1 yccheok jstock   57 Nov 30 15:13 00changelog.i
-rw-rw-r-- 1 yccheok jstock   93 Nov 30 15:29 branchheads.cache
-rw-rw-r-- 1 yccheok jstock   23 Nov 30 15:13 requires
drwxrwsr-x 3 yccheok jstock 1024 Nov 30 15:29 store
-rw-rw-r-- 1 yccheok jstock  317 Nov 30 15:29 tags.cache
-rw-rw-r-- 1 yccheok jstock    7 Nov 30 15:29 undo.branch
-rw-rw-r-- 1 yccheok jstock    0 Nov 30 15:29 undo.dirstate
[yccheok@shell-22003 .hg]$
</code>```

But not able to find hgrc file.

答:
My guess would be that the sourceforge server doesn't consider your repo's .hg/hgrc file due to trust rules.  Their webserver user would need to have a trust block saying they trust .hgrc files from you, which is a risk as it allows you to have code executed as their webserver user.

If there's a way to do this the solution is going to come from somewith with strong sourceforge-fu, not mercurial-fu.

Body:
Currently, I am in the progress of migrating CVS to Mercurial.

http://jstock.hg.sourceforge.net/hgweb/jstock/

I would like to have contact and description information in the mercurial page.

I look at https://www.mercurial-scm.org/wiki/PublishingRepositories#Putting_useful_information_in_the_index_page

But, it seems that, modification on C:\Projects\jstock\.hg\hgrc doesn't have any effect at all. push will not update anything in sourceforge server.

So, does this mean the only way is to remote access to sourceforge mercurial server and modify the hgrc file manually?

I try to ssh to the remote machine.

[yccheok@shell-22003 .hg]$ pwd
/home/scm_hg/j/js/jstock/jstock-cloud/.hg
[yccheok@shell-22003 .hg]$ ls -al
total 56
drwxrwsr-x 3 yccheok jstock 1024 Nov 30 15:29 .
drwxrwsr-x 3 yccheok jstock   80 Nov 30 15:13 ..
-rw-rw-r-- 1 yccheok jstock   57 Nov 30 15:13 00changelog.i
-rw-rw-r-- 1 yccheok jstock   93 Nov 30 15:29 branchheads.cache
-rw-rw-r-- 1 yccheok jstock   23 Nov 30 15:13 requires
drwxrwsr-x 3 yccheok jstock 1024 Nov 30 15:29 store
-rw-rw-r-- 1 yccheok jstock  317 Nov 30 15:29 tags.cache
-rw-rw-r-- 1 yccheok jstock    7 Nov 30 15:29 undo.branch
-rw-rw-r-- 1 yccheok jstock    0 Nov 30 15:29 undo.dirstate
[yccheok@shell-22003 .hg]$

But not able to find hgrc file.

ContentLicense: CC BY-SA 2.5


问:
After form submit, insert data into Mysql and redirect user to an url mydomain.com/entries/last_inserted_id
After I submit a form I want the next things to happen:

Insert data into Mysql.

Redirect the user to a template I have (entries.php). This template shows all the data from the new inserted row in the table.

User should be redirected to url: www.mydomain.com/entries/last_inserted_id which will be my new template url address, where I show to the user all the data he submited in the form and which can be later accessible by any user.

How should I do this?

I am thinking like something www.mydomain.com/entries/<?php get_last_id(); ?>

Where get_last_id() will be a function which obtains the last id(which is auto increment) inserted.

Any ideeas on how to redirect a user to a url containing the id of the inserted row, based on my template which address is fixed like: entries.php Maybe some javscript code to help me?

答:
You can redirect with the header function in php.  Example:

```<code>$lastId = // whatever you're using to get last inserted id

header("Location: http://www.example.com/entries/$lastId");
</code>```

Note: make sure to use the funciton before outputting anything else.

Body:
You can redirect with the header function in php.  Example:

$lastId = // whatever you're using to get last inserted id

header("Location: http://www.example.com/entries/$lastId");

Note: make sure to use the funciton before outputting anything else.


问:
Finding SQL Days between two dates with nulls
I have two columns: rental_date and actual_retdate. I need to find the amount of days between the actual_retdate and rental_date. The actual_retdate can be null for some instances so I would like to find the amount of days between today's date and the rental date in those situations.

Currently I have:

```<code>select rental_date, actual_retdate, actual_retdate - rental_date as 'Daysbetween'
from rental_agreement
</code>```

This gives me answers of:

```
Rental_date     actual_retdate  Daysbetween
2014-07-04  2014-07-11  7
2016-05-06  2016-05-08  2
2016-08-07  2016-09-07  100
2015-02-02  2015-02-10  8
2015-10-10  2015-10-15  5
2015-08-07  2015-08-17  10
2017-02-04  NULL            NULL
2016-07-08  2016-07-16  8
2017-03-02  NULL            NULL
2015-03-15  2015-04-15  100
```

答:
Use COALESCE to provide another value for the case when a value is NULL:

```<code>SELECT
    rental_date,
    actual_retdate
    COALESCE( actual_retdate, CURDATE() ) AS actual_retdate_or_today,
    COALESCE( actual_retdate, CURDATE() ) - rental_date AS days_between
FROM
    rental_agreement
</code>```

CURDATE() returns the current date. I assume that actual_retdate is a date column rather than a datetime column, as the results may be unexpected. Also consider using DATEADD instead of the - operator for performing date-arithmetic calculations.

The reason I repeated the COALESCE( actual_retdate, CURDATE() ) expression is because in SQL you cannot reference a column expression in another column - you must either recompute the result or wrap it in an outer-query.

Body:
I have two columns: rental_date and actual_retdate. I need to find the amount of days between the actual_retdate and rental_date. The actual_retdate can be null for some instances so I would like to find the amount of days between today's date and the rental date in those situations.

Currently I have:

select rental_date, actual_retdate, actual_retdate - rental_date as 'Daysbetween'
from rental_agreement

This gives me answers of:

Rental_date     actual_retdate  Daysbetween
2014-07-04  2014-07-11  7
2016-05-06  2016-05-08  2
2016-08-07  2016-09-07  100
2015-02-02  2015-02-10  8
2015-10-10  2015-10-15  5
2015-08-07  2015-08-17  10
2017-02-04  NULL            NULL
2016-07-08  2016-07-16  8
2017-03-02  NULL            NULL
2015-03-15  2015-04-15  100

Body:
Use COALESCE to provide another value for the case when a value is NULL:

SELECT
    rental_date,
    actual_retdate
    COALESCE( actual_retdate, CURDATE() ) AS actual_retdate_or_today,
    COALESCE( actual_retdate, CURDATE() ) - rental_date AS days_between
FROM
    rental_agreement

CURDATE() returns the current date. I assume that actual_retdate is a date column rather than a datetime column, as the results may be unexpected. Also consider using DATEADD instead of the - operator for performing date-arithmetic calculations.

The reason I repeated the COALESCE( actual_retdate, CURDATE() ) expression is because in SQL you cannot reference a column expression in another column - you must either recompute the result or wrap it in an outer-query.


答:
You are looking for coalesce():

```<code>select rental_date, actual_retdate,
       coalesce(actual_retdate, curdate()) - rental_date as Daysbetween
from rental_agreement
</code>```

Title: Finding SQL Days between two dates with nulls

Body:
You are looking for coalesce():

select rental_date, actual_retdate,
       coalesce(actual_retdate, curdate()) - rental_date as Daysbetween
from rental_agreement


问:
IOS: Cannot Change Color of CAShapeLayer
I want to create a layer to act as a mask for my UIImageView which was created in interface builder. However, no matter what I do the layer remains white. The code is pretty straightforward any ideas what is causing this behavior ?

```<code>UIImage* image = [UIImage imageNamed:@"face"];
self.imageView.image = image;

CAShapeLayer *maskLayer = [[CAShapeLayer alloc]init];
maskLayer.frame = self.imageView.bounds;
maskLayer.fillColor = [[UIColor blackColor] CGColor];
maskLayer.path = CGPathCreateWithRect(self.imageView.bounds, NULL);

self.imageView.layer.mask = maskLayer;
self.maskLayer = maskLayer;
</code>```

I edited the code and added the path but it still does not work.

答: You seem to have a misconception as to what a mask is. It is a set of instructions, in effect, for injecting transparency into a view, thus "punching a hole" through the view to a greater or lesser extent (depending on the degree of transparency). It has no color. You are seeing white because that is the color of what is behind your image view — you have punched a hole through the entire image view and made it invisible.

Body:
I want to create a layer to act as a mask for my UIImageView which was created in interface builder. However, no matter what I do the layer remains white. The code is pretty straightforward any ideas what is causing this behavior ?

UIImage* image = [UIImage imageNamed:@"face"];
self.imageView.image = image;

CAShapeLayer *maskLayer = [[CAShapeLayer alloc]init];
maskLayer.frame = self.imageView.bounds;
maskLayer.fillColor = [[UIColor blackColor] CGColor];
maskLayer.path = CGPathCreateWithRect(self.imageView.bounds, NULL);

self.imageView.layer.mask = maskLayer;
self.maskLayer = maskLayer;

I edited the code and added the path but it still does not work.


答:
Sounds like you could coalesce the actual_retdate with NOW().

It would look something like:

```<code>SELECT rental_date,
    actual_retdate,
    COALESCE(actual_retdate,NOW()) - rental_date as 'Daysbetween'
FROM rental_agreement
</code>```

COALESCE basically returns the first non-null value in the list. So if actual_retdate is NULL, it will return the value for NOW().

https://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html#function_coalesce

Edit: Since Spencer mentioned subtraction not being completely reliable as a way to get the difference in number of days, here's an updated snippet using his suggested TIMESTAMPDIFF.

```<code>SELECT rental_date,
    actual_retdate,
    TIMESTAMPDIFF(DAY,COALESCE(actual_retdate,NOW()),rental_date) as 'Daysbetween'
FROM rental_agreement
</code>```

Body:
Sounds like you could coalesce the actual_retdate with NOW().

It would look something like:

SELECT rental_date,
    actual_retdate,
    COALESCE(actual_retdate,NOW()) - rental_date as 'Daysbetween'
FROM rental_agreement

COALESCE basically returns the first non-null value in the list. So if actual_retdate is NULL, it will return the value for NOW().

https://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html#function_coalesce

Edit: Since Spencer mentioned subtraction not being completely reliable as a way to get the difference in number of days, here's an updated snippet using his suggested TIMESTAMPDIFF.

SELECT rental_date,
    actual_retdate,
    TIMESTAMPDIFF(DAY,COALESCE(actual_retdate,NOW()),rental_date) as 'Daysbetween'
FROM rental_agreement


问:
Buttons and forms using JQuery
I am very new at this so any help is appreciated.
I have 4 buttons on one page and a form for each button(forms are not visible). I need to know how to use jquery to make the form show up on the same page after I click the button.
Thanks for any help.</p>

答:
The best way to do this is to relate button → form with data-* attribute

```<code><button data-toggle="#form1">Toggle #form1</button>
<button data-toggle="#form2">Toggle #form2</button>

<form id="form1">I'm form 1</form>
<form id="form2">I'm form 2</form>
</code>```

jQuery will target the ID stored inside the data-toggle attribute

```<code>$("[data-toggle]").on("click", function(e) {
  e.preventDefault();
  $(this.dataset.toggle).stop().slideToggle(1000);
});
</code>```

https://jsfiddle.net/ev0egwpy/

Title: Buttons and forms using JQuery

Body:
The best way to do this is to relate button → form with data-* attribute

<button data-toggle="#form1">Toggle #form1</button>
<button data-toggle="#form2">Toggle #form2</button>

<form id="form1">I'm form 1</form>
<form id="form2">I'm form 2</form>

jQuery will target the ID stored inside the data-toggle attribute

$("[data-toggle]").on("click", function(e) {
  e.preventDefault();
  $(this.dataset.toggle).stop().slideToggle(1000);
});

https://jsfiddle.net/ev0egwpy/


问:
Python property and setter for list as for int and strings
I have a class with variables (int, string and list). And I would like to use @property to get value of variables, setter to set values to this variables. I could implement this conception for int and string variables, but not for list. Please, help me to implement it for list too.

```<code>class MyClass:

    def __init__(self):
        self._a = 1
        self._b = 'hello'
        self._c = [1, 2, 3]

    @property
    def a(self):
        print(self._a)

    @a.setter
    def a(self, a):
        self._a = a

    @property
    def b(self):
        print(self._b)

    @b.setter
    def b(self, b):
        self._b = b

my = MyClass()

my.a
# Output: 1
my.a = 2
my.a
# Output: 2

my.b
# Output: hello
my.b = 'world'
my.b
# Output: world

# Need to implement:
my.c
# Output: [1, 2, 3]
my.c = [4, 5, 6]
my.c
# Output: [4, 5, 6]
my.c[0] = 0
my.c
# Output: [0, 5, 6]
my.c[0]
# Output: 0
</code>```

I have found similar questions, but they don't suit for me, because in this way calling operations for list would differ from int and string:

Python decorating property setter with list

Python property on a list

答:
So I believe your misunderstanding stems from not realizing that everything in python is an object.  There is no difference between the list, the string or the int.  Note that in your implementation for the int and the string there is no difference, except for some names.

I have recast your example with a single property, and then assigned all of your use cases to it to verify that it works in all cases.

Code:

```<code>class MyClass:
    def __init__(self):
        self.my_prop = None

    @property
    def my_prop(self):
        return self._my_prop

    @my_prop.setter
    def my_prop(self, my_prop):
        self._my_prop = my_prop
</code>```

Test Code:

```<code>my = MyClass()

my.my_prop = 1
assert 1 == my.my_prop
my.my_prop = 2
assert 2 == my.my_prop

my.my_prop = 'hello'
assert 'hello' == my.my_prop
my.my_prop = 'world'
assert 'world' == my.my_prop

my.my_prop = [1, 2, 3]
assert [1, 2, 3] == my.my_prop
my.my_prop = [4, 5, 6]
assert [4, 5, 6] == my.my_prop
my.my_prop[0] = 0
assert [0, 5, 6] == my.my_prop
assert 0 == my.my_prop[0]
</code>```

Body:
I have a class with variables (int, string and list). And I would like to use @property to get value of variables, setter to set values to this variables. I could implement this conception for int and string variables, but not for list. Please, help me to implement it for list too.

class MyClass:

    def __init__(self):
        self._a = 1
        self._b = 'hello'
        self._c = [1, 2, 3]

    @property
    def a(self):
        print(self._a)

    @a.setter
    def a(self, a):
        self._a = a

    @property
    def b(self):
        print(self._b)

    @b.setter
    def b(self, b):
        self._b = b

my = MyClass()

my.a
# Output: 1
my.a = 2
my.a
# Output: 2

my.b
# Output: hello
my.b = 'world'
my.b
# Output: world

# Need to implement:
my.c
# Output: [1, 2, 3]
my.c = [4, 5, 6]
my.c
# Output: [4, 5, 6]
my.c[0] = 0
my.c
# Output: [0, 5, 6]
my.c[0]
# Output: 0

I have found similar questions, but they don't suit for me, because in this way calling operations for list would differ from int and string:

Python decorating property setter with list

Python property on a list

Body:
So I believe your misunderstanding stems from not realizing that everything in python is an object.  There is no difference between the list, the string or the int.  Note that in your implementation for the int and the string there is no difference, except for some names.

I have recast your example with a single property, and then assigned all of your use cases to it to verify that it works in all cases.

Code:

class MyClass:
    def __init__(self):
        self.my_prop = None

    @property
    def my_prop(self):
        return self._my_prop

    @my_prop.setter
    def my_prop(self, my_prop):
        self._my_prop = my_prop

Test Code:

my = MyClass()

my.my_prop = 1
assert 1 == my.my_prop
my.my_prop = 2
assert 2 == my.my_prop

my.my_prop = 'hello'
assert 'hello' == my.my_prop
my.my_prop = 'world'
assert 'world' == my.my_prop

my.my_prop = [1, 2, 3]
assert [1, 2, 3] == my.my_prop
my.my_prop = [4, 5, 6]
assert [4, 5, 6] == my.my_prop
my.my_prop[0] = 0
assert [0, 5, 6] == my.my_prop
assert 0 == my.my_prop[0]


问:
Individual width for li in PHP ul -for Wordpress
I'm creating a Wordpress template and need some advice. I'm using PHP inline
ul to display post results from different categories in a home page.

That works for me when I want all the posts displayed on the same size. However, I want some of the lines (categories) to include posts in different width. This is the code I use:

```<code><ul class="posts">
<?php query_posts('category_name="category1"&showposts=4'); while (have_posts()) : the_post(); ?>
    <li>
       <div class="col-md-3">
        <?php if(has_post_thumbnail()) : ?>
                <div class="post-thumb">
                    <?php the_post_thumbnail(); ?>
                </div>
        <?php endif; ?>
                    <h4 class="post-title"> <a href="<?php the_permalink(); ?>">
                <?php the_title(); ?>
            </a> </h4>
                    <?php the_excerpt();?>
       </div>
    </li>
<?php endwhile; ?>

<?php wp_reset_query(); ?>
</ul>
</code>```

This one returns 4 inline results for Category1, all with the same width. Any suggestions on how to edit each result's width individually?

Body:
I'm creating a Wordpress template and need some advice. I'm using PHP inline
ul to display post results from different categories in a home page.

That works for me when I want all the posts displayed on the same size. However, I want some of the lines (categories) to include posts in different width. This is the code I use:

<?php query_posts('category_name="category1"&showposts=4'); while (have_posts()) : the_post(); ?>

        <?php if(has_post_thumbnail()) : ?>

                    <?php the_post_thumbnail(); ?>

        <?php endif; ?>

 <a href="<?php the_permalink(); ?>">
                <?php the_title(); ?>

                    <?php the_excerpt();?>

<?php endwhile; ?>

<?php wp_reset_query(); ?>

This one returns 4 inline results for Category1, all with the same width. Any suggestions on how to edit each result's width individually?

Body: <div class="col-md-3"> tells me this theme is based on Bootstrap. It divides the page into twelve equal columns. Try changing the class to col-md-6 and it will take up half the page. Change it to col-md-4 and it will take up a third, etc.


问:
Deploy Phoenix application in Heroku, but result in application error
I'm deployed my application in Heroku, but although deploy ok,  in browser show view:

The Only clue of error is in log of application:

```<code>  : State changed from crashed to starting
2017-03-31T020 heroku[web.1]: Process exited with status 1
1]: Starting process with command `MIX_ENV=prod mix phoenix.server`

 =INFO REPORT==== 31-Mar-2017::02:20:04 ===
     application: boom_one
     exited: {{shutdown,
               {failed_to_start_child,'Elixir.BoomOne.Endpoint',
                {shutdown,
                 {failed_to_start_child,'Elixir.Phoenix.Endpoint.Server',
                  {shutdown,
                   {failed_to_start_child,
                    {ranch_listener_sup,'Elixir.BoomOne.Endpoint.HTTP'},
                    {'EXIT',
                     {noproc,
                      {gen_server,call,
                       [ranch_server,
                        {set_new_listener_opts,'Elixir.BoomOne.Endpoint.HTTP',
                         16384,
                         [{env,
                             [{'_',[],
                               [{[<<"socket">>,<<"websocket">>],
                           [{dispatch,
                                 [],'Elixir.Phoenix.Endpoint.CowboyWebSocket',
                                 {'Elixir.Phoenix.Transports.WebSocket',
                                  {'Elixir.BoomOne.Endpoint',
                                   'Elixir.BoomOne.UserSocket',websocket}}},
                                 {'Elixir.BoomOne.Endpoint',
                                {'_',[],'Elixir.Plug.Adapters.Cowboy.Handler',
                                  []}}]}]}]}]}]}}}}}}}}},
              {'Elixir.BoomOne',start,[normal,[]]}}
     type: permanent
 ** (exit) exited in: GenServer.call(Mix.State, {:get, {Map, :get, [:debug, false]}}, 5000)
     ** (EXIT) no process
     (mix) lib/mix/cli.ex:65: Mix.CLI.run_task/2
     (elixir) lib/code.ex:363: Code.require_file/2
     (elixir) lib/gen_server.ex:596: GenServer.call/3

 {"init terminating in do_boot",{noproc,{gen_server,call,[elixir_config,{get_and_put,at_exit,[]}]}}}

 init terminating in do_boot ()
 Crash dump is being written to: erl_crash.dump...done
1]: Process exited with status 1
1]: State changed from starting to crashed
</code>```

I followed this phoenix page tutorial on heroku.

答: I encountered the same problem and solved it by hardcoding "secret_key_base" setting instead of reading from system environment variable. This solution is not generally recommended as it exposes the secret key in the code repository but it might help debug the issue.</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm deployed my application in Heroku, but although deploy ok,  in browser show view:

The Only clue of error is in log of application:

  : State changed from crashed to starting
2017-03-31T020 heroku[web.1]: Process exited with status 1
1]: Starting process with command `MIX_ENV=prod mix phoenix.server`

 =INFO REPORT==== 31-Mar-2017::02:20:04 ===
     application: boom_one
     exited: {{shutdown,
               {failed_to_start_child,'Elixir.BoomOne.Endpoint',
                {shutdown,
                 {failed_to_start_child,'Elixir.Phoenix.Endpoint.Server',
                  {shutdown,
                   {failed_to_start_child,
                    {ranch_listener_sup,'Elixir.BoomOne.Endpoint.HTTP'},
                    {'EXIT',
                     {noproc,
                      {gen_server,call,
                       [ranch_server,
                        {set_new_listener_opts,'Elixir.BoomOne.Endpoint.HTTP',
                         16384,
                         [{env,
                             [{'_',[],
                               [{[<<"socket">>,<<"websocket">>],
                           [{dispatch,
                                 [],'Elixir.Phoenix.Endpoint.CowboyWebSocket',
                                 {'Elixir.Phoenix.Transports.WebSocket',
                                  {'Elixir.BoomOne.Endpoint',
                                   'Elixir.BoomOne.UserSocket',websocket}}},
                                 {'Elixir.BoomOne.Endpoint',
                                {'_',[],'Elixir.Plug.Adapters.Cowboy.Handler',
                                  []}}]}]}]}]}]}}}}}}}}},
              {'Elixir.BoomOne',start,[normal,[]]}}
     type: permanent
 ** (exit) exited in: GenServer.call(Mix.State, {:get, {Map, :get, [:debug, false]}}, 5000)
     ** (EXIT) no process
     (mix) lib/mix/cli.ex:65: Mix.CLI.run_task/2
     (elixir) lib/code.ex:363: Code.require_file/2
     (elixir) lib/gen_server.ex:596: GenServer.call/3

 {"init terminating in do_boot",{noproc,{gen_server,call,[elixir_config,{get_and_put,at_exit,[]}]}}}

 init terminating in do_boot ()
 Crash dump is being written to: erl_crash.dump...done
1]: Process exited with status 1
1]: State changed from starting to crashed

I followed this phoenix page tutorial on heroku.


问:
Why this code returns Segmentation fault error?
I have implemented the following code to perform filter2D on a matrix. After I compiled the program it returns Segmentation fault error. In this program, I want to assign an input array in the program (don't want to load images). then perform a filter which is assigned inside the program to measure the time of the filter2D function for different matrices and kernels at runtime.

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>

using namespace std;
using namespace cv;

int main(){

    //Picture size for input and output are the same
    int Pxsize = 128;
    int Pysize = Pxsize;

    //Kernel size
    int Kxsize = 3;
    int Kysize = Kxsize;

    //filter arguments
    Point anchor;
    double delta;
    int ddepth;

    //name for out put
    char window_name[32] = "filter2D Demo";

    Mat input[128][128];
    Mat output[128][128];
    Mat kernel[3][3];

    // Initialize arguments for the filter
    anchor = Point( -1, -1 );
    delta = 0;
    ddepth = -1;

    int i,j;
    //assign data between 0 and 255 to the input matrix
    for (i=0; i<Pxsize; i++)
        for (j=0; j<Pysize; j++)
            input[i][j]=(i*j)%255;

    //assign data to the kernel
    //assign data between 0 and 255 to the input matrix
    for (i=0; i<Kxsize; i++)
        for (j=0; j<Kysize; j++)
            kernel[i][j]=1;

    //the problem is here:
    filter2D((InputArray) input,  (OutputArray) output, ddepth , ( InputArray) kernel, anchor, delta, BORDER_DEFAULT );
    namedWindow( window_name, CV_WINDOW_AUTOSIZE );
    imshow( window_name, (OutputArray) output );

    return 0;
}
```

<p>the output is: </p>

```Segmentation fault

------------------
(program exited with code: 139)
Press return to continue
```

<p>I used this command for <code>gcc 6.2.0</code> compiler in Linux mint</p>

```g++ -Wall -Wextra -Werror -pedantic -I/usr/local/include/opencv -I/usr/local/include/opencv2 -L/usr/local/lib/ -g -o "opencv"  "opencv.cpp"  -lopencv_core -lopencv_imgproc -lopencv_highgui -lopencv_ml -lopencv_video -lopencv_features2d -lopencv_calib3d -lopencv_objdetect -lopencv_contrib -lopencv_legacy -lopencv_stitching
```

Compilation finished successfully

Thanks in advance

答:
According to the comments, the problem has been found! It is because of casting the Mat object to InputArray and OutputArray in filter2D function. I changed the implementation to the following program and it works.

```<code>#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <time.h>

//Picture size for input and output are the same
#define MAX1 4096

#define Pxsize MAX1
#define Pysize Pxsize

//Kernel size
#define Kxsize 9
#define Kysize Kxsize
//number of iterations
#define NUM_LOOP 10000

using namespace std;
using namespace cv;

unsigned short int A[Pxsize][Pysize];
unsigned short int B[Pxsize][Pysize];
unsigned short int K[Kxsize][Kysize];

// measuring the time
double pTime = 0, mTime = 10; // to indicate how much program time is (pTime) and how much i want to wait (mTime)
struct timespec start;

int main(){
    //singleCore
    struct timespec tStart, tEnd;//used to record the processiing time
    double tTotal , tBest=10000;//minimum of toltal time will asign to the best time
    int w=0;

    //filter arguments
    Point anchor;
    double delta;
    int ddepth;

    //assign data between 0 and 255 to the input matrix
    int i,j;
    for (i=0; i<Pxsize; i++)
        for (j=0; j<Pysize; j++)
            A[i][j] = (i+j)%255;

    //assign data to the kernel
    //assign data between 0 and 255 to the input matrix
    for (i=0; i<Kxsize; i++)
        for (j=0; j<Kysize; j++)
            K[i][j]=1;

    cv::Mat input = cv::Mat(Pxsize, Pysize, CV_8UC1, A);
    cv::Mat kernel = cv::Mat::ones(Kxsize, Kysize, CV_8UC1);

    //name for out put

    // Initialize arguments for the filter
    anchor = Point( -1, -1 );
    delta = 0;
    ddepth = -1;

    do{// this loop repeat the body to record the best time
        clock_gettime(CLOCK_MONOTONIC,&tStart);

        //the problem is here:
        filter2D( input,   output, ddepth ,  kernel, anchor, delta, 1 );

        clock_gettime(CLOCK_MONOTONIC,&tEnd);
        tTotal = (tEnd.tv_sec - tStart.tv_sec);
        tTotal += (tEnd.tv_nsec - tStart.tv_nsec) / 1000000000.0;

        if(tTotal<tBest)
            tBest=tTotal;
        pTime += tTotal;
    } while(w++ < NUM_LOOP && pTime < mTime);

    //cout<<" "<< input<<endl;
    //cout<<" "<< output<<endl;
    printf("\nThe best time: %f sec in %d repetition for %dX%d matrix for %d, %d kernel \n",tBest,w, Pxsize, Pysize, Kxsize, Kysize);

    return 0;
}
</code>```

Body:
I have implemented the following code to perform filter2D on a matrix. After I compiled the program it returns Segmentation fault error. In this program, I want to assign an input array in the program (don't want to load images). then perform a filter which is assigned inside the program to measure the time of the filter2D function for different matrices and kernels at runtime.

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>

using namespace std;
using namespace cv;

int main(){

    //Picture size for input and output are the same
    int Pxsize = 128;
    int Pysize = Pxsize;

    //Kernel size
    int Kxsize = 3;
    int Kysize = Kxsize;

    //filter arguments
    Point anchor;
    double delta;
    int ddepth;

    //name for out put
    char window_name[32] = "filter2D Demo";

    Mat input[128][128];
    Mat output[128][128];
    Mat kernel[3][3];

    // Initialize arguments for the filter
    anchor = Point( -1, -1 );
    delta = 0;
    ddepth = -1;

    int i,j;
    //assign data between 0 and 255 to the input matrix
    for (i=0; i<Pxsize; i++)
        for (j=0; j<Pysize; j++)
            input[i][j]=(i*j)%255;

    //assign data to the kernel
    //assign data between 0 and 255 to the input matrix
    for (i=0; i<Kxsize; i++)
        for (j=0; j<Kysize; j++)
            kernel[i][j]=1;

    //the problem is here:
    filter2D((InputArray) input,  (OutputArray) output, ddepth , ( InputArray) kernel, anchor, delta, BORDER_DEFAULT );
    namedWindow( window_name, CV_WINDOW_AUTOSIZE );
    imshow( window_name, (OutputArray) output );

    return 0;
}

the output is:

Segmentation fault

------------------
(program exited with code: 139)
Press return to continue

I used this command for gcc 6.2.0 compiler in Linux mint

g++ -Wall -Wextra -Werror -pedantic -I/usr/local/include/opencv -I/usr/local/include/opencv2 -L/usr/local/lib/ -g -o "opencv"  "opencv.cpp"  -lopencv_core -lopencv_imgproc -lopencv_highgui -lopencv_ml -lopencv_video -lopencv_features2d -lopencv_calib3d -lopencv_objdetect -lopencv_contrib -lopencv_legacy -lopencv_stitching

Compilation finished successfully

Thanks in advance

Body:
According to the comments, the problem has been found! It is because of casting the Mat object to InputArray and OutputArray in filter2D function. I changed the implementation to the following program and it works.

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <time.h>

//Picture size for input and output are the same
#define MAX1 4096

#define Pxsize MAX1
#define Pysize Pxsize

//Kernel size
#define Kxsize 9
#define Kysize Kxsize
//number of iterations
#define NUM_LOOP 10000

using namespace std;
using namespace cv;

unsigned short int A[Pxsize][Pysize];
unsigned short int B[Pxsize][Pysize];
unsigned short int K[Kxsize][Kysize];

// measuring the time
double pTime = 0, mTime = 10; // to indicate how much program time is (pTime) and how much i want to wait (mTime)
struct timespec start;

int main(){
    //singleCore
    struct timespec tStart, tEnd;//used to record the processiing time
    double tTotal , tBest=10000;//minimum of toltal time will asign to the best time
    int w=0;

    //filter arguments
    Point anchor;
    double delta;
    int ddepth;

    //assign data between 0 and 255 to the input matrix
    int i,j;
    for (i=0; i<Pxsize; i++)
        for (j=0; j<Pysize; j++)
            A[i][j] = (i+j)%255;

    //assign data to the kernel
    //assign data between 0 and 255 to the input matrix
    for (i=0; i<Kxsize; i++)
        for (j=0; j<Kysize; j++)
            K[i][j]=1;

    cv::Mat input = cv::Mat(Pxsize, Pysize, CV_8UC1, A);
    cv::Mat kernel = cv::Mat::ones(Kxsize, Kysize, CV_8UC1);

    //name for out put

    // Initialize arguments for the filter
    anchor = Point( -1, -1 );
    delta = 0;
    ddepth = -1;

    do{// this loop repeat the body to record the best time
        clock_gettime(CLOCK_MONOTONIC,&tStart);

        //the problem is here:
        filter2D( input,   output, ddepth ,  kernel, anchor, delta, 1 );

        clock_gettime(CLOCK_MONOTONIC,&tEnd);
        tTotal = (tEnd.tv_sec - tStart.tv_sec);
        tTotal += (tEnd.tv_nsec - tStart.tv_nsec) / 1000000000.0;

        if(tTotal<tBest)
            tBest=tTotal;
        pTime += tTotal;
    } while(w++ < NUM_LOOP && pTime < mTime);

    //cout<<" "<< input<<endl;
    //cout<<" "<< output<<endl;
    printf("\nThe best time: %f sec in %d repetition for %dX%d matrix for %d, %d kernel \n",tBest,w, Pxsize, Pysize, Kxsize, Kysize);

    return 0;
}


问:
Jquery function to detect cookies and set focus
I have an asp.net login control and I have implemented the user name to be remembered using cookies. How can I use Jquery(javascript) function to detect cookies and set the focus on the password field?</p>

答:
Here's a simple cookies plugin for jquery:
https://github.com/carhartl/jquery-cookie

```<code>var userCookie = $.cookie("userName");
if(userCookie){
    // userName cookie exists
    $("#username").val(userCookie)
}
</code>```

And focusing on the password field is as simple as

```<code>$("#password").focus()
</code>```

Body:
Here's a simple cookies plugin for jquery:
https://github.com/carhartl/jquery-cookie

var userCookie = $.cookie("userName");
if(userCookie){
    // userName cookie exists
    $("#username").val(userCookie)
}

And focusing on the password field is as simple as

$("#password").focus()


问:
Hyperledger peer creation error
I'm trying to create a genesis block with the command:

```<code>peer channel create -c myc
</code>```

following the install_instantiate.md file.

However I keep getting an error-message that there is no ordering service endpoint created. Somebody who can help me with this please?

答:
I guess you are working with Fabric 1.0.0-alpha. There
the API has been changed so that you have to pass an orderer now.

peer channel create -o orderer0:7050 -c mychannel

Please have a look at the following document:
https://fabric-rtd.readthedocs.io/en/latest/getting_started.html#create-channel

Title: Hyperledger peer creation error

Body:
I'm trying to create a genesis block with the command:

peer channel create -c myc

following the install_instantiate.md file.

However I keep getting an error-message that there is no ordering service endpoint created. Somebody who can help me with this please?


问:
Exporting SQL query results to pandas dataframe
```<code>id    date       temp       prcp
1   2015-01-01  -27.18      0
1   2015-01-02  -25.9       1.03
1   2015-01-03  -17.89      9.44
1   2015-01-04  -17.89      9.44
1   2015-01-05  -17.89      9.44

import dataset
import pandas as pd

db = dataset.connect(path_to_database_on_AWS)
res = db.query(SELECT * FROM tbl WHERE id=1 and date >= '2015-01-03' and date <= '2015-01-05')
pd.read_sql(res, con=db)
</code>```

In the above code, I am using the query method from the python dataset library to read in from a table and then want to export the results as a pandas dataframe, however, I get this bug:

```<code>*** AttributeError: 'Database' object has no attribute 'cursor'
</code>```

How do I export query results to pandas dataframe?

答:
You could do something like this:

```<code>   import sqlite3
   import pandas as pd
   con = sqlite3.connect('path_to_your_sql')
   myFrames = pd.read_sql_query('your query', con)
</code>```

Edit: for non sqlite db you could use this for the connection:

```<code>from sqlalchemy import create_engine
con = create_engine('dialect+driver://username:password@host:port/database')
</code>```

docs for create_engine

Body:
id    date       temp       prcp
1   2015-01-01  -27.18      0
1   2015-01-02  -25.9       1.03
1   2015-01-03  -17.89      9.44
1   2015-01-04  -17.89      9.44
1   2015-01-05  -17.89      9.44

import dataset
import pandas as pd

db = dataset.connect(path_to_database_on_AWS)
res = db.query(SELECT * FROM tbl WHERE id=1 and date >= '2015-01-03' and date <= '2015-01-05')
pd.read_sql(res, con=db)

In the above code, I am using the query method from the python dataset library to read in from a table and then want to export the results as a pandas dataframe, however, I get this bug:

*** AttributeError: 'Database' object has no attribute 'cursor'

How do I export query results to pandas dataframe?

Body:
You could do something like this:

   import sqlite3
   import pandas as pd
   con = sqlite3.connect('path_to_your_sql')
   myFrames = pd.read_sql_query('your query', con)

Edit: for non sqlite db you could use this for the connection:

from sqlalchemy import create_engine
con = create_engine('dialect+driver://username:password@host:port/database')

docs for create_engine


答:
From the docs:

The layer’s alpha channel determines how much of the layer’s content
  and background shows through. Fully or partially opaque pixels allow
  the underlying content to show through but fully transparent pixels
  block that content.

Black fill (interior of the closed path) = opaque pixels

Area outside of the closed path = transparent pixels

Image will appear on the interior region of your path and not appear outside of that path. The actual colour is irrelevant: when you set a layer as a mask, all we are interested in now is opacity.

The path is ostensively the same size as the imageView, so you won't see any difference as the mask matches the imageView bounds. Additionally , if you use this code before the geometry is fully set, such as in viewDidLoad, you may not get the results you expect.

As matt suggests - you need to think what result you are after.

If you want a "black translucent color" - or similar - consider adding another translucent-colored layer to the mix. But this is not a mask.

Title: IOS: Cannot Change Color of CAShapeLayer


问:
Mysql Duplicate Entry Error On Insert
Something very bizare is happening right now and I don't understand how to fix it... Well, temporarily I do but the solution I found is not how the program should behave...

So I have this employeetimesheets table:

```<code>empsheet_id | employee_id |timesheet_status |last_update |isWeekNumber|total_hours|isMonth|isYear|overtimeHours
</code>```

the variables:

```<code>    $isWeekNumber =  $_POST['isWeekNumber'];
    $attendanceyear= $_POST['attendanceyear'];
    $attendancemonth= $_POST['attendancemonth'];
    $employee_id=  $_POST['employee_id'];
</code>```

the query:

```<code>    $insertemptime= $db->prepare("INSERT INTO employeetimesheets (employee_id,isWeekNumber,isMonth,isYear) VALUES (?,?,?,?)");
    $insertemptime->bind_param("iiss",$employee_id,$isWeekNumber,$attendancemonth,$attendanceyear);
    $insertemptime->execute() or die(mysqli_error($db));
    $insertemptime->close();
</code>```

On insert NEW row I receive this error when there is already a row with same employee_id

Fatal error: Uncaught exception 'mysqli_sql_exception' with message
  'Duplicate entry '6748372' for key 'EmployeeTimeSheetsKey''

If I delete the row with the employee_id I'm trying to insert, the query works. I"m confused because it's an insert statement... I should be able to add as many rows I want with the same employee_id, yes? Anybody has an idea what's going on?

答:
You've set the field employee_id  to unique instead of index

Remove unique index from field and add index again without unique

Example sql code

Check index

```<code>SHOW INDEX FROM employeetimesheets;
</code>```

Remove Index

```<code>ALTER TABLE employeetimesheets DROP INDEX employee_id;
</code>```

Add Index

```<code>CREATE INDEX employeetimesheets ON employee_id;
</code>```

Title: Mysql Duplicate Entry Error On Insert

Body:
Something very bizare is happening right now and I don't understand how to fix it... Well, temporarily I do but the solution I found is not how the program should behave...

So I have this employeetimesheets table:

empsheet_id | employee_id |timesheet_status |last_update |isWeekNumber|total_hours|isMonth|isYear|overtimeHours

the variables:

    $isWeekNumber =  $_POST['isWeekNumber'];
    $attendanceyear= $_POST['attendanceyear'];
    $attendancemonth= $_POST['attendancemonth'];
    $employee_id=  $_POST['employee_id'];

the query:

    $insertemptime= $db->prepare("INSERT INTO employeetimesheets (employee_id,isWeekNumber,isMonth,isYear) VALUES (?,?,?,?)");
    $insertemptime->bind_param("iiss",$employee_id,$isWeekNumber,$attendancemonth,$attendanceyear);
    $insertemptime->execute() or die(mysqli_error($db));
    $insertemptime->close();

On insert NEW row I receive this error when there is already a row with same employee_id

Fatal error: Uncaught exception 'mysqli_sql_exception' with message
  'Duplicate entry '6748372' for key 'EmployeeTimeSheetsKey''

If I delete the row with the employee_id I'm trying to insert, the query works. I"m confused because it's an insert statement... I should be able to add as many rows I want with the same employee_id, yes? Anybody has an idea what's going on?

Body:
You've set the field employee_id  to unique instead of index

Remove unique index from field and add index again without unique

Example sql code

Check index

SHOW INDEX FROM employeetimesheets;

Remove Index

ALTER TABLE employeetimesheets DROP INDEX employee_id;

Add Index

CREATE INDEX employeetimesheets ON employee_id;


问:
SQL - Constraint on insert value to be less than existed value in other rows
I do have a table that looks like:

```<code>CategoryID | GameNO | Name         | Price
-----------+--------+--------------+-------
     1     |    1   | Zelda        |   10
     1     |    2   | Sonic        |   12
     2     |    1   | Metal Gear   |   21
     2     |    2   | Street Fight |   15
</code>```

Where both CategoryID & GameNo are a primary key, and GameNo is a foreign key to another relation.

I want to alter the table and add constraint that each category game price to not be greater than the double price of any other from the same category?

For instance if I want to do:

```<code>insert into tableName
values (1, 3, 'Super Mario', 21);
</code>```

The inserted price for Super Mario 21 is greater than the double price of Zelda which is 10. I want to constraint this to be not accepted?

答:
If there is a front-end you should get the value first and limit what they are allowed to enter and tell them why.

Constraints are really a single row thing. Logic like if state='CA' taxes must be greater than zero.

You didn't say what flavor of SQL you use, so I'll show SQL Server.

In my save stored proc I would have:

```<code>if ((select max(price) * 2 from tablename where CategoryID = @CategoryID) < @Price)
begin
   -- throw exception or raise error here.
end

insert into tablename ....
</code>```

As a side note, there should be a single ID that is unique in the table for each row. What do you do if you want to change Zelda to category 2?  "Game No = 1" is already taken. And foreign keys work best with a single ID. Last nag, a lot of the new development tools (Entity Framework comes to mind) almost demand a single unique key.

Body:
I do have a table that looks like:

CategoryID | GameNO | Name         | Price
-----------+--------+--------------+-------
     1     |    1   | Zelda        |   10
     1     |    2   | Sonic        |   12
     2     |    1   | Metal Gear   |   21
     2     |    2   | Street Fight |   15

Where both CategoryID & GameNo are a primary key, and GameNo is a foreign key to another relation.

I want to alter the table and add constraint that each category game price to not be greater than the double price of any other from the same category?

For instance if I want to do:

insert into tableName
values (1, 3, 'Super Mario', 21);

The inserted price for Super Mario 21 is greater than the double price of Zelda which is 10. I want to constraint this to be not accepted?

Body:
If there is a front-end you should get the value first and limit what they are allowed to enter and tell them why.

Constraints are really a single row thing. Logic like if state='CA' taxes must be greater than zero.

You didn't say what flavor of SQL you use, so I'll show SQL Server.

In my save stored proc I would have:

if ((select max(price) * 2 from tablename where CategoryID = @CategoryID) < @Price)
begin
   -- throw exception or raise error here.
end

insert into tablename ....

As a side note, there should be a single ID that is unique in the table for each row. What do you do if you want to change Zelda to category 2?  "Game No = 1" is already taken. And foreign keys work best with a single ID. Last nag, a lot of the new development tools (Entity Framework comes to mind) almost demand a single unique key.


问:
how to convert string to date (HHMMMDD) (hour, month, day-of-month)
I try to convert a string into date type. This is the whole what I did.

```<code>DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HHMMMDD");

String date = "23Mar25";

System.out.println(date);

LocalDate localDate = LocalDate.parse(date, formatter);

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

And I got the error information as

```<code>Text '23Mar25' could not be parsed:
Unable to obtain LocalDate from TemporalAccessor:
{MonthOfYear=3, DayOfYear=25},ISO resolved to 23:00 of type
java.time.format.Parsed at
java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
</code>```

Anyone can help me to solve it?

答:
tl;dr

```<code>LocalTime.parse( "23Mar25" , DateTimeFormatter.ofPattern ( "HHMMMdd", Locale.US )
         .toString()  // 23:00
</code>```

…and…

```<code>MonthDay.parse( "23Mar25" , DateTimeFormatter.ofPattern ( "HHMMMdd", Locale.US )
        .toString()   // --03-25
</code>```

Details

If you are certain that input indeed represents an hour-of-day, month, and day-of-month…

DateTimeFormatter

Define a single DateTimeFormatter. Be sure to specify a Locale for the human language by which to translate the abbreviated name of the month.

```<code>String input = "23Mar25";
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "HHMMMdd", Locale.US );
</code>```

LocalTime

Use that formatter twice. Once to produce a time-of-day as a LocalTime object to hold the hour-of-day.

```<code>LocalTime lt = LocalTime.parse ( input, f );
</code>```

MonthDay

Again to produce a MonthDay object to hold the month and the day-of-month.

```<code>MonthDay md = MonthDay.parse ( input , f  );
</code>```

ZoneId

To make a specific moment of that value, we must assign a year and a time zone. If we want to use use the current year, we need a time zone for that as well. Keep in mind the fact that for any given moment both the date and the time-of-day vary around the globe by zone.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

```<code>ZoneId z = ZoneId.of ( "America/Montreal" );
</code>```

LocalDate

Determine a LocalDate object by assigning a year to our MonthDay object.

```<code>int yearNumber = Year.now ( z )
                     .getValue ( ) ;
LocalDate ld = md.atYear ( yearNumber );
</code>```

ZonedDateTime

Combine with the LocalTime to get an exact moment, a point on the timeline. Result is a ZonedDateTime object.

```<code>ZonedDateTime zdt = ZonedDateTime.of ( ld, lt, z );
</code>```

Dump to console.

```<code>System.out.println ( "input: " + input );
System.out.println ( "lt: " + lt );
System.out.println ( "md: " + md );
System.out.println ( "ld: " + ld );
System.out.println ( "zdt: " + zdt );
</code>```

input: 23Mar25

lt: 23:00

md: --03-25

ld: 2017-03-25

zdt: 2017-03-25T23:00-04:00[America/Montreal]

OffsetDateTime

If your input is intended for UTC, then instead of ZoneId and ZonedDateTime, use ZoneOffset.UTC constant and OffsetDateTime class in code similar to above.

```<code>OffsetDateTime zdt = OffsetDateTime.of ( ld, lt, ZoneOffset.UTC );
</code>```

ISO 8601

Notice the output, the strings generated by the toString methods. The java.time classes use the ISO 8601 standard formats by default when parsing/generating strings. I strongly suggest you and your data-source use these standard formats rather than invent your own such as seen in the Question. The java.time classes can directly parse as well as generate such standard strings without needing to specify a formatting pattern.

To generate strings in other formats, use the DateTimeFormatter class. That topic is covered by many other Stack Overflow pages, so search for many examples and more discussion.

Body:
I try to convert a string into date type. This is the whole what I did.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HHMMMDD");

String date = "23Mar25";

System.out.println(date);

LocalDate localDate = LocalDate.parse(date, formatter);

System.out.println(localDate);

And I got the error information as

Text '23Mar25' could not be parsed:
Unable to obtain LocalDate from TemporalAccessor:
{MonthOfYear=3, DayOfYear=25},ISO resolved to 23:00 of type
java.time.format.Parsed at
java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)

Anyone can help me to solve it?

Body:
tl;dr

LocalTime.parse( "23Mar25" , DateTimeFormatter.ofPattern ( "HHMMMdd", Locale.US )
         .toString()  // 23:00

…and…

MonthDay.parse( "23Mar25" , DateTimeFormatter.ofPattern ( "HHMMMdd", Locale.US )
        .toString()   // --03-25

Details

If you are certain that input indeed represents an hour-of-day, month, and day-of-month…

DateTimeFormatter

Define a single DateTimeFormatter. Be sure to specify a Locale for the human language by which to translate the abbreviated name of the month.

String input = "23Mar25";
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "HHMMMdd", Locale.US );

LocalTime

Use that formatter twice. Once to produce a time-of-day as a LocalTime object to hold the hour-of-day.

LocalTime lt = LocalTime.parse ( input, f );

MonthDay

Again to produce a MonthDay object to hold the month and the day-of-month.

MonthDay md = MonthDay.parse ( input , f  );

ZoneId

To make a specific moment of that value, we must assign a year and a time zone. If we want to use use the current year, we need a time zone for that as well. Keep in mind the fact that for any given moment both the date and the time-of-day vary around the globe by zone.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of ( "America/Montreal" );

LocalDate

Determine a LocalDate object by assigning a year to our MonthDay object.

int yearNumber = Year.now ( z )
                     .getValue ( ) ;
LocalDate ld = md.atYear ( yearNumber );

ZonedDateTime

Combine with the LocalTime to get an exact moment, a point on the timeline. Result is a ZonedDateTime object.

ZonedDateTime zdt = ZonedDateTime.of ( ld, lt, z );

Dump to console.

System.out.println ( "input: " + input );
System.out.println ( "lt: " + lt );
System.out.println ( "md: " + md );
System.out.println ( "ld: " + ld );
System.out.println ( "zdt: " + zdt );

input: 23Mar25

lt: 23:00

md: --03-25

ld: 2017-03-25

zdt: 2017-03-25T23:00-04:00[America/Montreal]

OffsetDateTime

If your input is intended for UTC, then instead of ZoneId and ZonedDateTime, use ZoneOffset.UTC constant and OffsetDateTime class in code similar to above.

OffsetDateTime zdt = OffsetDateTime.of ( ld, lt, ZoneOffset.UTC );

ISO 8601

Notice the output, the strings generated by the toString methods. The java.time classes use the ISO 8601 standard formats by default when parsing/generating strings. I strongly suggest you and your data-source use these standard formats rather than invent your own such as seen in the Question. The java.time classes can directly parse as well as generate such standard strings without needing to specify a formatting pattern.

To generate strings in other formats, use the DateTimeFormatter class. That topic is covered by many other Stack Overflow pages, so search for many examples and more discussion.


问:
How to create a WCF service
I want to learn step by step how to create a WCF service, starting from something very simple.

Can anyone help me?

答:
I found this webcast to be an excellent introduction to WCF.

I would also recommend anything by Juval Lowy, especially his book Programming WCF Services.  His website, IDesign.net, has a lot of free code downloads that I find especially instructive.

Title: How to create a WCF service


问:
Calling functions in every possible combination
I have a list of functions. I want to call each possible combination of these functions, where each function is either called once or not at all. It doesn't matter that order they are in.

Example:

```<code>functionList = [function1, function2, function3]
</code>```

I would like to call function1() on its own and also function1() + function2() and also function1() + function2() + function3() and also function2() etc

How would I implement this in python? I thought to use itertools.combinations however it doesn't seem I can use that for my problem.

答:
You can use powerset function from the the itertools recipe page:

```<code>from itertools import chain, combinations

def powerset(iterable):
    """
    powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)
    """
    xs = list(iterable)
    # note we return an iterator rather than a list
    return chain.from_iterable(combinations(xs,n) for n in range(len(xs)+1))

def f1():
    return "f1"

def f2():
    return "f2"

def f3():
    return "f3"

functions = [f1, f2, f3]

for function_comb in powerset(functions):
   out = ""
   if not function_comb:
      continue # skip the empty set of functions
   for f in function_comb:
      out += f()
   print out
</code>```

It produces the following output:

```<code>f1
f2
f3
f1f2
f1f3
f2f3
f1f2f3
</code>```

Body:
I have a list of functions. I want to call each possible combination of these functions, where each function is either called once or not at all. It doesn't matter that order they are in.

Example:

functionList = [function1, function2, function3]

I would like to call function1() on its own and also function1() + function2() and also function1() + function2() + function3() and also function2() etc

How would I implement this in python? I thought to use itertools.combinations however it doesn't seem I can use that for my problem.

Body:
You can use powerset function from the the itertools recipe page:

from itertools import chain, combinations

def powerset(iterable):
    """
    powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)
    """
    xs = list(iterable)
    # note we return an iterator rather than a list
    return chain.from_iterable(combinations(xs,n) for n in range(len(xs)+1))

def f1():
    return "f1"

def f2():
    return "f2"

def f3():
    return "f3"

functions = [f1, f2, f3]

for function_comb in powerset(functions):
   out = ""
   if not function_comb:
      continue # skip the empty set of functions
   for f in function_comb:
      out += f()
   print out

It produces the following output:

f1
f2
f3
f1f2
f1f3
f2f3
f1f2f3


问:
How to output a reverse expanded sum
I want to output a reverse expanded sum, which should give me an output like this:

Reverse expanded sum:
  Output the expanded sum in reverse.
  For example, if the user entered 7, then your program should output:

```<code>7+6+5+4+3+2+1=28
</code>```

The code below is giving me an non-stop output instead with +-12+-13 format:

```<code> public static int printSum(int n, boolean reverse) {
    int sum = 0;
    String s = "";
    for(int i = 1; i < n+1; i--) {
        sum += i;//was =
        //System.out.print(i + "+");
    }
    for(int i = 1; i <n; i--) {
        s =String.valueOf(i);
        System.out.print(s + "+");
    }
    //System.out.print(i);

    System.out.print( n + "=" + sum);
    return sum;
}
</code>```

I used case statements in the main method to call the printSum method:

```<code>//reverse expanded sum
case 2:
    System.out.print("Enter a positive integer.\n");
    number = console.nextInt();
    printSum(number, false);
    break;
</code>```

答:
Think this does what you linked in the image assuming it only takes positive integers given "Enter a positive integer.\n"</p>

```<code>  public static int printSum(int n) {
        int sum = 0;
        for(int x = 0; x < n; x++){
            sum += n - x;
            if(x != n - 1){
                System.out.print((n - x) + "+");
            }
            else{
                System.out.print((n - x) + "=" + sum);
            }
        }
        return sum;
    }
</code>```

Title: How to output a reverse expanded sum

Body:
I want to output a reverse expanded sum, which should give me an output like this:

Reverse expanded sum:
  Output the expanded sum in reverse.
  For example, if the user entered 7, then your program should output:

7+6+5+4+3+2+1=28

The code below is giving me an non-stop output instead with +-12+-13 format:

 public static int printSum(int n, boolean reverse) {
    int sum = 0;
    String s = "";
    for(int i = 1; i < n+1; i--) {
        sum += i;//was =
        //System.out.print(i + "+");
    }
    for(int i = 1; i <n; i--) {
        s =String.valueOf(i);
        System.out.print(s + "+");
    }
    //System.out.print(i);

    System.out.print( n + "=" + sum);
    return sum;
}

I used case statements in the main method to call the printSum method:

//reverse expanded sum
case 2:
    System.out.print("Enter a positive integer.\n");
    number = console.nextInt();
    printSum(number, false);
    break;

Body:
Think this does what you linked in the image assuming it only takes positive integers given "Enter a positive integer.\n"

  public static int printSum(int n) {
        int sum = 0;
        for(int x = 0; x < n; x++){
            sum += n - x;
            if(x != n - 1){
                System.out.print((n - x) + "+");
            }
            else{
                System.out.print((n - x) + "=" + sum);
            }
        }
        return sum;
    }


问:
How to format and move mutiple regression equation for each group in ggplot?
I have been searching this for a while but can't get a solution.

```<code>This is the data I have
Display     Frustration  Neck Angle
1 Microscope          55 40.77672
2 Microscope          70 53.74905
3 Loupe               10 52.41799
4 Loupe               5  62.36514
5 Video               25 49.83489
6 Video               10 68.19686
my current code

lm_eqn <- function(df){
 m <- lm(Neck ~ Frustration, df);
  eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,
                   list(a = format(coef(m)[1], digits = 2),
                        b = format(coef(m)[2], digits = 2),
                        r2 = format(summary(m)$r.squared, digits = 3)))
  as.character(as.expression(eq));
}
eq <- ddply(df.frus,"Display",lm_eqn)
p<- ggplot(df.frus,aes(x=Frustration,y=Neck,col=Display))+geom_jitter(width=0.5)+geom_smooth(method="lm",se=FALSE)
p+geom_text(data=eq,aes(x = 30, y = 80,label=V1), parse = TRUE)
</code>```

Now I am able to generate regression lines and r^2 values for each group, but they are in the same place, how should I format the place of showing these equations?

My current plot

Really appreciate any help!!!!

答:
You can use the ggpmisc package.

```<code>library(ggpmisc)
ggplot(df.frus,aes(x=Frustration,y=Neck,col=Display))+geom_jitter(width=0.5)+
stat_poly_eq(formula = y~x, aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")), parse = TRUE)
</code>```

Body:
I have been searching this for a while but can't get a solution.

This is the data I have
Display     Frustration  Neck Angle
1 Microscope          55 40.77672
2 Microscope          70 53.74905
3 Loupe               10 52.41799
4 Loupe               5  62.36514
5 Video               25 49.83489
6 Video               10 68.19686
my current code

lm_eqn <- function(df){
 m <- lm(Neck ~ Frustration, df);
  eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,
                   list(a = format(coef(m)[1], digits = 2),
                        b = format(coef(m)[2], digits = 2),
                        r2 = format(summary(m)$r.squared, digits = 3)))
  as.character(as.expression(eq));
}
eq <- ddply(df.frus,"Display",lm_eqn)
p<- ggplot(df.frus,aes(x=Frustration,y=Neck,col=Display))+geom_jitter(width=0.5)+geom_smooth(method="lm",se=FALSE)
p+geom_text(data=eq,aes(x = 30, y = 80,label=V1), parse = TRUE)

Now I am able to generate regression lines and r^2 values for each group, but they are in the same place, how should I format the place of showing these equations?

My current plot

Really appreciate any help!!!!

Body:
You can use the ggpmisc package.

library(ggpmisc)
ggplot(df.frus,aes(x=Frustration,y=Neck,col=Display))+geom_jitter(width=0.5)+
stat_poly_eq(formula = y~x, aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")), parse = TRUE)


问:
Using R + For Loops to Create Variables
Supposed that I have the following data:

```<code>a1 <- 1
a2 <- 2
a3 <- 3
</code>```

In my actual data, I have way more variable and what I am aiming to do is create interaction variables between them and then put them into one big dataframe like this:

```<code>a1a1 <- a1*a1
a1a2 <- a1*a2
a1a3 <- a1*a3

a2a2 <- a2*a1
a2a3 <- a2*a2

a3a3 <- a3*a3

mydf <- data.frame(a1a1,a1a2,...)
</code>```

I am certain I could use a forloop to accomplish what I want but I am horribly new to R and coding methodology altogether. My intuition tells me to do something along the lines of this:

```<code> n <- 3
 j <- 3

 for( i in 1:n) {
    k <- 1
    for( j in 1:k) {

 aiaj <- ai*aj
 #Not sure how to put into a data.frame for each variable
 k <- k + 1
 }
 }
</code>```

The way the loop is constructed, I believe it would make the variables a1a1,a1a2,a1a3 on the first iteration, on the second iteration it would make a2a2,a2a3, and then on the third iteration a3a3. I've tried this, and it doesn't work so I am hoping I can get some suggestions. Additionally, I have no idea how I would keep adding to the data.frame

答:
This will store all interactions in a data.frame that can filtered or additional functions used as desired</p>

```<code>a <- c(a1, a2, a3)
df1 <- expand.grid(a, a)
df1$prod <- df1[, 1] * df1[, 2]

> df1
  Var1 Var2 prod
1    1    1    1
2    2    1    2
3    3    1    3
4    1    2    2
5    2    2    4
6    3    2    6
7    1    3    3
8    2    3    6
9    3    3    9
</code>```

Title: Using R + For Loops to Create Variables

Body:
Supposed that I have the following data:

a1 <- 1
a2 <- 2
a3 <- 3

In my actual data, I have way more variable and what I am aiming to do is create interaction variables between them and then put them into one big dataframe like this:

a1a1 <- a1*a1
a1a2 <- a1*a2
a1a3 <- a1*a3

a2a2 <- a2*a1
a2a3 <- a2*a2

a3a3 <- a3*a3

mydf <- data.frame(a1a1,a1a2,...)

I am certain I could use a forloop to accomplish what I want but I am horribly new to R and coding methodology altogether. My intuition tells me to do something along the lines of this:

 n <- 3
 j <- 3

 for( i in 1:n) {
    k <- 1
    for( j in 1:k) {

 aiaj <- ai*aj
 #Not sure how to put into a data.frame for each variable
 k <- k + 1
 }
 }

The way the loop is constructed, I believe it would make the variables a1a1,a1a2,a1a3 on the first iteration, on the second iteration it would make a2a2,a2a3, and then on the third iteration a3a3. I've tried this, and it doesn't work so I am hoping I can get some suggestions. Additionally, I have no idea how I would keep adding to the data.frame

Body:
This will store all interactions in a data.frame that can filtered or additional functions used as desired

a <- c(a1, a2, a3)
df1 <- expand.grid(a, a)
df1$prod <- df1[, 1] * df1[, 2]

> df1
  Var1 Var2 prod
1    1    1    1
2    2    1    2
3    3    1    3
4    1    2    2
5    2    2    4
6    3    2    6
7    1    3    3
8    2    3    6
9    3    3    9


问:
Sorting on has many association
I'm building a hotel app and I'll like to sort all hotels by the price of it's cheapest room but I can't seem to achieve my goal.

Roomtype Model>>

```<code>class Roomtype < ActiveRecord::Base
  mount_uploader :image, RimageUploader
  belongs_to :hotel
  has_many :order_items
  default_scope { order(:price => :desc)}
end
</code>```

Hotel Model>>

```<code>class Hotel < ActiveRecord::Base
  has_many :roomtypes, -> { order(:price => :desc) }
  has_many :hotel_images
  belongs_to :destination
  belongs_to :area
  accepts_nested_attributes_for :hotel_images

  def price
    price = self.roomtypes.last.price
  end

end
</code>```

I need a default_scope for the hotels to sort by Hotel.find(params[:id]).roomtypes.last.price

答:
```<code>  class Roomtype < ActiveRecord::Base
      mount_uploader :image, RimageUploader
      belongs_to :hotel
      has_many :order_items
      default_scope { order(:price => :desc)}
    end
</code>```

I think the default_scope order should be ascending, since you want the prices to to be sorted from small to large.

```<code>default_scope { order(:price => :asc)}
</code>```

Then Hotel.first.room_types should give you the result you wanted.

Title: Sorting on has many association

Body:
I'm building a hotel app and I'll like to sort all hotels by the price of it's cheapest room but I can't seem to achieve my goal.

Roomtype Model>>

class Roomtype < ActiveRecord::Base
  mount_uploader :image, RimageUploader
  belongs_to :hotel
  has_many :order_items
  default_scope { order(:price => :desc)}
end

Hotel Model>>

class Hotel < ActiveRecord::Base
  has_many :roomtypes, -> { order(:price => :desc) }
  has_many :hotel_images
  belongs_to :destination
  belongs_to :area
  accepts_nested_attributes_for :hotel_images

  def price
    price = self.roomtypes.last.price
  end

end

I need a default_scope for the hotels to sort by Hotel.find(params[:id]).roomtypes.last.price

Body:
  class Roomtype < ActiveRecord::Base
      mount_uploader :image, RimageUploader
      belongs_to :hotel
      has_many :order_items
      default_scope { order(:price => :desc)}
    end

I think the default_scope order should be ascending, since you want the prices to to be sorted from small to large.

default_scope { order(:price => :asc)}

Then Hotel.first.room_types should give you the result you wanted.


问:
Interval censored data: Cox proportional hazard and surival difference in R
there is quite a lot of information (internet and textbooks) on how to do survival analysis in R with the survival package. But I don't find any information on how to do this when you have left censored data.

Problem background:

I have a self constructed data set with published survival data. Usually the event time and the date of the last follow-up (right censoring) is given. There is however one study that only states that the event happened before day 360. So I left censored this data.

What I want to do:

I want to analyse the complete data set with left truncation, events, and right truncation. I want to plot the Kaplan-Meier curve by gender and then

do a log-rank test

do a Cox regression

What I need:

I am able to create a Surv object with type = interval2. But this does neither allow to calculate survdiff, nor coxph of the survival package.

The intcox package was removed from CRAN and I don't find what I search in the icenReg or interval packages.

Can anyone please give me a hind how to solve my problem or where to find practical information on this? I am already spending days on this one.

Many thanks!

答:
You can fit a Cox-PH model with both right and left censoring in icenReg by using the ic_sp function. You can fit this using the standard Surv response variable, i.e.

```<code>fit <- ic_sp(Surv(L, R, type = 'interval2') ~ treatment, data = myData)
</code>```

or a little more succinctly with

```<code>fit <- ic_sp(cbind(L, R) ~ treatment, data = myData)
</code>```

Log-rank tests are not available in icenReg, but can be found in the interval package.

Body:
You can fit a Cox-PH model with both right and left censoring in icenReg by using the ic_sp function. You can fit this using the standard Surv response variable, i.e.

fit <- ic_sp(Surv(L, R, type = 'interval2') ~ treatment, data = myData)

or a little more succinctly with

fit <- ic_sp(cbind(L, R) ~ treatment, data = myData)

Log-rank tests are not available in icenReg, but can be found in the interval package.


问:
Why did my SQL Server database fill up so fast, and how can I get back my space?
Have a SQL Server environment in which we are using Microsoft SQL Server Management Studio to perform data analysis. The server capacity is 50GB and we loaded in about 8GB worth of '.csv' datasets using the Import Wizard. The 8GB worth of '.csv' files are no longer stored on the server environment.

However, after a few days of querying and creating three new tables, the full 50GB is taken up.

I tried to delete all interim tables, restart the server multiple times, turn off backup, and limit log autogrowth--all to no avail.

How can I get back my storage space? Or at least figure out what is using it all up?

答:
The 8GB worth of '.csv' files...

However, after a few days of querying and creating three new tables, the full 50GB is taken up.

If you're using nvarchar instead of varchar then you're using UCS-2 to store textual data, so your 8GB of data becomes 16GB right there (I wish SQL Server natively supported UTF-8...), then with 3 tables that's 48GB right there - not to mention space used by transaction logs.

When you create a table, then fill it, then delete it, then create a new table, the previously-occupied space is not necessarily reclaimed or overwritten by the new table - this is what probably what's happening. "Normal" tables are expensive in relational database servers - that's why in-memory tables and temporary-tables should be used for ephemeral data (as I believe, though I don't have a reference, that temporary-tables have different storage behavior, and their disk space is more aggressively reclaimed compared to normal tables).

Note that you should use BULK INSERT or at least INSERT INTO ... SELECT FROM instead of repeating a single INSERT INTO ... VALUES... statement because that will hit your transaction log pretty hard (though I'll concedede that BULK INSERT in SQL Server does not offer much flexibility when processing CSV files)


问:
Creating a column variable taking the mean of a variable conditional on two other variables
I have a data frame that shows the mean 'dwdime' for each of the given conditions:

```<code>DIMExCand_means = DIMExCand.groupby(['cycle', 'coded_state', 'party.orig', 'comtype']).mean()
</code>```

I have created a pivot table from DIMExCand_means with the following command and output:

```<code>DIMExCand_master = pd.pivot_table(DIMExCand_means,index=["Cycle","State"])
</code>```

However, some data gets lost in the process. I would like to add columns to the 'DIMExCand_master' dataframe that includes the mean 'dwdime' score given each possible combination of 'party.orig' and 'comptype', as this will allow me to have one entry per 'cycle'-'coded_state'.

答:
Let's try:</p>

```<code>DIMExCand_means = DIMExCand_means.reset_index()
DIMExCand_master = DIMExCand_master.reset_index()

pd.merge(DIMExCand_means, DIMExCand_master, left_on=['cycle','coded_state'], right_on=['Cycle','State'])
</code>```

Body:
I have a data frame that shows the mean 'dwdime' for each of the given conditions:

DIMExCand_means = DIMExCand.groupby(['cycle', 'coded_state', 'party.orig', 'comtype']).mean()

I have created a pivot table from DIMExCand_means with the following command and output:

DIMExCand_master = pd.pivot_table(DIMExCand_means,index=["Cycle","State"])

However, some data gets lost in the process. I would like to add columns to the 'DIMExCand_master' dataframe that includes the mean 'dwdime' score given each possible combination of 'party.orig' and 'comptype', as this will allow me to have one entry per 'cycle'-'coded_state'.

Body:
Let's try:

DIMExCand_means = DIMExCand_means.reset_index()
DIMExCand_master = DIMExCand_master.reset_index()

pd.merge(DIMExCand_means, DIMExCand_master, left_on=['cycle','coded_state'], right_on=['Cycle','State'])