问:
In android studio using sqlite. How can I create views?
How can I create views using columns in other tables in android studio sqlite ? </p>

答:
Use SQLite Database Helper class

```<code>public class SQLiteHandler extends SQLiteOpenHelper {

private static final String TAG = SQLiteHandler.class.getSimpleName();

private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "android_api";

// Login table name
private static final String TABLE_USER = "user";

// Login Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_EMAIL = "email";
private static final String KEY_UID = "uid";
private static final String KEY_CREATED_AT = "created_at";

public SQLiteHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_USER + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
            + KEY_EMAIL + " TEXT UNIQUE," + KEY_UID + " TEXT,"
            + KEY_CREATED_AT + " TEXT" + ")";
    db.execSQL(CREATE_LOGIN_TABLE);

    Log.d(TAG, "Database tables created");
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER);

    // Create tables again
    onCreate(db);
}
</code>```

}

Body:
Use SQLite Database Helper class

public class SQLiteHandler extends SQLiteOpenHelper {

private static final String TAG = SQLiteHandler.class.getSimpleName();

private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "android_api";

// Login table name
private static final String TABLE_USER = "user";

// Login Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_EMAIL = "email";
private static final String KEY_UID = "uid";
private static final String KEY_CREATED_AT = "created_at";

public SQLiteHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_USER + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
            + KEY_EMAIL + " TEXT UNIQUE," + KEY_UID + " TEXT,"
            + KEY_CREATED_AT + " TEXT" + ")";
    db.execSQL(CREATE_LOGIN_TABLE);

    Log.d(TAG, "Database tables created");
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER);

    // Create tables again
    onCreate(db);
}

}


来源: stackexchange

问:
Django search in multiple field with multiple value
I have a model which stores login logout time and date for users

```<code>class LoginLogout(models.Model):
    username = models.CharField(max_length=30, unique=True)
    date = models.DateField(auto_now_add=True)
    login_time = models.TimeField()
    logout_time = models.TimeField(null=True, blank=True)
</code>```

Now I need to search in this model by the field date and username. I have a form which takes date_from, date_to and username as input. Any field can be blank. If username is blank all results will be returned. Now what will be the queryset for achieving the desired queryset.

答:
I need to search in this model by the field date and username. I have a form which takes date_from, date_to and username as input.

You want to learn about Django's query expressions.

events = LoginLogout.objects.filter(
        username=username,
        date__ge=date_from,
        date__le=date_to,
)
```

<blockquote>
  <p>Any field can be blank. If username is blank all results will be returned.</p>
</blockquote>

<p>Those are special conditions, and should be represented as such in your code.</p>

<pre class="lang-python prettyprint-override"><code>filter_args = {}
if username:
    filter_args['username'] = username
    if date_from:
        filter_args['date__ge'] = date_from
    if date_to:
        filter_args['date__le'] = date_to
events = LoginLogout.objects.filter(**filter_args)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a model which stores login logout time and date for users

class LoginLogout(models.Model):
    username = models.CharField(max_length=30, unique=True)
    date = models.DateField(auto_now_add=True)
    login_time = models.TimeField()
    logout_time = models.TimeField(null=True, blank=True)

Now I need to search in this model by the field date and username. I have a form which takes date_from, date_to and username as input. Any field can be blank. If username is blank all results will be returned. Now what will be the queryset for achieving the desired queryset.

Body:
I need to search in this model by the field date and username. I have a form which takes date_from, date_to and username as input.

You want to learn about Django's query expressions.

events = LoginLogout.objects.filter(
        username=username,
        date__ge=date_from,
        date__le=date_to,
)

Any field can be blank. If username is blank all results will be returned.

Those are special conditions, and should be represented as such in your code.

filter_args = {}
if username:
    filter_args['username'] = username
    if date_from:
        filter_args['date__ge'] = date_from
    if date_to:
        filter_args['date__le'] = date_to
events = LoginLogout.objects.filter(**filter_args)


问:
Prevent second fancybox from open when another fancybox instance is already open
On my site, i have a two fancybox instance

open youtube video when someone clicks on div

open newsletter popup after 25 seconds when someone visit site.

The problem is when someone clicks on div and start watching the video and if 25 seconds pass in meantime, it will open newsletter popup and close the already open video popup. This will create bad experience for site users can anyone having solutions?

Below is the code for both fancybox instance

video popup jquery

```<code>jQuery("#yblock").click(function() {
jQuery.fancybox({
        'padding'       : 0,
        'aspectRatio'         : true,
        'transitionIn'  : 'none',
        'transitionOut' : 'none',
        'title'         : this.title,
        'width'     : 780,
        'height'        : 500,
        'href'          : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
        'type'          : 'swf',
        'swf'                   : {
             'wmode'        : 'transparent',
            'allowfullscreen'   : 'true'
        },
        helpers                  : {
            'overlay': {
            'locked': false
                       }
        }
</code>```

Newsletter popup jquery

```<code>jQuery(function ($) {
setTimeout(function () {
                beginNewsletterForm();
            }, 25000);
});

function beginNewsletterForm() {
    jQuery.fancybox({
        'padding': '0px',
        'autoScale': true,
        'transitionIn': 'fade',
        'transitionOut': 'fade',
        'type': 'inline',
        'href': '#newsletter_popup',
        'onComplete': function () {
            $.cookie('newsletter_popup', 'shown');
        },
        'tpl': {
            closeBtn: '<a title="Close" class="fancybox-item fancybox-close fancybox-newsletter-close" href="javascript:;"></a>'
        },
        'helpers': {
            overlay: {
                locked: true
            }
        }
    });
    jQuery('#newsletter_popup').trigger('click');
}
</code>```

I want to prevent second fancybox to open if first fancybox is already open

答: sorry for my english before. For open 2 modal at once using the same plugin (fancybox) may cause conflict in action. you can try open the video box with fancybox and open the newsletter box with bootstrap modal or another plugin. may this help. thanks</p>

Body:
On my site, i have a two fancybox instance

open youtube video when someone clicks on div

open newsletter popup after 25 seconds when someone visit site.

The problem is when someone clicks on div and start watching the video and if 25 seconds pass in meantime, it will open newsletter popup and close the already open video popup. This will create bad experience for site users can anyone having solutions?

Below is the code for both fancybox instance

video popup jquery

jQuery("#yblock").click(function() {
jQuery.fancybox({
        'padding'       : 0,
        'aspectRatio'         : true,
        'transitionIn'  : 'none',
        'transitionOut' : 'none',
        'title'         : this.title,
        'width'     : 780,
        'height'        : 500,
        'href'          : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
        'type'          : 'swf',
        'swf'                   : {
             'wmode'        : 'transparent',
            'allowfullscreen'   : 'true'
        },
        helpers                  : {
            'overlay': {
            'locked': false
                       }
        }

Newsletter popup jquery

jQuery(function ($) {
setTimeout(function () {
                beginNewsletterForm();
            }, 25000);
});

function beginNewsletterForm() {
    jQuery.fancybox({
        'padding': '0px',
        'autoScale': true,
        'transitionIn': 'fade',
        'transitionOut': 'fade',
        'type': 'inline',
        'href': '#newsletter_popup',
        'onComplete': function () {
            $.cookie('newsletter_popup', 'shown');
        },
        'tpl': {
            closeBtn: ''
        },
        'helpers': {
            overlay: {
                locked: true
            }
        }
    });
    jQuery('#newsletter_popup').trigger('click');
}

I want to prevent second fancybox to open if first fancybox is already open


问:
SSH Key authorization for user
Scenario :
There are multiple users who need SSH into a server. What I'm following is

Create user1 , user2 in the server (Ubuntu 14.04 Server) running in AWS EC2.

Add each user public key (id_rsa.pub) into server /home/$USER/.ssh/authorized_keys file

Problem is I only can SSH to ubuntu (Default user)  with the private key of the user. But I can not SSH into user1 user.

Sample

```<code>[root@rubi-pc Downloads]# ssh -i ~/.ssh/id_rsa ruwan@DummyIP -v
OpenSSH_7.5p1, OpenSSL 1.1.0e  16 Feb 2017
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Connecting to DummyIP [DummyIP] port 22.
debug1: Connection established.
debug1: permanently_set_uid: 0/0
debug1: identity file /root/.ssh/id_rsa type 1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_rsa-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.5
debug1: Remote protocol version 2.0, remote software version OpenSSH_6.6.1p1 Ubuntu-2ubuntu2.8
debug1: match: OpenSSH_6.6.1p1 Ubuntu-2ubuntu2.8 pat OpenSSH_6.6.1* compat 0x04000000
debug1: Authenticating to DummyIP:22 as 'ruwan'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: algorithm: curve25519-sha256@libssh.org
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:0kqNAt37ILO4cCP8ioiLN9j9x9badLOGL+etIvSYzfs
debug1: Host 'DummyIP' is known and matches the ECDSA host key.
debug1: Found key in /root/.ssh/known_hosts:2
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /root/.ssh/id_rsa
debug1: Authentications that can continue: publickey
debug1: No more authentication methods to try.
Permission denied (publickey).
</code>```

Please do let me know if any details requeired .

答:
Problem Occurred because of .ssh/authorized_keys not chowned to $USER and groups.
also chmod <code>-rw-rw-r-- ( 664 )</code> . </p>

Title: SSH Key authorization for user

Body:
Scenario :
There are multiple users who need SSH into a server. What I'm following is

Create user1 , user2 in the server (Ubuntu 14.04 Server) running in AWS EC2.

Add each user public key (id_rsa.pub) into server /home/$USER/.ssh/authorized_keys file

Problem is I only can SSH to ubuntu (Default user)  with the private key of the user. But I can not SSH into user1 user.

Sample

[root@rubi-pc Downloads]# ssh -i ~/.ssh/id_rsa ruwan@DummyIP -v
OpenSSH_7.5p1, OpenSSL 1.1.0e  16 Feb 2017
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Connecting to DummyIP [DummyIP] port 22.
debug1: Connection established.
debug1: permanently_set_uid: 0/0
debug1: identity file /root/.ssh/id_rsa type 1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_rsa-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.5
debug1: Remote protocol version 2.0, remote software version OpenSSH_6.6.1p1 Ubuntu-2ubuntu2.8
debug1: match: OpenSSH_6.6.1p1 Ubuntu-2ubuntu2.8 pat OpenSSH_6.6.1* compat 0x04000000
debug1: Authenticating to DummyIP:22 as 'ruwan'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: algorithm: curve25519-sha256@libssh.org
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:0kqNAt37ILO4cCP8ioiLN9j9x9badLOGL+etIvSYzfs
debug1: Host 'DummyIP' is known and matches the ECDSA host key.
debug1: Found key in /root/.ssh/known_hosts:2
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /root/.ssh/id_rsa
debug1: Authentications that can continue: publickey
debug1: No more authentication methods to try.
Permission denied (publickey).

Please do let me know if any details requeired .

Body:
Problem Occurred because of .ssh/authorized_keys not chowned to $USER and groups.
also chmod -rw-rw-r-- ( 664 ) .


问:
Addressing instance name string in __init__(self) in Python
I am doing something like this:

```<code>class Class(object):
    def __init__(self):
        self.var=#new instance name string#
</code>```

How do I make the __ init __ method of my instance to use the instance name string for 'c'? Say in case:

```<code>c=Class()
</code>```

I want c.var equal to 'c'.

Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:

```<code>c=Class()
</code>```

Then, suppose:

```<code>del c
</code>```

Later on:

```<code>c=Class()
</code>```

sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.

Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:

```<code>c=Class()
</code>```

Then, suppose:

```<code>del c
</code>```

Later on:

```<code>c=Class()
</code>```

sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.

答:
I am unaware of a way to access a variable's name programmatically without using deep reflection and a debugger.  I do not think the information is available at runtime.

If you want to give instances a (unique?) name, you should probably make the initializer accept an extra argument.

```<code>def __init__(self, name):
    self.name = name
</code>```

And the caller should pass in the appropriate name:

```<code>c = Class("c")
</code>```

OwnerDisplayName: xktybot

Body:
I am doing something like this:

class Class(object):
    def __init__(self):
        self.var=#new instance name string#

How do I make the __ init __ method of my instance to use the instance name string for 'c'? Say in case:

c=Class()

I want c.var equal to 'c'.

Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:

c=Class()

Then, suppose:

del c

Later on:

c=Class()

sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.

Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:

c=Class()

Then, suppose:

del c

Later on:

c=Class()

sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.

LastEditorDisplayName: xktybot

Body:
I am unaware of a way to access a variable's name programmatically without using deep reflection and a debugger.  I do not think the information is available at runtime.

If you want to give instances a (unique?) name, you should probably make the initializer accept an extra argument.

def __init__(self, name):
    self.name = name

And the caller should pass in the appropriate name:

c = Class("c")

OwnerDisplayName: Brett Daniel

ContentLicense: CC BY-SA 2.5


问:
Calling a function overloaded in several namespaces from inside one namespace
I have the following code snippet:

```<code>void foo(double a) {}

namespace bar_space
{
  struct Bar {};

  void foo(Bar a) {}
}
</code>```

foo(double) is a general function from a library.
I have my own namespace bar_space with my own struct, Bar. I would like to implement an overloading of foo() for Bar, thus making Bar more similar to the built-in types.

Trouble appears when I attempt to call the original foo(double) from within the namespace:

```<code>namespace bar_space
{
  void baz()
  {
    foo(5.0); // error: conversion from ‘double’ to non-scalar type ‘ssc::bar_space::Bar’ requested
  }
}
</code>```

This fails to compile on gcc on both my Fedora and Mac.

Calling

```<code>foo(5.0)
</code>```

from outside the namespace or using

```<code>namespace bar_space
{
  ::foo(5.0)
}
</code>```

works ok, but this doesnt make my new function quite as nice as I had hoped for (other developers are also working inside bar_space).

Is bar_space hiding the original function? Is there a way to make foo(5.0) callable from within bar_space without explicit scoping (::)? Any help is appreciated.

答: Yes, bar_space is hiding the original function and no, you can't make foo(5.0) callable from whithin bar_space without explicit scoping if foo(double) is defined in the global namespace.

Body:
I have the following code snippet:

void foo(double a) {}

namespace bar_space
{
  struct Bar {};

  void foo(Bar a) {}
}

foo(double) is a general function from a library.
I have my own namespace bar_space with my own struct, Bar. I would like to implement an overloading of foo() for Bar, thus making Bar more similar to the built-in types.

Trouble appears when I attempt to call the original foo(double) from within the namespace:

namespace bar_space
{
  void baz()
  {
    foo(5.0); // error: conversion from ‘double’ to non-scalar type ‘ssc::bar_space::Bar’ requested
  }
}

This fails to compile on gcc on both my Fedora and Mac.

Calling

foo(5.0)

from outside the namespace or using

namespace bar_space
{
  ::foo(5.0)
}

works ok, but this doesnt make my new function quite as nice as I had hoped for (other developers are also working inside bar_space).

Is bar_space hiding the original function? Is there a way to make foo(5.0) callable from within bar_space without explicit scoping (::)? Any help is appreciated.


问:
How change iOS TableView index Color?

How do I customise the Color and Font of the right side list.

答:
Simply you can access sectionIndexColor method of UITableView

```<code>yourTableviewName.sectionIndexColor = UIColor.yourDesiredColor
yourTableviewName.sectionIndexColor = UIColor.red // as Example i have used red color
</code>```

Title: How change iOS TableView index Color?

Body:
Simply you can access sectionIndexColor method of UITableView

yourTableviewName.sectionIndexColor = UIColor.yourDesiredColor
yourTableviewName.sectionIndexColor = UIColor.red // as Example i have used red color


问:
How to avoid N+1 queries with Spring Data REST Projections?
I have been prototyping my new application in Spring Data REST backed by Spring Data JPA & Hibernate, which has been a fantastic productivity booster for my team, but as the data model becomes more complex the performance is going down the tubes. Looking at the executed SQL, I see two separate but related problems:

When using a Projection with only a few properties to reduce the size of my payload, SDR is still loading the entire entity graph, with all the overhead that incurs. EDIT: filed DATAREST-1089

There seems to be no way to specify eager loading using JPA, as SDR auto-generates the repository methods so I can't add @EntityGraph to them. (and per DATAREST-905 below, even that doesn't work) EDIT: addressed in Cepr0's answer below, though this can only be applied to each finder method once. See DATAJPA-749

I have one key model that I use several different projections of depending on the context (list page, view page, autocomplete, related item page, etc), so implementing one custom ResourceProcessor doesn't seem like a solution.)

Has anyone found a way around these problems? Otherwise anyone with a non-trivial object graph will see performance deteriorate drastically as their model grows.

My research:

How do I avoid n+1 queries with Spring Data Rest? (from 2013)

https://jira.spring.io/browse/DATAJPA-466
(
Add support for lazy loading configuration via JPA 2.1 fetch-/loadgraph.)

https://jira.spring.io/browse/DATAREST-905 (
No way to avoid loading all child relations in spring-data-rest?) (2016, unanswered)

答:
To fight with 1+N issue I use the following two approaches:

@EntityGraph

I use '@EntityGraph' annotation in Repository for findAll method. Just override it:

@Override
@EntityGraph(attributePaths = {"author", "publisher"})
Page<Book> findAll(Pageable pageable);
```

<p>This approach is suitable for all "reading" methods of Repository.</p>

<p><strong>Cache</strong></p>

<p>I use <strong>cache</strong> to reduce the impact of 1+N issue for complex Projections. </p>

<p>Suppose we have <strong>Book</strong> entity to store the book data and <strong>Reading</strong> entity to store the information about the number of readings of a specific Book and its reader rating. To get this data we can make a Projection like this:</p>

<pre class="lang-java prettyprint-override"><code>@Projection(name = "bookRating", types = Book.class)
public interface WithRatings {

    String getTitle();
    String getIsbn();

    @Value("#{@readingRepo.getBookRatings(target)}")
    Ratings getRatings();
}
</code>```

Where readingRepo.getBookRatings is the method of ReadingRepository:

@RestResource(exported = false)
@Query("select avg(r.rating) as rating, count(r) as readings from Reading r where r.book = ?1")
Ratings getBookRatings(Book book);
```

<p>It also return a projection that store "rating" info:</p>

<pre class="lang-java prettyprint-override"><code>@JsonSerialize(as = Ratings.class)
public interface Ratings {

    @JsonProperty("rating")
    Float getRating();

    @JsonProperty("readings")
    Integer getReadings();
}
</code>```

The request of /books?projection=bookRating will cause the invocation of readingRepo.getBookRatings for every Book which will lead to redundant N queries.

To reduce the impact of this we can use the cache:

Preparing the cache in the SpringBootApplication class:

@SpringBootApplication
@EnableCaching
public class Application {

    //...

    @Bean
    public CacheManager cacheManager() {

        Cache bookRatings = new ConcurrentMapCache("bookRatings");

        SimpleCacheManager manager = new SimpleCacheManager();
        manager.setCaches(Collections.singletonList(bookRatings));

        return manager;
    }
}
```

<p>Then adding a corresponding annotation to <code>readingRepo.getBookRatings</code> method: </p>

<pre class="lang-java prettyprint-override"><code>@Cacheable(value = "bookRatings", key = "#a0.id")
@RestResource(exported = false)
@Query("select avg(r.rating) as rating, count(r) as readings from Reading r where r.book = ?1")
Ratings getBookRatings(Book book);
</code>```

And implementing the cache eviction when Book data is updated:

@RepositoryEventHandler(Reading.class)
public class ReadingEventHandler {

    private final @NonNull CacheManager cacheManager;

    @HandleAfterCreate
    @HandleAfterSave
    @HandleAfterDelete
    public void evictCaches(Reading reading) {
        Book book = reading.getBook();
        cacheManager.getCache("bookRatings").evict(book.getId());
    }
}
```

Now all subsequent requests of /books?projection=bookRating will get rating data from our cache and will not cause redundant requests to the database.

More info and working example is here.

Body:
To fight with 1+N issue I use the following two approaches:

@EntityGraph

I use '@EntityGraph' annotation in Repository for findAll method. Just override it:

@Override
@EntityGraph(attributePaths = {"author", "publisher"})
Page<Book> findAll(Pageable pageable);

This approach is suitable for all "reading" methods of Repository.

Cache

I use cache to reduce the impact of 1+N issue for complex Projections.

Suppose we have Book entity to store the book data and Reading entity to store the information about the number of readings of a specific Book and its reader rating. To get this data we can make a Projection like this:

@Projection(name = "bookRating", types = Book.class)
public interface WithRatings {

    String getTitle();
    String getIsbn();

    @Value("#{@readingRepo.getBookRatings(target)}")
    Ratings getRatings();
}

Where readingRepo.getBookRatings is the method of ReadingRepository:

@RestResource(exported = false)
@Query("select avg(r.rating) as rating, count(r) as readings from Reading r where r.book = ?1")
Ratings getBookRatings(Book book);

It also return a projection that store "rating" info:

@JsonSerialize(as = Ratings.class)
public interface Ratings {

    @JsonProperty("rating")
    Float getRating();

    @JsonProperty("readings")
    Integer getReadings();
}

The request of /books?projection=bookRating will cause the invocation of readingRepo.getBookRatings for every Book which will lead to redundant N queries.

To reduce the impact of this we can use the cache:

Preparing the cache in the SpringBootApplication class:

@SpringBootApplication
@EnableCaching
public class Application {

    //...

    @Bean
    public CacheManager cacheManager() {

        Cache bookRatings = new ConcurrentMapCache("bookRatings");

        SimpleCacheManager manager = new SimpleCacheManager();
        manager.setCaches(Collections.singletonList(bookRatings));

        return manager;
    }
}

Then adding a corresponding annotation to readingRepo.getBookRatings method:

@Cacheable(value = "bookRatings", key = "#a0.id")
@RestResource(exported = false)
@Query("select avg(r.rating) as rating, count(r) as readings from Reading r where r.book = ?1")
Ratings getBookRatings(Book book);

And implementing the cache eviction when Book data is updated:

@RepositoryEventHandler(Reading.class)
public class ReadingEventHandler {

    private final @NonNull CacheManager cacheManager;

    @HandleAfterCreate
    @HandleAfterSave
    @HandleAfterDelete
    public void evictCaches(Reading reading) {
        Book book = reading.getBook();
        cacheManager.getCache("bookRatings").evict(book.getId());
    }
}

Now all subsequent requests of /books?projection=bookRating will get rating data from our cache and will not cause redundant requests to the database.

More info and working example is here.


问:
How do you perform wireless debugging in Xcode 9 with iOS 11, Apple TV 4K, etc?
Wireless debugging was recently added as a feature in Xcode 9, iOS 11, and tvOS 11. Apple TV 4K doesn't have a USB port, so it requires wireless debugging. How do you perform this wireless debugging in Xcode?</p>

答:
Set up a device for network debugging

from help.apple.com

Debug your app running on an iOS or tvOS device over a Wi-Fi or other network connection.

Steps to set up iPhone, iPad, or iPod touch

Check that your device has a passcode and add one if it doesn't. Your device must have a passcode to enable remote debugging

The Mac and the iPhone/iPad need to be on the same network to use wireless debugging.

Next, in Xcode

Choose Window > Devices and Simulators, then in the window that appears, click Devices.

Connect your device to your Mac with a Lightning cable.

In the left column, select the device, and in the detail area, select Connect via network.

Xcode pairs with your device. If Xcode can connect with the device using a network, a network icon appears next to the device in the left column.

Disconnect your device.

Now you are ready for debugging over the network.

Sometimes it doesn't work. You might need to restart the device or network connection.

Note: Network debugging requires Xcode 9.0 or later running on macOS 10.12.4 or later, and on the device, requires iOS 11.0 or later, or tvOS 11.0 or later.

Steps to set up Apple TV:

Make sure your Mac and your Apple TV are on the same network.

Choose Window > Devices and Simulators, then in the window that appears, click Devices.

On your Apple TV, open the Settings app and choose Remotes and Devices > Remote App and Devices.

The Apple TV searches for possible devices including the Mac. (If you have any firewall or Internet security, disable/turn it off to allow searching.)

On your Mac, select the Apple TV in the Devices pane. The pane for the Apple TV is displayed and shows the current status of the connection request.

Enter the verification code displayed on your AppleTV into the Device window pane for the device and click Connect.

Xcode sets up the Apple TV for wireless debugging and pairs with the device.

ContentLicense: CC BY-SA 4.0


问:
Issue connecting composer to Blockchain on Bluemix - identity or token does not match
I have fabric composer 0.72 installed on my mac, and I was able to follow this thread to get it connected to my Blockchain (v.61 of Fabric) on Bluemix.

fabric-composer-integration-with-bluemix-blockchain-service

Now I am trying to build an ubuntu (16.04) docker container and run composer-rest-server there.  When I try to connect to my blockchain service from my docker container (using the same id, WebAppAdmin, that I used on my mac) I get an error:

```<code>Discovering types from business network definition ...
Connection fails: Error: Identity or token does not match.
It will be retried for the next request.
{ Error: Identity or token does not match.
     at /home/composer/.nvm/versions/node/v6.10.3/lib/node_modules  /composer-rest-server/node_modules/grpc/src/node/src/client.js:417:17 code: 2, metadata: Metadata { _internal_repr: {} } }
</code>```

I tried copying the cert from my mac to my docker container:

```<code>/home/composer/.composer-credentials/member.WebAppAdmin
</code>```

but when I did that I got a different error that says "signature does not verify".  I did some additional testing, and I discovered that if I used an id that I had not previously used with composer (i.e. user_type1_0) then I could connect, and I could see a new cert in my .composer-credentials directory.

I tried deleting that container and building a new one (I dorked something else up) I could not use that same userid again.

Does anybody know how security and these certs are supposed to work?  It would seem as though something to do with certificate generation/validation is tied to the client (i.e. hardware address), such that if I try to re-use an id on a different machine, the certs or keys or something don't match.  I have a way to make things work, but it doesn't seem like it's the right way if I can't use the same id from different machines.

Thanks!

答:
I have also faced this issue, and concluded that

There is inconsistent behavior while deploying network using composer on Cloud environment includeing Bluemix. Problem is not with composer, but with fabric 0.6.

I am assuming that this issue is also indirectly related to following known bugs into fabric 0.6, which will not be fixed in fabric 0.6.

ERROR:

"

throw er; // Unhandled 'error' event
^

Error
at ClientDuplexStream._emitStatusIfDone (/home/ubuntu/.nvm/versions/node/v6.9.5/lib/node_modules/composer-cli/node_modules/grpc/src/node/src/client.js:189:19)
at ClientDuplexStream._readsDone (/home/ubuntu/.nvm/versions/node/v6.9.5/lib/node_modules/composer-cli/node_modules/grpc/src/node/src/client.js:158:8)
at readCallback (/home/ubuntu/.nvm/versions/node/v6.9.5/lib/node_modules/composer-cli/node_modules/grpc/src/node/src/client.js:217:12)

"

So far, We have understood that following three JIRA are root cause , where essentially the cloud networking layer ends up killing the idle event hub connection after a period of inactivity and the fabric SDK cannot handle this.

https://jira.hyperledger.org/browse/FAB-4002 FAB-3310

https://jira.hyperledger.org/browse/FAB-3310

or FAB-2787

Conclusion:

There is no alternative way of fixing this issue with Bluemix or any cloud environment with fabric 0.6

You may not experience this issue with Fabric 1.0, but there is still possibilities as all above mentioned defects are not fixed yet.

Body:
I have fabric composer 0.72 installed on my mac, and I was able to follow this thread to get it connected to my Blockchain (v.61 of Fabric) on Bluemix.

fabric-composer-integration-with-bluemix-blockchain-service

Now I am trying to build an ubuntu (16.04) docker container and run composer-rest-server there.  When I try to connect to my blockchain service from my docker container (using the same id, WebAppAdmin, that I used on my mac) I get an error:

Discovering types from business network definition ...
Connection fails: Error: Identity or token does not match.
It will be retried for the next request.
{ Error: Identity or token does not match.
     at /home/composer/.nvm/versions/node/v6.10.3/lib/node_modules  /composer-rest-server/node_modules/grpc/src/node/src/client.js:417:17 code: 2, metadata: Metadata { _internal_repr: {} } }

I tried copying the cert from my mac to my docker container:

/home/composer/.composer-credentials/member.WebAppAdmin

but when I did that I got a different error that says "signature does not verify".  I did some additional testing, and I discovered that if I used an id that I had not previously used with composer (i.e. user_type1_0) then I could connect, and I could see a new cert in my .composer-credentials directory.

I tried deleting that container and building a new one (I dorked something else up) I could not use that same userid again.

Does anybody know how security and these certs are supposed to work?  It would seem as though something to do with certificate generation/validation is tied to the client (i.e. hardware address), such that if I try to re-use an id on a different machine, the certs or keys or something don't match.  I have a way to make things work, but it doesn't seem like it's the right way if I can't use the same id from different machines.

Thanks!


问:
Render different update action based on params
In my controller I need to call different update.js based of existence of a parameter.
How to do it correctly?

```<code>  respond_to do |format|
    format.js do
      if params[:ble].present?
        'one/update.js'
      else
        'two/update.js'
      end
    end
  end
</code>```

答:
I think you're just forgetting to explicitly call render, but you also need to specify layout: false

```<code>respond_to do |format|
  format.js do
    if params[:ble].present?
      render 'one/update.js', layout: false
    else
      render 'two/update.js', layout: false
    end
  end
end
</code>```

Body:
In my controller I need to call different update.js based of existence of a parameter.
How to do it correctly?

  respond_to do |format|
    format.js do
      if params[:ble].present?
        'one/update.js'
      else
        'two/update.js'
      end
    end
  end

Body:
I think you're just forgetting to explicitly call render, but you also need to specify layout: false

respond_to do |format|
  format.js do
    if params[:ble].present?
      render 'one/update.js', layout: false
    else
      render 'two/update.js', layout: false
    end
  end
end


问:
Sails.js - PATH variable - sails command not recognized
After I npm installed Sails.js on Windows Server 2008, "sails" command is not recognized.

Can someone give me a hint on what values to use in the PATH variable? As I understand it is Node.exe that runs the sails.js file. But if I try tunning "node sails.js" command in cmd, it recognizes it, but can't find some of the dependencies.

On my Windows 7 machine everything installed and is running like a charm.

答:
Install sails globally
npm install -g sails

If you have right to add Environment variables (Start =>  Computer=> Properties=>Advance system setting => Advance(Tab)=>Environment Variable(button at the bottom) => User variable for ...(the top one) => find "PATH" => edit ) and add the location of your npm folder (C:\Users\XXXXXX\AppData\Roaming\npm) (this folder can be hidden so enable show hidden folder to locate your path)

open new cmd window and enjoy sails :)


问:
SPARQL Query tab in Protege doesn't show anything
I open the SPARQL Query tab in Protege but the result is this:

How can I write my query?

答:
It happens in version 2.0.1 of Protégé SPARQL Plugin, bundled with
  Protege 5.2, after any ontology is loaded.

Update the the "OWLAPI RDF Library" and "Protege SPARQL Plugin" to the latest version with the auto-update mechanism (which appears when starting up Protege or can be activated through the File > Check for plugins… menu):

Source: https://github.com/protegeproject/sparql-query-plugin/issues/10.


问:
Why do I see "No Debuggable Applications" in Android Studio Logcat while my application is running?
I wanted to filter what is shown in the Android Studio Logcat to show what is relevant to my application only. I have chosen Show only selected applications from the drop down at the top of the logcat as shown in the following screenshot:

But in the drop down menu above it which is supposed to show running application(s) (and other options) from which we can choose our application to see Log messages related to it only, I see No debuggable Applications as the only option.

Why? What should I do to fix this?

Note: It does not happen every time I run the project. Sometimes it happens, sometimes it automatically selects my app (when I run it) from the drop down menu shown in the second screenshot, and filters the results properly.

答:
Please make sure to have the android property debuggable = "true" in the application tag AndroidManifest.xml

```<code>**<application  android:debuggable="true">
</application>**
</code>```

Also, if you have multiple build variants (ex. debug, alpha, release) you may need to check which build you are attempting to debug and set the debuggable true attribute accordingly in the build.gradle

```<code>buildTypes {
    debug {
        ...
        debuggable true
        ...
    }
    alpha {
        ...
        debuggable true
        ...
    }
    release {
        ...
        debuggable false
        ...
    }
}
</code>```

Body:
Please make sure to have the android property debuggable = "true" in the application tag AndroidManifest.xml

**<application  android:debuggable="true">
</application>**

Also, if you have multiple build variants (ex. debug, alpha, release) you may need to check which build you are attempting to debug and set the debuggable true attribute accordingly in the build.gradle

buildTypes {
    debug {
        ...
        debuggable true
        ...
    }
    alpha {
        ...
        debuggable true
        ...
    }
    release {
        ...
        debuggable false
        ...
    }
}


问:
Using Roboletric for Junit testing
No such manifest file: build/intermediates/bundles/debug/app/src/main/AndroidManifest.xml

Refered to -Robolectric says "AndroidManifest.xml not found"

https://github.com/robolectric/robolectric/issues/1648 but was not helpful.

答:
Check your gradle and your class :

Gradle :

```<code> testCompile 'org.robolectric:robolectric:3.3'
 testCompile 'junit:junit:4.12'
 testCompile 'org.assertj:assertj-core:1.7.1'
</code>```

In your test Class :

```<code>@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 25)
public class YourTest {

    @Test
    public void shouldNotBeNull() throws Exception {
       //put your test here for example
    }
)
</code>```

YourTest class should be put in Test folder (not AndroidTest folder)

On Android Studio :

Edit Configurations

In Junit, you have to change the working directory to $MODULE_DIR$.
The important thing is $MODULE_DIR$.

Title: Using Roboletric for Junit testing

Body:
Check your gradle and your class :

Gradle :

 testCompile 'org.robolectric:robolectric:3.3'
 testCompile 'junit:junit:4.12'
 testCompile 'org.assertj:assertj-core:1.7.1'

In your test Class :

@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 25)
public class YourTest {

    @Test
    public void shouldNotBeNull() throws Exception {
       //put your test here for example
    }
)

YourTest class should be put in Test folder (not AndroidTest folder)

On Android Studio :

Edit Configurations

In Junit, you have to change the working directory to $MODULE_DIR$.
The important thing is $MODULE_DIR$.


问:
Serial port listener in background C#
I have a question , i build a form application in C# but i am not so good in it.
I want to add a new feature to the form that listen to the serial port in the background and that then show the received data in a textbox and this has to be done so long that the appication is running.

I found some code from how to do this for a console application but now i want to change the code so that i can use it in a form , could anyone help me?

```<code>using System;
using System.IO.Ports;

class PortDataReceived
{
    public static void Main()
    {
        SerialPort mySerialPort = new SerialPort("COM8");

        mySerialPort.BaudRate = 57600;
        mySerialPort.Parity = Parity.None;
        mySerialPort.StopBits = StopBits.One;
        mySerialPort.DataBits = 8;
        mySerialPort.Handshake = Handshake.None;

        mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

        mySerialPort.Open();

        Console.WriteLine("Press any key to continue...");
        Console.WriteLine();
        Console.ReadKey();
        mySerialPort.Close();
    }

    private static void DataReceivedHandler(
                        object sender,
                        SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadExisting();
        Console.WriteLine("Data Received:");
        Console.Write(indata);
    }
}
</code>```

答:
Put the serial port initialization code into the form's Shown event handler, copy the DataReceived event handler code into the form class an instead of writing to the console, put the data into a text box or so.

Please note that the DataReceived handler will be called on a separate thread, so you need to call this.Invoke to execute the code that updates your UI on the UI thread. Otherwise you'll get an exception.

Title: Serial port listener in background C#

Body:
I have a question , i build a form application in C# but i am not so good in it.
I want to add a new feature to the form that listen to the serial port in the background and that then show the received data in a textbox and this has to be done so long that the appication is running.

I found some code from how to do this for a console application but now i want to change the code so that i can use it in a form , could anyone help me?

using System;
using System.IO.Ports;

class PortDataReceived
{
    public static void Main()
    {
        SerialPort mySerialPort = new SerialPort("COM8");

        mySerialPort.BaudRate = 57600;
        mySerialPort.Parity = Parity.None;
        mySerialPort.StopBits = StopBits.One;
        mySerialPort.DataBits = 8;
        mySerialPort.Handshake = Handshake.None;

        mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

        mySerialPort.Open();

        Console.WriteLine("Press any key to continue...");
        Console.WriteLine();
        Console.ReadKey();
        mySerialPort.Close();
    }

    private static void DataReceivedHandler(
                        object sender,
                        SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadExisting();
        Console.WriteLine("Data Received:");
        Console.Write(indata);
    }
}


问:
Custom delegate for NSWindow
I want to create a custom delegate for NSWindow.
CustomWindow is subclassed to get notified about NSWindowDelegate events.
Now I want to create delegate for this CustomWindow.

I tried following code:

CustomWindow.h

```<code>@class CustomWindow;

@protocol CustomWindowDelegate

- (void)method1:(CustomWindow *)sender userInfo:(NSMutableDictionary*) userInfo;
- (void)method2:(CustomWindow *)sender event:(NSEvent *)theEvent;
- (void)method3:(CustomWindow *)sender;

@end

@interface CustomWindow : NSWindow <NSWindowDelegate>

@property (nonatomic) id <CustomWindowDelegate> delegate;

@end
</code>```

mainDocument.h

```<code>#import "CustomWindow.h"

@interface mainDocument : NSDocument

@property (assign) IBOutlet CustomWindow *mainWindow;

@end
</code>```

mainDocument.m

```<code>#import "mainDocument.h"

@implementation mainDocument

- (void)method1:(CustomWindow *)sender userInfo:(NSMutableDictionary*) userInfo
{
...
...
}

- (void)method2:(CustomWindow *)sender event:(NSEvent *)theEvent
{
...
...
}

- (void)method3:(CustomWindow *)sender
{
...
...
}

@end
</code>```

Its working as per expectations however its giving following warnings:

'retain (or strong)' attribute on property 'delegate' does not match the property inherited from 'NSWindow'

'atomic' attribute on property 'delegate' does not match the property inherited from 'NSWindow'

Property type 'id' is incompatible with type 'id _Nullable' inherited from 'NSWindow'

Auto property synthesis will not synthesize property 'delegate'; it will be implemented by its superclass, use @dynamic to acknowledge intention

How can I get rid of these warnings ?

Any helps are greatly appreciated.

答:
NSWindow already has a delegate property and it uses its delegate for different purposes than you're using yours for. The errors are conflicts between your declaration of your delegate property with the declaration of the inherited property.

The simplest solution is for you to rename your property to customDelegate or something like that. Also, the general convention is for delegate properties to be weak, so you should probably declare yours as weak, too.

In general, one could combine a new delegate protocol with NSWindowDelegate and re-use the existing delegate property. In your case, though, since you've declared CustomWindow to conform to NSWindowDelegate, it seems like you're planning on making the window object its own delegate. So, that would conflict with this approach. But, for completeness, if you were going to do that you'd declare your protocol as an extension of NSWindowDelegate:

```<code>@protocol CustomWindowDelegate <NSWindowDelegate>
</code>```

Your property declaration would have to have the same attributes as NSWindow's declaration of its delegate property. So:

```<code>@property (nullable, assign) id<CustomWindowDelegate> delegate;
</code>```

Finally, since you're relying on NSWindow to actually provide the storage and accessor methods of the property, you'd fix the last warning by putting this in the @implementation of CustomWindow:

```<code>@dynamic delegate;
</code>```

Title: Custom delegate for NSWindow

Body:
I want to create a custom delegate for NSWindow.
CustomWindow is subclassed to get notified about NSWindowDelegate events.
Now I want to create delegate for this CustomWindow.

I tried following code:

CustomWindow.h

@class CustomWindow;

@protocol CustomWindowDelegate

- (void)method1:(CustomWindow *)sender userInfo:(NSMutableDictionary*) userInfo;
- (void)method2:(CustomWindow *)sender event:(NSEvent *)theEvent;
- (void)method3:(CustomWindow *)sender;

@end

@interface CustomWindow : NSWindow <NSWindowDelegate>

@property (nonatomic) id <CustomWindowDelegate> delegate;

@end

mainDocument.h

#import "CustomWindow.h"

@interface mainDocument : NSDocument

@property (assign) IBOutlet CustomWindow *mainWindow;

@end

mainDocument.m

#import "mainDocument.h"

@implementation mainDocument

- (void)method1:(CustomWindow *)sender userInfo:(NSMutableDictionary*) userInfo
{
...
...
}

- (void)method2:(CustomWindow *)sender event:(NSEvent *)theEvent
{
...
...
}

- (void)method3:(CustomWindow *)sender
{
...
...
}

@end

Its working as per expectations however its giving following warnings:

'retain (or strong)' attribute on property 'delegate' does not match the property inherited from 'NSWindow'

'atomic' attribute on property 'delegate' does not match the property inherited from 'NSWindow'

Property type 'id' is incompatible with type 'id _Nullable' inherited from 'NSWindow'

Auto property synthesis will not synthesize property 'delegate'; it will be implemented by its superclass, use @dynamic to acknowledge intention

How can I get rid of these warnings ?

Any helps are greatly appreciated.

Body:
NSWindow already has a delegate property and it uses its delegate for different purposes than you're using yours for. The errors are conflicts between your declaration of your delegate property with the declaration of the inherited property.

The simplest solution is for you to rename your property to customDelegate or something like that. Also, the general convention is for delegate properties to be weak, so you should probably declare yours as weak, too.

In general, one could combine a new delegate protocol with NSWindowDelegate and re-use the existing delegate property. In your case, though, since you've declared CustomWindow to conform to NSWindowDelegate, it seems like you're planning on making the window object its own delegate. So, that would conflict with this approach. But, for completeness, if you were going to do that you'd declare your protocol as an extension of NSWindowDelegate:

@protocol CustomWindowDelegate <NSWindowDelegate>

Your property declaration would have to have the same attributes as NSWindow's declaration of its delegate property. So:

@property (nullable, assign) id<CustomWindowDelegate> delegate;

Finally, since you're relying on NSWindow to actually provide the storage and accessor methods of the property, you'd fix the last warning by putting this in the @implementation of CustomWindow:

@dynamic delegate;


问:
Converting a formatted date to another in PHP
I've a date in this format: Tuesday 11th October, 2016
stored in a php varaible $pastdate

I want to convert this to:
2016-10-11 23:59:59

I'm using this line of code:

```<code>$newDate = date("Y-m-d", strtotime($pastDate)).' 23:59:59';
</code>```

However, the output of $newDate is:
2017-10-17 23:59:59

Can anyone explain why this is happening and how I should better format my code?
Thanks in advance.

答:
Here we are changing date from one format to another. Date format reference

Try this code snippet here

```<code><?php

ini_set('display_errors', 1);
$date=date_create_from_format("l dS F, Y", 'Tuesday 11th October, 2016');
$newDate= $date->format("Y-m-d");
echo $newDate." 23:59:59";
</code>```

Output: 2016-10-11 23:59:59

Body:
I've a date in this format: Tuesday 11th October, 2016
stored in a php varaible $pastdate

I want to convert this to:
2016-10-11 23:59:59

I'm using this line of code:

$newDate = date("Y-m-d", strtotime($pastDate)).' 23:59:59';

However, the output of $newDate is:
2017-10-17 23:59:59

Can anyone explain why this is happening and how I should better format my code?
Thanks in advance.

Body:
Here we are changing date from one format to another. Date format reference

Try this code snippet here

<?php

ini_set('display_errors', 1);
$date=date_create_from_format("l dS F, Y", 'Tuesday 11th October, 2016');
$newDate= $date->format("Y-m-d");
echo $newDate." 23:59:59";

Output: 2016-10-11 23:59:59


问:
How to get rows of Data from Multiple Tables using LinQ To Entities
I am using dbcontext Code first to get a query base on this condition for the Classes (tables) below:

Creator != null && ArticleAttached != null && !IsCancelled

```<code>var ArticleStudentLiked = dbcontext.LearningActivites
  .Where(la => la.Creator != null && la.ArticleAttached != null && !la.IsCancelled)
  .Sum(la => la.ArticleAttached.StudentsLiked.Count);

  var NewsArticleComment = dbcontext.LearningActivites
  .Where(la => la.Creator != null && la.ArticleAttached != null && !la.IsCancelled)
  .Sum(la => la.ArticleAttached.Comments.Count);
</code>```

The following Methods only return count for:

ArticleStudentLiked

ArticleComment

I need to get rows of record from the Queries into a single collection which I can pass to View to display line by line

like this :

Article Title, No. of Likes, No. Of Comments

How to use LinQ to Get these : Article Title,No. Of Like , No. of Comment

```<code>Classes:

 public class LearningActivity
 {
   public virtual ArticleCreator Creator { get; set; }
   public virtual ArticleCreator EditedBy { get; set; }
   public virtual Teacher CreatedByTeacher { get; set; }
   public virtual Article ArticleAttached { get; set; }
   public virtual Article ArticleAttachedByOther { get; set; }
   public bool IsCancelled { get; set; }
 }

 public class Article
 {
   public string ArticleTitle {get;set;}
   public virtual IList<Teacher> TeachersLiked { get; set; }
   public virtual IList<Student> StudentsLiked { get; set; }
   public virtual IList<ArticleComment> Comments { get; set; }
 }

 public class Student
 {
   public virtual IList<ArticleCommentStudent> Comments { get; set; }
 }
</code>```

Thanks

答:
Can you try this </p>

```<code>// LikeCount is total of Teacher and Student Likes
// and where clause can be added before Select
var result = dbcontext.Classes
            .Select(x=> new { ArticleTitle = x.ArticleTitle,
                              LikeCount = x.TeachersLiked.Count() + x.StudentsLiked.Count(),
                              CommentCount= x.Comments.Count }).First();
</code>```

Body:
I am using dbcontext Code first to get a query base on this condition for the Classes (tables) below:

Creator != null && ArticleAttached != null && !IsCancelled

var ArticleStudentLiked = dbcontext.LearningActivites
  .Where(la => la.Creator != null && la.ArticleAttached != null && !la.IsCancelled)
  .Sum(la => la.ArticleAttached.StudentsLiked.Count);

  var NewsArticleComment = dbcontext.LearningActivites
  .Where(la => la.Creator != null && la.ArticleAttached != null && !la.IsCancelled)
  .Sum(la => la.ArticleAttached.Comments.Count);

The following Methods only return count for:

ArticleStudentLiked

ArticleComment

I need to get rows of record from the Queries into a single collection which I can pass to View to display line by line

like this :

Article Title, No. of Likes, No. Of Comments

How to use LinQ to Get these : Article Title,No. Of Like , No. of Comment

Classes:

 public class LearningActivity
 {
   public virtual ArticleCreator Creator { get; set; }
   public virtual ArticleCreator EditedBy { get; set; }
   public virtual Teacher CreatedByTeacher { get; set; }
   public virtual Article ArticleAttached { get; set; }
   public virtual Article ArticleAttachedByOther { get; set; }
   public bool IsCancelled { get; set; }
 }

 public class Article
 {
   public string ArticleTitle {get;set;}
   public virtual IList<Teacher> TeachersLiked { get; set; }
   public virtual IList<Student> StudentsLiked { get; set; }
   public virtual IList<ArticleComment> Comments { get; set; }
 }

 public class Student
 {
   public virtual IList<ArticleCommentStudent> Comments { get; set; }
 }

Thanks

Body:
Can you try this

// LikeCount is total of Teacher and Student Likes
// and where clause can be added before Select
var result = dbcontext.Classes
            .Select(x=> new { ArticleTitle = x.ArticleTitle,
                              LikeCount = x.TeachersLiked.Count() + x.StudentsLiked.Count(),
                              CommentCount= x.Comments.Count }).First();


问:
SQLAlchemy execute() return ResultProxy as Tuple, not dict
I have the following code:

```<code>query = """
SELECT Coalesce((SELECT sp.param_value
                 FROM   sites_params sp
                 WHERE  sp.param_name = 'ci'
                        AND sp.site_id = s.id
                 ORDER  BY sp.id DESC
                 LIMIT  1), -1) AS ci
FROM   sites s
WHERE  s.deleted = 0
       AND s.id = 10

"""

site = db_session.execute(query)
# print site
# <sqlalchemy.engine.result.ResultProxy object at 0x033E63D0>

site = db_session.execute(query).fetchone()
print site  # (u'375')
print list(site) # [u'375']
</code>```

Why does SQLAlchemy return tuples, not dicts, for this query? I want to use the following style to access the results of the query:

```<code>print site.ci
# u'375'
</code>```

答:
You can easily convert each result row to a dictionary by using dict(site).
Then site['ci'] would be available if ci column is exists.

In order to have site.ci (according to https://stackoverflow.com/a/22084672/487460):

```<code>from collections import namedtuple
Site = namedtuple('Site', site.keys())
record = Site(*site)
</code>```

Body:
I have the following code:

query = """
SELECT Coalesce((SELECT sp.param_value
                 FROM   sites_params sp
                 WHERE  sp.param_name = 'ci'
                        AND sp.site_id = s.id
                 ORDER  BY sp.id DESC
                 LIMIT  1), -1) AS ci
FROM   sites s
WHERE  s.deleted = 0
       AND s.id = 10

"""

site = db_session.execute(query)
# print site
# <sqlalchemy.engine.result.ResultProxy object at 0x033E63D0>

site = db_session.execute(query).fetchone()
print site  # (u'375')
print list(site) # [u'375']

Why does SQLAlchemy return tuples, not dicts, for this query? I want to use the following style to access the results of the query:

print site.ci
# u'375'

Body:
You can easily convert each result row to a dictionary by using dict(site).
Then site['ci'] would be available if ci column is exists.

In order to have site.ci (according to https://stackoverflow.com/a/22084672/487460):

from collections import namedtuple
Site = namedtuple('Site', site.keys())
record = Site(*site)


问:
How to programmatically check whether a library dependent program can run in a Linux system?
I am having a program(binary) which depends upon libraries such as pthread, sqlite3,libcrypto and libcurl.I want to run this program in multiple user PCs.How to programmatically check whether the dependencies are met, before installing the binary?

./configure cannot be be used as it is for the purpose of building the program as mentioned in , Making os independent configure file which checks for curl dependency.
If I am not wrong .deb and .rpm have there own methods for this.

Can anybody please tell me what is the method they are following for this.Is it just a file name check? For example,if I have build the program using libcurl.so.3, whether it checks that the system in which it will be running is having libcurl.so.3 as a regular file or a simulink.Or any other check is there for the libraries?

What is the reliable method for checking the dependencies, while installing and running a binary?

答:
Building a package

You could distribute your program as .deb or .rpm package. Both formats support specifying dependencies that need to be present:

rpm: Dependencies

deb: Declaring relationships between packages

Checking manually using ldd

You could use ldd(1) to check whether necessary shared libraries are installed and how they are resolved:

```<code>$ ldd /usr/bin/xterm
        linux-vdso.so.1 =>  (0x00007fff649ff000)
        libXft.so.2 => /usr/lib/x86_64-linux-gnu/libXft.so.2 (0x00007fc5195cd000)
        libXaw.so.7 => /usr/lib/x86_64-linux-gnu/libXaw.so.7 (0x00007fc51935b000)
        libutempter.so.0 => /usr/lib/libutempter.so.0 (0x00007fc519158000)
        libtinfo.so.5 => /lib/x86_64-linux-gnu/libtinfo.so.5 (0x00007fc518f2f000)
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fc518ba2000)
        libfontconfig.so.1 => /usr/lib/x86_64-linux-gnu/libfontconfig.so.1 (0x00007fc51896a000)
        libX11.so.6 => /usr/lib/x86_64-linux-gnu/libX11.so.6 (0x00007fc51862f000)
        libXmu.so.6 => /usr/lib/x86_64-linux-gnu/libXmu.so.6 (0x00007fc518415000)
        libXt.so.6 => /usr/lib/x86_64-linux-gnu/libXt.so.6 (0x00007fc5181ad000)
        libICE.so.6 => /usr/lib/x86_64-linux-gnu/libICE.so.6 (0x00007fc517f92000)
        libfreetype.so.6 => /usr/lib/x86_64-linux-gnu/libfreetype.so.6 (0x00007fc517cf3000)
        libXrender.so.1 => /usr/lib/x86_64-linux-gnu/libXrender.so.1 (0x00007fc517ae9000)
        libXext.so.6 => /usr/lib/x86_64-linux-gnu/libXext.so.6 (0x00007fc5178d7000)
        libXpm.so.4 => /usr/lib/x86_64-linux-gnu/libXpm.so.4 (0x00007fc5176c6000)
        /lib64/ld-linux-x86-64.so.2 (0x00007fc5197f8000)
        libz.so.1 => /lib/x86_64-linux-gnu/libz.so.1 (0x00007fc5174ae000)
        libexpat.so.1 => /lib/x86_64-linux-gnu/libexpat.so.1 (0x00007fc517284000)
        libxcb.so.1 => /usr/lib/x86_64-linux-gnu/libxcb.so.1 (0x00007fc517064000)
        libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007fc516e5f000)
        libSM.so.6 => /usr/lib/x86_64-linux-gnu/libSM.so.6 (0x00007fc516c58000)
        libXau.so.6 => /usr/lib/x86_64-linux-gnu/libXau.so.6 (0x00007fc516a54000)
        libXdmcp.so.6 => /usr/lib/x86_64-linux-gnu/libXdmcp.so.6 (0x00007fc51684f000)
        libuuid.so.1 => /lib/x86_64-linux-gnu/libuuid.so.1 (0x00007fc51664a000)
</code>```

When required libraries are not found, "not found" is printed:

```<code>$ ldd bar
        linux-vdso.so.1 =>  (0x00007fffde7ff000)
        libfoo.so => not found
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f5954eae000)
        /lib64/ld-linux-x86-64.so.2 (0x00007f5955251000)
</code>```

Unfortunately, ldd does not return useful exit code in that case.

Keep it simple, stupid

You could just try to run your program and when it fails due to missing libraries, then... you know that you are missing some libraries;)

Body:
Building a package

You could distribute your program as .deb or .rpm package. Both formats support specifying dependencies that need to be present:

rpm: Dependencies

deb: Declaring relationships between packages

Checking manually using ldd

You could use ldd(1) to check whether necessary shared libraries are installed and how they are resolved:

$ ldd /usr/bin/xterm
        linux-vdso.so.1 =>  (0x00007fff649ff000)
        libXft.so.2 => /usr/lib/x86_64-linux-gnu/libXft.so.2 (0x00007fc5195cd000)
        libXaw.so.7 => /usr/lib/x86_64-linux-gnu/libXaw.so.7 (0x00007fc51935b000)
        libutempter.so.0 => /usr/lib/libutempter.so.0 (0x00007fc519158000)
        libtinfo.so.5 => /lib/x86_64-linux-gnu/libtinfo.so.5 (0x00007fc518f2f000)
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fc518ba2000)
        libfontconfig.so.1 => /usr/lib/x86_64-linux-gnu/libfontconfig.so.1 (0x00007fc51896a000)
        libX11.so.6 => /usr/lib/x86_64-linux-gnu/libX11.so.6 (0x00007fc51862f000)
        libXmu.so.6 => /usr/lib/x86_64-linux-gnu/libXmu.so.6 (0x00007fc518415000)
        libXt.so.6 => /usr/lib/x86_64-linux-gnu/libXt.so.6 (0x00007fc5181ad000)
        libICE.so.6 => /usr/lib/x86_64-linux-gnu/libICE.so.6 (0x00007fc517f92000)
        libfreetype.so.6 => /usr/lib/x86_64-linux-gnu/libfreetype.so.6 (0x00007fc517cf3000)
        libXrender.so.1 => /usr/lib/x86_64-linux-gnu/libXrender.so.1 (0x00007fc517ae9000)
        libXext.so.6 => /usr/lib/x86_64-linux-gnu/libXext.so.6 (0x00007fc5178d7000)
        libXpm.so.4 => /usr/lib/x86_64-linux-gnu/libXpm.so.4 (0x00007fc5176c6000)
        /lib64/ld-linux-x86-64.so.2 (0x00007fc5197f8000)
        libz.so.1 => /lib/x86_64-linux-gnu/libz.so.1 (0x00007fc5174ae000)
        libexpat.so.1 => /lib/x86_64-linux-gnu/libexpat.so.1 (0x00007fc517284000)
        libxcb.so.1 => /usr/lib/x86_64-linux-gnu/libxcb.so.1 (0x00007fc517064000)
        libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007fc516e5f000)
        libSM.so.6 => /usr/lib/x86_64-linux-gnu/libSM.so.6 (0x00007fc516c58000)
        libXau.so.6 => /usr/lib/x86_64-linux-gnu/libXau.so.6 (0x00007fc516a54000)
        libXdmcp.so.6 => /usr/lib/x86_64-linux-gnu/libXdmcp.so.6 (0x00007fc51684f000)
        libuuid.so.1 => /lib/x86_64-linux-gnu/libuuid.so.1 (0x00007fc51664a000)

When required libraries are not found, "not found" is printed:

$ ldd bar
        linux-vdso.so.1 =>  (0x00007fffde7ff000)
        libfoo.so => not found
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f5954eae000)
        /lib64/ld-linux-x86-64.so.2 (0x00007f5955251000)

Unfortunately, ldd does not return useful exit code in that case.

Keep it simple, stupid

You could just try to run your program and when it fails due to missing libraries, then... you know that you are missing some libraries;)


问:
An internal error occurred in the Places API library
I'm working with GoogleMaps an GooglePlaces API but I always obtain de same error.

"The operation couldn’t be completed. An internal error occurred in the Places API library. If you believe this error represents a bug, please file a report using the instructions on our community and support page (https://developers.google.com/places/support)"

I've tried to run pod try GoogleMaps and when I launch de project any map is loaded, only a tableView with different options.

This is my code, I only want to obtain the user position:

```<code>-(IBAction)getCurrentPlace:(UIButton *)sender {
[placesClient currentPlaceWithCallback:^(GMSPlaceLikelihoodList *placeLikelihoodList, NSError *error){
    if (error != nil) {
        NSLog(@"Pick Place error %@", [error localizedDescription]);
        return;
    }

    self.nameLabel.text = @"No current place";
    self.addressLabel.text = @"";

    if (placeLikelihoodList != nil) {
        GMSPlace *place = [[[placeLikelihoodList likelihoods] firstObject] place];
        if (place != nil) {
            self.nameLabel.text = place.name;
            self.addressLabel.text = [[place.formattedAddress componentsSeparatedByString:@", "]
                                      componentsJoinedByString:@"\n"];
        }
    }
}];
}
</code>```

I have imported mi APIKEY in didFinishLaunchingWithOptions

```<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[GMSServices provideAPIKey:@"MY_APIKEY"];

return YES;
}
</code>```

And this is my Podfile

```<code>platform :ios, '7.0'
source 'https://github.com/CocoaPods/Specs.git'

target ‘googlePlace’ do

   pod 'GoogleMaps'
   pod 'GooglePlaces'

end
</code>```

Finally, my apikey is configured to iOS application in Google Console.

What's the problem??

答:
This looks like your API key is either invalid or out of quota.

Can you check that you are passing the correct API key to GMSPlacesClient.provideAPIKey(_:).

If you are sure that you are passing the correct API key check the Google API Console (https://console.developers.google.com/) to ensure you have not run over your daily quota limit.

This issue can be tracked here: https://issuetracker.google.com/issues/35830792

Body:
I'm working with GoogleMaps an GooglePlaces API but I always obtain de same error.

"The operation couldn’t be completed. An internal error occurred in the Places API library. If you believe this error represents a bug, please file a report using the instructions on our community and support page (https://developers.google.com/places/support)"

I've tried to run pod try GoogleMaps and when I launch de project any map is loaded, only a tableView with different options.

This is my code, I only want to obtain the user position:

-(IBAction)getCurrentPlace:(UIButton *)sender {
[placesClient currentPlaceWithCallback:^(GMSPlaceLikelihoodList *placeLikelihoodList, NSError *error){
    if (error != nil) {
        NSLog(@"Pick Place error %@", [error localizedDescription]);
        return;
    }

    self.nameLabel.text = @"No current place";
    self.addressLabel.text = @"";

    if (placeLikelihoodList != nil) {
        GMSPlace *place = [[[placeLikelihoodList likelihoods] firstObject] place];
        if (place != nil) {
            self.nameLabel.text = place.name;
            self.addressLabel.text = [[place.formattedAddress componentsSeparatedByString:@", "]
                                      componentsJoinedByString:@"\n"];
        }
    }
}];
}

I have imported mi APIKEY in didFinishLaunchingWithOptions

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[GMSServices provideAPIKey:@"MY_APIKEY"];

return YES;
}

And this is my Podfile

platform :ios, '7.0'
source 'https://github.com/CocoaPods/Specs.git'

target ‘googlePlace’ do

   pod 'GoogleMaps'
   pod 'GooglePlaces'

end

Finally, my apikey is configured to iOS application in Google Console.

What's the problem??


问:
What is the result of the expression?
Does this code would work as expected in all browsers? Is there any notes in specification about it?

```<code>var attributes = this._attributes ? this._attributes : (this._attributes = []);
</code>```

I.e. if *this._attributes* not initialized, then new array will be created and that array will be assigned to *this._attributes* and to attributes.

答:
This works just fine, when accessing an undefined property of any object, that access will return undefined. The single thing you have to watch out for is that you don't extend the Object.prototype to have a _attributes attribute because this will screw you up, but then again, never extend native prototypes.

From the spec :

8.12.2 [[GetProperty]] (P)

Let prop be the result of calling the [[GetOwnProperty]] internal method of O with property name P.

If prop is not undefined, return prop.

Let proto be the value of the [[Prototype]] internal property of O.

If proto is null, return undefined.

Return the result of calling the [[GetProperty]] internal method of proto with argument P.

So it checks whether the object has the property, if so it returns it, if not it searches up the prototype chain, if it finds something there it returns it, otherwise it returns undefined.

Title: What is the result of the expression?

Body:
Does this code would work as expected in all browsers? Is there any notes in specification about it?

var attributes = this._attributes ? this._attributes : (this._attributes = []);

I.e. if *this._attributes* not initialized, then new array will be created and that array will be assigned to *this._attributes* and to attributes.


问:
Can't subscribe data using one subscribe function in ionic 2
This is my get method.

```<code>    get(url: string, options?: RequestOptionsArgs): Promise<Observable<{}>> {
    return new Promise((resolve, reject) => {
      this._frotzOptions(url, options).then((data) => {
        if (data) {
          resolve(this.http.get(url, data));
        } else
          resolve(false);
      }).catch((err) => {
        reject(err);
      });
    });
  }
</code>```

_frotzOptions method.

```<code>     private _frotzOptions(urlo: string | Request, options: RequestOptionsArgs): Promise<{}> {
    if (!options) {
      options = {}
    }
    if (!options.headers) {
      options.headers = new Headers();
    }
    return new Promise((resolve, reject) => {
      this.storage.get('token').then(token => {
        options.headers.append('Content-Type', 'application/json');
        options.headers.append('Authorization', 'Bearer ' + token);
        if (token) {
          resolve(options);
        }
        else
          resolve(false);
      }).catch((err) => {
        reject(err);
      });
    });

  }
</code>```

home.ts

```<code>var subscription = Observable.fromPromise(this.ahttp.get(url));
subscription.subscribe((data) => {
  data.subscribe(rsp => {
    console.log("rsp", rsp);
  })
}, (err) => {
  console.log(err)
});
</code>```

When I need to use data which are resolving fro the get method, I have to use a subscribe within a subscribe! What is the best way to do this by using a subscribe! Any suggestions! Thank you!

答:
Hi why don 't you just do like this:

```<code>private _frotzOptions(urlo: string | Request, options: RequestOptionsArgs): Observable<any> { //<--!! CHANGE TO OBSERVABLE from Rx/rx
if (!options) {
  options = {}
}
if (!options.headers) {
  options.headers = new Headers();
}
return new Promise((resolve, reject) => {
  this.storage.get('token').then(token => {
    options.headers.append('Content-Type', 'application/json');
    options.headers.append('Authorization', 'Bearer ' + token);
    if (token) {
      resolve(options);
    }
    else
      resolve(false);
  }).catch((err) => {
    reject(err);
  });
});
</code>```

and then when you want to use it:

```<code>this.ahttp.get(url).subscribe((data) => {
  data.subscribe(rsp => {
    console.log("rsp", rsp);
  })
}, (err) => {
  console.log(err)
});
</code>```

And last ... to inject your Bearer token in request use INTERCEPTOR ... maybe with some plugin like:

```<code>https://www.npmjs.com/package/angular2-http-interceptor
</code>```

Body:
This is my get method.

    get(url: string, options?: RequestOptionsArgs): Promise<Observable<{}>> {
    return new Promise((resolve, reject) => {
      this._frotzOptions(url, options).then((data) => {
        if (data) {
          resolve(this.http.get(url, data));
        } else
          resolve(false);
      }).catch((err) => {
        reject(err);
      });
    });
  }

_frotzOptions method.

     private _frotzOptions(urlo: string | Request, options: RequestOptionsArgs): Promise<{}> {
    if (!options) {
      options = {}
    }
    if (!options.headers) {
      options.headers = new Headers();
    }
    return new Promise((resolve, reject) => {
      this.storage.get('token').then(token => {
        options.headers.append('Content-Type', 'application/json');
        options.headers.append('Authorization', 'Bearer ' + token);
        if (token) {
          resolve(options);
        }
        else
          resolve(false);
      }).catch((err) => {
        reject(err);
      });
    });

  }

home.ts

var subscription = Observable.fromPromise(this.ahttp.get(url));
subscription.subscribe((data) => {
  data.subscribe(rsp => {
    console.log("rsp", rsp);
  })
}, (err) => {
  console.log(err)
});

When I need to use data which are resolving fro the get method, I have to use a subscribe within a subscribe! What is the best way to do this by using a subscribe! Any suggestions! Thank you!

Body:
Hi why don 't you just do like this:

private _frotzOptions(urlo: string | Request, options: RequestOptionsArgs): Observable<any> { //<--!! CHANGE TO OBSERVABLE from Rx/rx
if (!options) {
  options = {}
}
if (!options.headers) {
  options.headers = new Headers();
}
return new Promise((resolve, reject) => {
  this.storage.get('token').then(token => {
    options.headers.append('Content-Type', 'application/json');
    options.headers.append('Authorization', 'Bearer ' + token);
    if (token) {
      resolve(options);
    }
    else
      resolve(false);
  }).catch((err) => {
    reject(err);
  });
});

and then when you want to use it:

this.ahttp.get(url).subscribe((data) => {
  data.subscribe(rsp => {
    console.log("rsp", rsp);
  })
}, (err) => {
  console.log(err)
});

And last ... to inject your Bearer token in request use INTERCEPTOR ... maybe with some plugin like:

https://www.npmjs.com/package/angular2-http-interceptor


问:
How to open an existing GitHub project with Xcode?
I am new to xcode and I want to learn iphone development.

I found one demo project on github, I want to know how to open this existing project?

答:
Note: since June 2016, you can open your demo GitHub project in Xcode directly from the GitHub site!

But you will need the latest Xcode 9, announced at the 2017 WWDC

See "Clone in Xcode"

It's easy to explore code in your browser when you visit a GitHub repository, but you often want to pull that code directly into the appropriate editor and try it out.

  For example, if the repository contains an .xcodeproj or .xcworkspace file, you might want to open that code in Xcode.

This is possible starting today with the new "Open in Xcode" button.

That will trigger the git clone for you.

Note: as illustrated in "Unable to see “Open in Xcode” button on GitHub", you also have to be logged in to GitHub in Xcode as well.

In Xcode, navigate to Preferences.../Accounts, select GitHub and enter your login credentials.


问:
access images from resource folder on iphone
I have folder inside reource folder lets say

resource->folder A->61.png

so how to access this path I did this

```<code>NSString *myFilePath=   [[NSBundle mainBundle] pathForResource:@"61" ofType:@"png" inDirectory:@"A" ];

NSLog(@"file is at %@",myFilePath);// its null
</code>```

why my path is null?

答:
This is the answer for anyone who is looking for it.

You need to import the directory into your app using the following method:

Create a Directory on your Mac.

Select to Add Existing Files to your project

Select the Directory you want to import

In the pop-up window make sure you select "Copy items into destination group's folder" and "Create Folder References for any added folders"

Hit "Add"

You’re done!

Body:
I have folder inside reource folder lets say

resource->folder A->61.png

so how to access this path I did this

NSString *myFilePath=   [[NSBundle mainBundle] pathForResource:@"61" ofType:@"png" inDirectory:@"A" ];

NSLog(@"file is at %@",myFilePath);// its null

why my path is null?


问:
What is the best practice of SUM column values using codeigniter
I am currently using below code to sum up numbers of quantity based on a ID
targeting mysql quantity column, just wondering if this is the best practice  using codeigniter? or is there a shorter way to execute this.

My Model.php

```<code>public function sum_quantity_of_stacks($id){

        $query = $this->db->query("SELECT *, SUM(qty) as total FROM stocks WHERE drug_id = '$id'");
        return $query->row_array();

    }

    public function sum_quantity_of_request($id){

        $query = $this->db->query("SELECT *,SUM(quantity) as total_request FROM med_request WHERE med_given = '$id' AND status = 'Approved'");
        return $query->row_array();

    }
</code>```

Then my view.php

```<code>$id = $medicine['ID'];

        $data['get_count'] = $this->Medicine_model->sum_quantity_of_stacks($id);

        $data['get_request'] = $this->Medicine_model->sum_quantity_of_request($id);

        $total_available = $data['get_count']['total'];
        $total_given = $data['get_request']['total_request'];

        echo $total_available  - $total_given;
</code>```

Above code gives me the current available stocks of my medicine inventory.

答:
No, there are no such way to do that, similar to what are you are doing now.

SELECT other column with SUM feature not possible

But there are a method name select_sum() available in query builder by which you may get SUM only like

```<code>public function sum_quantity_of_stacks($id){
    $this->db->select_sum('qty','total');
    $this->db->where('drug_id',$id);
    $query = $this->db->get('stocks');
    $res = $query->row_array();
    //now SUM is available in $res['total']
    return $res['total'];
   // or return $query->row_array();
}
</code>```

Body:
I am currently using below code to sum up numbers of quantity based on a ID
targeting mysql quantity column, just wondering if this is the best practice  using codeigniter? or is there a shorter way to execute this.

My Model.php

public function sum_quantity_of_stacks($id){

        $query = $this->db->query("SELECT *, SUM(qty) as total FROM stocks WHERE drug_id = '$id'");
        return $query->row_array();

    }

    public function sum_quantity_of_request($id){

        $query = $this->db->query("SELECT *,SUM(quantity) as total_request FROM med_request WHERE med_given = '$id' AND status = 'Approved'");
        return $query->row_array();

    }

Then my view.php

$id = $medicine['ID'];

        $data['get_count'] = $this->Medicine_model->sum_quantity_of_stacks($id);

        $data['get_request'] = $this->Medicine_model->sum_quantity_of_request($id);

        $total_available = $data['get_count']['total'];
        $total_given = $data['get_request']['total_request'];

        echo $total_available  - $total_given;

Above code gives me the current available stocks of my medicine inventory.

Body:
No, there are no such way to do that, similar to what are you are doing now.

SELECT other column with SUM feature not possible

But there are a method name select_sum() available in query builder by which you may get SUM only like

public function sum_quantity_of_stacks($id){
    $this->db->select_sum('qty','total');
    $this->db->where('drug_id',$id);
    $query = $this->db->get('stocks');
    $res = $query->row_array();
    //now SUM is available in $res['total']
    return $res['total'];
   // or return $query->row_array();
}


问:
How can do multiple stationary tests for multiple timeseries in a dataframe
I have the following df:

```<code>head(vardata)
       Month repo Callrate  WPI GDP  FED    nse   usd
1 2001-04-01 9.00     7.49 5.41 4.6 4.50 1125.2 46.79
2 2001-05-01 8.75     8.03 5.60 4.6 4.00 1167.9 46.92
3 2001-06-01 8.50     7.24 5.30 4.6 3.75 1107.9 47.00
4 2001-07-01 8.50     7.19 5.23 5.3 3.75 1072.8 47.14
5 2001-08-01 8.50     6.94 5.41 5.3 3.50 1053.8 47.13
6 2001-09-01 8.50     7.30 4.52 5.3 3.00  913.9 47.65

vardata_num<-df[,2:8]
</code>```

I want to conduct Box.test, adf.test, and kpss.test for all the 7 var with following set of rules:

Say I set a significance level of 5%. Then the rules are:

1) For the Box.test, if p-value < 0.05 => stationary

2) For the adf.test, if p-value < 0.05 => stationary

3) For the kpss.test, if p-value > 0.05 => stationary (note change of inequality)

Individually i did the tests as:

```<code>Box.test(ts(vardata_num$repo),lag=20,type="Ljung-Box")

    Box-Ljung test

data:  ts(vardata_num$repo)
X-squared = 1100, df = 20, p-value <2e-16

adf.test(ts(vardata_num$repo),alternative = "stationary")

    Augmented Dickey-Fuller Test

data:  ts(vardata_num$repo)
Dickey-Fuller = -2.7, Lag order = 5, p-value = 0.3
alternative hypothesis: stationary

kpss.test(ts(vardata_num$repo))

    KPSS Test for Level Stationarity

data:  ts(vardata_num$repo)
KPSS Level = 0.32, Truncation lag parameter = 3, p-value = 0.1

# to extract p values
Box.test(ts(vardata_num$repo),lag=20,type="Ljung-Box")$p.value
adf.test(ts(vardata_num$repo),alternative = "stationary")$p.value
kpss.test(ts(vardata_num$repo))$p.value
</code>```

This was done one at a time for all the variables.....

But I would like to do all these tests in one go for all the var & the outputted in some sort of a data frame if possible maybe like this:

```<code>   var         box.pvalue  box  adf.pvalue adf  kpss.pvalue kpss
   repo          0.03      TRUE    0.03   TRUE     0.03    FALSE
   Callrate      0.03      TRUE    0.03   TRUE     0.03    FALSE
   WPI           0.03      TRUE    0.03   TRUE     0.03    FALSE
   GDP           0.03      TRUE    0.03   TRUE     0.03    FALSE
   FED           0.51      FALSE   0.03   TRUE     0.03    FALSE
   nse           0.03      TRUE    0.03   TRUE     0.03    FALSE
   usd           0.45      FALSE   0.03   TRUE     0.03    FALSE
</code>```

Where TRUE= series is stationary ; FALSE= series is NON-stationary

update--- my attempt

stationarity tests for multiple time series

```<code>multi_stat_tests<- function(df){
  for(i in 1:dim(df)[2]){
    df_multi<-data.frame(var=names(df)[i],box.pvalue=Box.test(ts(df[,i]),lag=20,type="Ljung-Box")$p.value,adf.pvalue=adf.test(ts(df[,i]),alternative = "stationary")$p.value,kpss.pvalue=kpss.test(ts(df[,i]))$p.value,
box=Box.test(ts(df[,i]),lag=20,type="Ljung-Box")$p.value<0.05,
adf=adf.test(ts(df[,i]),alternative = "stationary")$p.value<0.05,
kpss=kpss.test(ts(df[,i]))$p.value>0.05
)
    return(df_multi)
  }
}

>multi_stat_tests(vardata_num)

  var box.pvalue adf.pvalue  kpss.pvalue  box  adf  kpss
1 repo          0     0.2859         0.1 TRUE FALSE TRUE
</code>```

Its just picking up only one var......its not iterating across all the variables...missing something here....HELP required!!!!!

答:
Here is the dplyr and tidyr solution:

```<code>library(dplyr)
library(tidyr)
library(tseries) # for kpss.test

data <- data.frame(Sys.Date()-1:200, matrix(rnorm(1400, 0, 1), ncol=7) )
colnames(data) <- c("Month", "repo", "Callrate", "WPI", "GDP", "FED", "nse", "usd")

data %>%
 gather(Series, Value, -Month) %>%
  group_by(Series) %>%
   summarise(
    box.pvalue = Box.test(Value, lag=20, type="Ljung-Box")$p.value,
    box = Box.test(Value, lag=20, type="Ljung-Box")$p.value<0.05,
    adf.pvalue = adf.test(Value, alternative = "stationary")$p.value,
    adf = adf.test(Value, alternative = "stationary")$p.value<0.05,
    kpss.pvalue=kpss.test(Value)$p.value,
    kpss=kpss.test(Value)$p.value>0.05
  )
</code>```

Long-table design allows you to avoid for loop solution. Instead, you conduct a conditional analysis (conditioned by Series) of values in column Value.

Body:
I have the following df:

head(vardata)
       Month repo Callrate  WPI GDP  FED    nse   usd
1 2001-04-01 9.00     7.49 5.41 4.6 4.50 1125.2 46.79
2 2001-05-01 8.75     8.03 5.60 4.6 4.00 1167.9 46.92
3 2001-06-01 8.50     7.24 5.30 4.6 3.75 1107.9 47.00
4 2001-07-01 8.50     7.19 5.23 5.3 3.75 1072.8 47.14
5 2001-08-01 8.50     6.94 5.41 5.3 3.50 1053.8 47.13
6 2001-09-01 8.50     7.30 4.52 5.3 3.00  913.9 47.65

vardata_num<-df[,2:8]

I want to conduct Box.test, adf.test, and kpss.test for all the 7 var with following set of rules:

Say I set a significance level of 5%. Then the rules are:

1) For the Box.test, if p-value < 0.05 => stationary

2) For the adf.test, if p-value < 0.05 => stationary

3) For the kpss.test, if p-value > 0.05 => stationary (note change of inequality)

Individually i did the tests as:

Box.test(ts(vardata_num$repo),lag=20,type="Ljung-Box")

    Box-Ljung test

data:  ts(vardata_num$repo)
X-squared = 1100, df = 20, p-value <2e-16

adf.test(ts(vardata_num$repo),alternative = "stationary")

    Augmented Dickey-Fuller Test

data:  ts(vardata_num$repo)
Dickey-Fuller = -2.7, Lag order = 5, p-value = 0.3
alternative hypothesis: stationary

kpss.test(ts(vardata_num$repo))

    KPSS Test for Level Stationarity

data:  ts(vardata_num$repo)
KPSS Level = 0.32, Truncation lag parameter = 3, p-value = 0.1

# to extract p values
Box.test(ts(vardata_num$repo),lag=20,type="Ljung-Box")$p.value
adf.test(ts(vardata_num$repo),alternative = "stationary")$p.value
kpss.test(ts(vardata_num$repo))$p.value

This was done one at a time for all the variables.....

But I would like to do all these tests in one go for all the var & the outputted in some sort of a data frame if possible maybe like this:

   var         box.pvalue  box  adf.pvalue adf  kpss.pvalue kpss
   repo          0.03      TRUE    0.03   TRUE     0.03    FALSE
   Callrate      0.03      TRUE    0.03   TRUE     0.03    FALSE
   WPI           0.03      TRUE    0.03   TRUE     0.03    FALSE
   GDP           0.03      TRUE    0.03   TRUE     0.03    FALSE
   FED           0.51      FALSE   0.03   TRUE     0.03    FALSE
   nse           0.03      TRUE    0.03   TRUE     0.03    FALSE
   usd           0.45      FALSE   0.03   TRUE     0.03    FALSE

Where TRUE= series is stationary ; FALSE= series is NON-stationary

update--- my attempt

stationarity tests for multiple time series

multi_stat_tests<- function(df){
  for(i in 1:dim(df)[2]){
    df_multi<-data.frame(var=names(df)[i],box.pvalue=Box.test(ts(df[,i]),lag=20,type="Ljung-Box")$p.value,adf.pvalue=adf.test(ts(df[,i]),alternative = "stationary")$p.value,kpss.pvalue=kpss.test(ts(df[,i]))$p.value,
box=Box.test(ts(df[,i]),lag=20,type="Ljung-Box")$p.value<0.05,
adf=adf.test(ts(df[,i]),alternative = "stationary")$p.value<0.05,
kpss=kpss.test(ts(df[,i]))$p.value>0.05
)
    return(df_multi)
  }
}

>multi_stat_tests(vardata_num)

  var box.pvalue adf.pvalue  kpss.pvalue  box  adf  kpss
1 repo          0     0.2859         0.1 TRUE FALSE TRUE

Its just picking up only one var......its not iterating across all the variables...missing something here....HELP required!!!!!

Body:
Here is the dplyr and tidyr solution:

library(dplyr)
library(tidyr)
library(tseries) # for kpss.test

data <- data.frame(Sys.Date()-1:200, matrix(rnorm(1400, 0, 1), ncol=7) )
colnames(data) <- c("Month", "repo", "Callrate", "WPI", "GDP", "FED", "nse", "usd")

data %>%
 gather(Series, Value, -Month) %>%
  group_by(Series) %>%
   summarise(
    box.pvalue = Box.test(Value, lag=20, type="Ljung-Box")$p.value,
    box = Box.test(Value, lag=20, type="Ljung-Box")$p.value<0.05,
    adf.pvalue = adf.test(Value, alternative = "stationary")$p.value,
    adf = adf.test(Value, alternative = "stationary")$p.value<0.05,
    kpss.pvalue=kpss.test(Value)$p.value,
    kpss=kpss.test(Value)$p.value>0.05
  )

Long-table design allows you to avoid for loop solution. Instead, you conduct a conditional analysis (conditioned by Series) of values in column Value.


问:
Unable to fetch records when using between in date range in sql
When I use the following query in SQL, no records have been returned.

```<code>select distinct e.No from attendance a
inner join Employee e on a.EmployeeId =e.No
where e.No not in (select EmployeeId from attendance where AttendanceDate between '2017-05-26 00:00:00' and '2017-06-06 00:00:00')
</code>```

But when I single date instead of date range, it works fine. e.g.

```<code>select distinct e.No from attendance a
inner join Employee e on a.EmployeeId =e.No
where e.No not in (select EmployeeId from attendance where AttendanceDate = '2017-06-06 00:00:00' )
</code>```

Can someone please help me out to solve this issue as I have to use a date range instead of a particular date.

答:
if you run the select in your where statement do you get any results?

try it without the time on it:

```<code>between '2017-05-26' and '2017-06-06'
</code>```

what date format are you using?

Body:
When I use the following query in SQL, no records have been returned.

select distinct e.No from attendance a
inner join Employee e on a.EmployeeId =e.No
where e.No not in (select EmployeeId from attendance where AttendanceDate between '2017-05-26 00:00:00' and '2017-06-06 00:00:00')

But when I single date instead of date range, it works fine. e.g.

select distinct e.No from attendance a
inner join Employee e on a.EmployeeId =e.No
where e.No not in (select EmployeeId from attendance where AttendanceDate = '2017-06-06 00:00:00' )

Can someone please help me out to solve this issue as I have to use a date range instead of a particular date.

Body:
if you run the select in your where statement do you get any results?

try it without the time on it:

between '2017-05-26' and '2017-06-06'

what date format are you using?


问:
Display DICOM monochrome2 having bits stored less than bits allocated
I want to display DICOM file having photometric interpretation MONOCHROME2.

some of the specifications of image are-

```<code>Rows:           1024
Columns:        1024
No of Frames:   622
Bits Allocated: 16
Bits Stored:    10
High Bit:       9
Pixel Representation: 0
Sample per pixel: 1
</code>```

I am using gdcmRegionReader to extract single frames byte array in the following way.

```<code> gdcm.ImageRegionReader _regionReader = new gdcm.ImageRegionReader();
 _regionReader.SetRegion(_boxRegion);  // _boxRegion is some region
 _regionReader.ReadIntoBuffer(Result, (uint)Result.Length);
 Marshal.Copy(Result.ToArray(), 0, _imageData.GetScalarPointer(),
 Result.ToArray().Length);
 _viewer.SetInput(_imageData);  // _viewer = vtkImageViewer
</code>```

But when i display that file it is displaying like this..

but the original image is like this..

So can someone help me on how to load and display MONOCHROME2 dicom images.

答:
Disclaimer: I never used the toolkit in question. I am attempting to answer based on my understanding of DICOM. In my experience about DICOM, syntax was rarely was the problem. Real problem was the concept and terms.

I see two problems in output.

One is about part of the image rendered. Notice that entire data is not rendered in your output. Check the toolkit document to see how to set the dimensions/bounds while rendering image.

Other problem is about output quality. Initially, I suspected the Transfer Syntax might be the issue. I do not think it is but just make sure you are uncompromising the image before rendering. I am not sure how your toolkit handles compression while rendering.

There is other way available to render pixel data in the toolkit.

```<code>_ImageViewer.SetRenderWindow(renderWindow);
_ImageViewer.GetRenderer().AddActor2D(sliceStatusActor);
_ImageViewer.GetRenderer().AddActor2D(usageTextActor);
_ImageViewer.SetSlice(_MinSlice);
_ImageViewer.Render();
</code>```

Above code is copied from "http://www.vtk.org/Wiki/VTK/Examples/CSharp/IO/ReadDICOMSeries". Detailed code is available there.

Following links may also be helpful:

http://vtk.1045678.n5.nabble.com/How-to-map-negative-grayscale-to-color-td5737080.html

https://www.codeproject.com/Articles/31581/Displaying-bit-Images-Using-C

Body:
I want to display DICOM file having photometric interpretation MONOCHROME2.

some of the specifications of image are-

Rows:           1024
Columns:        1024
No of Frames:   622
Bits Allocated: 16
Bits Stored:    10
High Bit:       9
Pixel Representation: 0
Sample per pixel: 1

I am using gdcmRegionReader to extract single frames byte array in the following way.

 gdcm.ImageRegionReader _regionReader = new gdcm.ImageRegionReader();
 _regionReader.SetRegion(_boxRegion);  // _boxRegion is some region
 _regionReader.ReadIntoBuffer(Result, (uint)Result.Length);
 Marshal.Copy(Result.ToArray(), 0, _imageData.GetScalarPointer(),
 Result.ToArray().Length);
 _viewer.SetInput(_imageData);  // _viewer = vtkImageViewer

But when i display that file it is displaying like this..

but the original image is like this..

So can someone help me on how to load and display MONOCHROME2 dicom images.

Body:
Disclaimer: I never used the toolkit in question. I am attempting to answer based on my understanding of DICOM. In my experience about DICOM, syntax was rarely was the problem. Real problem was the concept and terms.

I see two problems in output.

One is about part of the image rendered. Notice that entire data is not rendered in your output. Check the toolkit document to see how to set the dimensions/bounds while rendering image.

Other problem is about output quality. Initially, I suspected the Transfer Syntax might be the issue. I do not think it is but just make sure you are uncompromising the image before rendering. I am not sure how your toolkit handles compression while rendering.

There is other way available to render pixel data in the toolkit.

_ImageViewer.SetRenderWindow(renderWindow);
_ImageViewer.GetRenderer().AddActor2D(sliceStatusActor);
_ImageViewer.GetRenderer().AddActor2D(usageTextActor);
_ImageViewer.SetSlice(_MinSlice);
_ImageViewer.Render();

Above code is copied from "http://www.vtk.org/Wiki/VTK/Examples/CSharp/IO/ReadDICOMSeries". Detailed code is available there.

Following links may also be helpful:

http://vtk.1045678.n5.nabble.com/How-to-map-negative-grayscale-to-color-td5737080.html

https://www.codeproject.com/Articles/31581/Displaying-bit-Images-Using-C