2014年05月

Getting the number of seconds since the Epoch from a string in any time zone

I need to calculate the number of seconds since the epoch from a well-formed string, such as u'Wed Jun 24 20:19:10 PDT 2015'. The following code does that:



def seconds_from_epoch(date, date_pattern='%a %b %d %H:%M:%S %Z %Y'):
epoch = int(time.mktime(time.strptime(date, date_pattern)))
return epoch

>>> d=u'Wed Jun 24 20:19:10 PDT 2015'
>>> s=seconds_from_epoch(d)
>>> s
1435202350


The problem is that the strings come from an unpredictable variety of time zones, and the solution above only works if the timezone is the same as that of the running Python script itself (or apparently GMT/UTC, which does not help).



So what I need is something that does exactly the same as the code above, but for all time zones.



Answers

See Python strptime() and timezones? particularly answer of Joe Shaw,



I would use https://dateutil.readthedocs.org/en/latest/ , dateutil library already takes care of timezones. The reason why you won't get timezoned date from strptime is that it does not support timezones.




A naive object does not contain enough information to unambiguously locate itself relative to other date/time objects. Whether a naive object represents Coordinated Universal Time (UTC), local time, or time in some other timezone is purely up to the program, just like it’s up to the program whether a particular number represents metres, miles, or mass. Naive objects are easy to understand and to work with, at the cost of ignoring some aspects of reality.




see https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime



Answers

def total_seconds(dt): #just in case you are using a python that the datetime library does not provide this automagically
print dt.days*24*60+dt.seconds

from dateutil.parser import parse as date_parse

print total_seconds(date_parse(date_string))


you will need to
pip install python-dateutil



Answers

The dateutil parser can convert almost any string to a datetime object, so you can even loosen the well-formed constraint; but anyway, datetime objects in Python 3 have the convenient timestamp method:



>>> d = dateutil.parser.parse('Wed Jun 24 20:19:10 PDT 2015')
>>> d.timestamp()
1435166350.0
>>> d = dateutil.parser.parse('Wed Jun 24 20:19:10 UTC 2015')
>>> d.timestamp()
1435177150.0


Since you're probably using Python 2, here's a manual calculation:



>>> d = dateutil.parser.parse('Wed Jun 24 20:19:10 PDT 2015')
>>> (d - datetime.datetime(1970, 1, 1)).total_seconds()
Traceback (most recent call last):
...
TypeError: cant subtract offset-naive and offset-aware datetimes
>>> # :(
>>> (d - datetime.datetime(1970, 1, 1, tzinfo=d.tzinfo)).total_seconds()
1435177150.0 # UTC
>>> ((d - datetime.datetime(1970, 1, 1, tzinfo=d.tzinfo)) - d.utcoffset()).total_seconds()
1435166350.0 # The original timezone




json parse from result.php file url

i have a php file that return json. here my php file.



http://dev.mediaodd.com/data/testjson.php



if i use writing testjson.json file it will success but if i use .php it will failed.



this is my output script:



<?php
// copy file content into a string var

$jsondata = file_get_contents('http://dev.mediaodd.com/data/testjson.php');
$obj = json_decode($jsondata,true);


echo $obj['company'][0]['id'];

?>


what did i do wrong?



file_get_contents cant read .php file?



my testjson.php file return same as testjason.json file.



Answers

after clarification by OP, the following is not the case



file_get_contents cannot read from url resource unless this has been setup explicitly in php.ini configuration (not recommended mostly for security reasons).



So you should not use file_get_contents('http://dev.mediaodd.com/data/testjson.php'); to read an http resource, but instead read from local php files only that exist in the (server) disk





Eclipse can't be opened Mac UI5

So I am trying to develop using UI5 and I can not seem to open Eclipse. Every time I open the program it says the following: "The Application 'eclipse' can't be opened". Does anyone have a solution. I downloaded a version that already has an IDE built in. Is that a possible issue?



Answers

Problem open Eclipse - Did you instal correct on your MAC

I had no problems installing the Keppler version : look at
http://www.eclipse.org/downloads/
-> go to Kepler
Look for Eclipse IDE for Java EE Developers (MAC 64 Bit), this will
download the file eclipse-jee-kepler-SR2-macosx-cocoa-x86_64.tar.gz !
Just open (unpack) it, it will create an entry: Eclipse.app.





Afterwards, when done, open Eclipse and install the
"SAP UI5 – Development Toolkit" in Eclipse through:
Help/Install new software/ open site -> https://tools/hana.ondemand.com/kepler



Best Luck, Markus





How to create generic convenience initializer in Swift?

I'm tackling with generics in Swift. I've got extension to NSManagedObject class and wanted to create initializer which is only available for classes which implements some protocol I defined. Now I've got something like below but this is not working and even not compiling. Could you help me make it working?



public extension NSManagedObject {
public convenience init<Self: Nameable>(context: NSManagedObjectContext) {
let entity = NSEntityDescription.entityForName(Self.entityName(), inManagedObjectContext: context)!
self.init(entity: entity, insertIntoManagedObjectContext: context)
}
}

public protocol Nameable {
static func entityName() -> String
}


Xcode says: "Generic parameter 'Self' is not used in function signature".



Answers

As matt already explained, you cannot define an initializer which
is restricted to types implementing a protocol. Alternatively, you
could define a global function instead:



public protocol Nameable {
static func entityName() -> String
}

func createInstance<T : NSManagedObject where T: Nameable>(type : T.Type, context : NSManagedObjectContext) -> T {
let entity = NSEntityDescription.entityForName(T.entityName(), inManagedObjectContext: context)!
return T(entity: entity, insertIntoManagedObjectContext: context)
}


which is then used as



let obj = createInstance(Entity.self, context)


You can avoid the additional type parameter if you define the method
as



func createInstance<T : NSManagedObject where T: Nameable>(context : NSManagedObjectContext) -> T { ... }


and use it as



let obj : Entity = createInstance(context)


or



let obj = createInstance(context) as Entity


where the type is now inferred from the context.



Answers

It seems to me that you are describing something like this:



class Thing {}

func makeANewThing<T:ThingMaker>(caller:T) -> Thing {
let t = Thing()
return t
}

protocol ThingMaker {
}

class Dog : ThingMaker {
}

class Cat { // not a ThingMaker
}

let t = makeANewThing(Dog()) // ok
let t2 = makeANewThing(Cat()) // illegal


In real life, I presume that makeANewThing would actually do something with its caller, but the point is that it can only be called by passing a caller that has adopted ThingMaker.



That is probably the best you can do in Swift 1. If you want to inject a method into only classes that adopt a certain protocol, then what you want is a protocol extension — but that is available only in Swift 2.



Answers

Okay, thanks for your comments on this thread. I realized with @matt comments that I cannot do what I thought because it is even not possible. I wanted to not create subclass to make it working and it was not possible with my understanding of the problem.



Finally I found another way to get entity name. It has pros and cons but I decided to use it for now. Then I created extension for NSManagedObject to make it work.



extension NSManagedObject {

class func entityName() -> String {
let fullClassName = NSStringFromClass(object_getClass(self))
let nameComponents = split(fullClassName) { $0 == "." }
return last(nameComponents)!
}

public convenience init(context: NSManagedObjectContext) {
let name = self.dynamicType.entityName()
let entity = NSEntityDescription.entityForName(name, inManagedObjectContext: context)!
self.init(entity: entity, insertIntoManagedObjectContext: context)
}
}


And then



obj = Obj(context: ctx)




Android - Make whole search bar clickable

I am using a search-view element in my fragment to implement search feature.



<SearchView
android:id="@+id/search_bar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="7dp"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
android:layout_marginBottom="7dp"
android:background="@color/white" />




The problem is only the search icon is clickable other area in the search bar is not clickable, when i click the icon only i can able to search.





Can you please help me to make the whole search area clickable.





Answers

What is the clickable mean? trigger search action or just make the edit area focused? If it is the first, you can just make the icon clickable=false. and make the whole layout clickable and implement a event listener.



<SearchView
android:id="@+id/search_bar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:click="onClick"
android:layout_marginTop="7dp"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
android:layout_marginBottom="7dp"
android:background="@color/white" />


The onClick method should be



public void onClick(View v) {
  InputMethodManager im = ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE));
im.showSoftInput(editText, 0);



Answers

add this to your xml android:iconifiedByDefault="false" it will keep
open your searchview.



and to clear it add clearfocus to your searchview object.





↑このページのトップヘ