问:
PL SQL relationship and procedure issues
I would like to ask some help with pl/sql oracle. I am trying to figure out this object oriented database stuff but not much success so far. I am into programming and i understand rdbms as well, already managed some complex database but this object oriented is over my understanding.
So the task is the following:
There are teachers and students. need to make a timetable which has two type of lessons. day and afternoon.
day class can have maximum 10 students and afternoon max 5.

the followings i have so far:

```<code>/*create student type and table*/
create type student_typ as object(
st_id char(3),
st_name varchar(50)
)
create table student_tbl of student_typ(
st_id primary key not null,
st_name not null
)

/*create teacher type and table*/
create type teacher_typ as object(
tr_id char(3),
tr_name varchar(50)
)
create table teacher_tbl of teacher_typ(
tr_id primary key not null,
tr_name not null
)

/*create array type to store the student id-s*/
create type students_arr as varray(20) of char(3);

/*create table for timetable*/
create table timetable_tbl(
t_ID char(5),
t_Date date,
t_Time varchar(5), /*store time format as 12:00*/
t_Type char(1),
teacher ref teacher_typ scope is teacher_tbl,
students students_arr,
constraint chk_type check(t_Type='D' or t_Type='N')
)

/*insert values into the tables*/
insert into teacher_tbl values ('t01','bob');
insert into teacher_tbl values ('t02','smith');
insert into student_tbl values ('s01','lara');
insert into student_tbl values ('s02','john');

/*insert values into timetable*/
insert into timetable_tbl( select 't01','01-Apr-17','09:00','D',ref(t),students_arr('s01','s02') from teacher_tbl t where t.tr_ID='t01');
insert into timetable_tbl( select 't02','01-Apr-17','19:00','N',ref(t),students_arr('s01') from teacher_tbl t where t.tr_ID='t02');

/*display timetable records*/
select t_ID, t_Date, t_Time, t_Type, deref(teacher).tr_ID,deref(teacher).tr_Name, students from timetable_tbl;

/*create procedure to add new student*/
create or replace procedure Add_Student(
v_id in student_tbl.st_id%type,
v_name in student_tbl.st_name%type,
verror out varchar2 )
is begin
insert into student_tbl (st_id,st_name) values (v_id,v_name);
commit;
exception when others then
verror := sqlerrm;
end;

/*call add_student procedure*/
declare
verror varchar2(500);
begin
Add_Student('s03','sam',verror);
end;
</code>```

So that is what i have so far. The questions are the next.

Is this the right way to do this?

how can i reference the students in the varray? i have tried ref as with the teacher ref but no result at all?
students student_arr ref student_typ scope is student_tbl; this code is not working.
the students_arr array should accept only existing records from student table

how can i create a procedure for timetable? because the main thing there is when the t_Type is "D" then the student_arr should allow maximum 10 values
and if the t_Type is "N" then the student_arr should allow maximum 5 values only. i Should do something like add_record procedure for timetable and using if statement but i am not sure it would be a good idea.
if t_type='D' then
if students.count<=10
or
if t_type='N' then
if students.count<=5

Im kind of stucked now. I have watched a lot of tutorials about pl sql but got even more confused. The annoying things is that i managed the same with
rdbms (sql server) and java in no time. But this language and object database got me hard now.

Any help would be appropriated!

答:
You can expand the students array using the table() function:

```<code>select t_id, t_date, t_time, t_type, deref(teacher).tr_id,deref(teacher).tr_name
     , s.column_value as student
from   timetable_tbl cross join table(students) s;
</code>```

You'll also see that join written as

```<code>from   timetable_tbl, table(students) s;
</code>```

which looks neater in this context but I've officially switched to ANSI join syntax.

Since students_arr is a generic varray of varchar2 it has no attribute names, hence the default name column_value.

As for the procedure to insert timetables, if it takes a students_arr varray parameter named p_students, yes just check p_students.count against the t_type value. (You can't use a cardinality() function in a check constraint unfortunately, which otherwise might have been the declarative approach.)

Regarding "the right way to do this", use ordinary, normalised relational tables unless you have a good use for the object/nested table stuff.

Body:
I would like to ask some help with pl/sql oracle. I am trying to figure out this object oriented database stuff but not much success so far. I am into programming and i understand rdbms as well, already managed some complex database but this object oriented is over my understanding.
So the task is the following:
There are teachers and students. need to make a timetable which has two type of lessons. day and afternoon.
day class can have maximum 10 students and afternoon max 5.

the followings i have so far:

/*create student type and table*/
create type student_typ as object(
st_id char(3),
st_name varchar(50)
)
create table student_tbl of student_typ(
st_id primary key not null,
st_name not null
)

/*create teacher type and table*/
create type teacher_typ as object(
tr_id char(3),
tr_name varchar(50)
)
create table teacher_tbl of teacher_typ(
tr_id primary key not null,
tr_name not null
)

/*create array type to store the student id-s*/
create type students_arr as varray(20) of char(3);

/*create table for timetable*/
create table timetable_tbl(
t_ID char(5),
t_Date date,
t_Time varchar(5), /*store time format as 12:00*/
t_Type char(1),
teacher ref teacher_typ scope is teacher_tbl,
students students_arr,
constraint chk_type check(t_Type='D' or t_Type='N')
)

/*insert values into the tables*/
insert into teacher_tbl values ('t01','bob');
insert into teacher_tbl values ('t02','smith');
insert into student_tbl values ('s01','lara');
insert into student_tbl values ('s02','john');

/*insert values into timetable*/
insert into timetable_tbl( select 't01','01-Apr-17','09:00','D',ref(t),students_arr('s01','s02') from teacher_tbl t where t.tr_ID='t01');
insert into timetable_tbl( select 't02','01-Apr-17','19:00','N',ref(t),students_arr('s01') from teacher_tbl t where t.tr_ID='t02');

/*display timetable records*/
select t_ID, t_Date, t_Time, t_Type, deref(teacher).tr_ID,deref(teacher).tr_Name, students from timetable_tbl;

/*create procedure to add new student*/
create or replace procedure Add_Student(
v_id in student_tbl.st_id%type,
v_name in student_tbl.st_name%type,
verror out varchar2 )
is begin
insert into student_tbl (st_id,st_name) values (v_id,v_name);
commit;
exception when others then
verror := sqlerrm;
end;

/*call add_student procedure*/
declare
verror varchar2(500);
begin
Add_Student('s03','sam',verror);
end;

So that is what i have so far. The questions are the next.

Is this the right way to do this?

how can i reference the students in the varray? i have tried ref as with the teacher ref but no result at all?
students student_arr ref student_typ scope is student_tbl; this code is not working.
the students_arr array should accept only existing records from student table

how can i create a procedure for timetable? because the main thing there is when the t_Type is "D" then the student_arr should allow maximum 10 values
and if the t_Type is "N" then the student_arr should allow maximum 5 values only. i Should do something like add_record procedure for timetable and using if statement but i am not sure it would be a good idea.
if t_type='D' then
if students.count<=10
or
if t_type='N' then
if students.count<=5

Im kind of stucked now. I have watched a lot of tutorials about pl sql but got even more confused. The annoying things is that i managed the same with
rdbms (sql server) and java in no time. But this language and object database got me hard now.

Any help would be appropriated!

Body:
You can expand the students array using the table() function:

select t_id, t_date, t_time, t_type, deref(teacher).tr_id,deref(teacher).tr_name
     , s.column_value as student
from   timetable_tbl cross join table(students) s;

You'll also see that join written as

from   timetable_tbl, table(students) s;

which looks neater in this context but I've officially switched to ANSI join syntax.

Since students_arr is a generic varray of varchar2 it has no attribute names, hence the default name column_value.

As for the procedure to insert timetables, if it takes a students_arr varray parameter named p_students, yes just check p_students.count against the t_type value. (You can't use a cardinality() function in a check constraint unfortunately, which otherwise might have been the declarative approach.)

Regarding "the right way to do this", use ordinary, normalised relational tables unless you have a good use for the object/nested table stuff.


来源: stackexchange

问:
Why does mysql allow a foreign key to refer a part of composite primary key?
Suppose I have two tables in mysql
1.Child(name,father_name)
2.Father(name,contact)

The table Father has a composite key (name,contact).Father_name in Child table references name in father . Thus a foreign key references a part of primary key.This is allowed by mysql.

However consider the following situation:

Table father has the following tuples:

```<code>(kishan,9906011111)
(kishan,9990601234)
</code>```

Now suppose I insert a row in child

```<code>(xyz,kishan)
</code>```

How would I know which kishan in the father table is the child xyz related to ?

This situation could have been avoided if mysql does not allow a foreign key to refer a part of the primary key .

Please answer what's the benefit of this scheme allowed by mysql ?

答:
This is a peculiarity of MySQL.  In my opinion, foreign keys should only be to unique keys or primary keys.  There should not be a mapping to "sets" of values using a foreign key relationship.

Clearly, the designers of MySQL disagree (both with me and other database implementors).  They allow foreign key relationships to any columns that are indexed -- in MySQL parlance, are defined as a "key".  If you have a composite primary key, then the initial column(s) are such a key.

To prevent problems and make your tables unambiguous and easy to use, I would recommend:

All tables have an auto-incremented primary key.

All foreign key relationships are only to primary keys (not to unique keys or other types of key).

The primary key be named the singular of the entity followed by id (example:  things would have thingId as a primary key).

The foreign key have the same name as the primary key (except when this is not possible because there are multiple foreign key relationships to the same table).

ContentLicense: CC BY-SA 3.0

Body:
Suppose I have two tables in mysql
1.Child(name,father_name)
2.Father(name,contact)

The table Father has a composite key (name,contact).Father_name in Child table references name in father . Thus a foreign key references a part of primary key.This is allowed by mysql.

However consider the following situation:

Table father has the following tuples:

(kishan,9906011111)
(kishan,9990601234)

Now suppose I insert a row in child

(xyz,kishan)

How would I know which kishan in the father table is the child xyz related to ?

This situation could have been avoided if mysql does not allow a foreign key to refer a part of the primary key .

Please answer what's the benefit of this scheme allowed by mysql ?


问:
Why an object is invisible?
I have a class. In this class I declare a a private variable private Agent agent;. In my class I have

```<code>private Thread controller = new Thread() {
...
}
</code>```

Within the above private thread I call getParameter which is a private method of the considered class. Within the getParameter I call one of the methods of the agent. As a result I get a NullPointerException. So, I conclude that agent is not visible from the getParameter.

Why is that? Can it be that the reason of that is that the getParameter is within the private Thread? And, if it is the case, how the described problem can be resolved?

ADDED

I realized that I need to be more specific. My code is organized like that:

```<code>public class GameWindow {
   ...
   private Agent agent;
   ...
   private Thread controller = new Thread() {
        public void run() {
           ...
           Agent agent = new Agent();
           ...
           parameter = getParameter();
        }
  }
  ...
  private String getParameter() {
     ...
     agent.someMethod();
     ...
  }
}
</code>```

ADDED 2
In the GameWindow I have:

```<code>public void startWindow() {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            controller.start();
        }
    });
}
</code>```

答:
The NullPointerException has nothing to do with visibility. You are probably calling the getParameter method of a null object. Your agent variable is declared, but not initialiazed. You may want to code something like:

```<code>private Agent agent;
private Thread controller = new Thread() {
    agent = new Agent();
    // ...
    agent.getParameter(); // should not throw a NullPointerException
}
</code>```

UPDATE AFTER CODE WAS ADDED

Your code has two definitions of agent. The first one in the class:

```<code>private Agent agent;
</code>```

And the second one inside your run() method:

```<code>Agent agent = new Agent();
</code>```

Your getParameter() method does not know the agent defined inside the run() method. It only knows the agent member of the class, which was not initialized. Your problem will be solved when you remove the second definition of agent:

```<code>public void run() {
       ...
       // Agent agent = new Agent();
       agent = new Agent(); // works fine: you are initiliazing the class member
       ...
       parameter = getParameter();
 }
</code>```

OLD UPDATE:
The NullPointerException is thrown inside the getParameter() method. So I understand your code is like the following:

```<code>private Something getParameter() {
    agent.someMethod(); // exception thrown here
}
</code>```

If this is your code, the problem remains the same: agent is not initialized. You must initialize it before calling any of its methods inside the getParameter() method.

ContentLicense: CC BY-SA 2.5

Title: Why an object is invisible?

Body:
I have a class. In this class I declare a a private variable private Agent agent;. In my class I have

private Thread controller = new Thread() {
...
}

Within the above private thread I call getParameter which is a private method of the considered class. Within the getParameter I call one of the methods of the agent. As a result I get a NullPointerException. So, I conclude that agent is not visible from the getParameter.

Why is that? Can it be that the reason of that is that the getParameter is within the private Thread? And, if it is the case, how the described problem can be resolved?

ADDED

I realized that I need to be more specific. My code is organized like that:

public class GameWindow {
   ...
   private Agent agent;
   ...
   private Thread controller = new Thread() {
        public void run() {
           ...
           Agent agent = new Agent();
           ...
           parameter = getParameter();
        }
  }
  ...
  private String getParameter() {
     ...
     agent.someMethod();
     ...
  }
}

ADDED 2
In the GameWindow I have:

public void startWindow() {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            controller.start();
        }
    });
}

Body:
The NullPointerException has nothing to do with visibility. You are probably calling the getParameter method of a null object. Your agent variable is declared, but not initialiazed. You may want to code something like:

private Agent agent;
private Thread controller = new Thread() {
    agent = new Agent();
    // ...
    agent.getParameter(); // should not throw a NullPointerException
}

UPDATE AFTER CODE WAS ADDED

Your code has two definitions of agent. The first one in the class:

private Agent agent;

And the second one inside your run() method:

Agent agent = new Agent();

Your getParameter() method does not know the agent defined inside the run() method. It only knows the agent member of the class, which was not initialized. Your problem will be solved when you remove the second definition of agent:

public void run() {
       ...
       // Agent agent = new Agent();
       agent = new Agent(); // works fine: you are initiliazing the class member
       ...
       parameter = getParameter();
 }

OLD UPDATE:
The NullPointerException is thrown inside the getParameter() method. So I understand your code is like the following:

private Something getParameter() {
    agent.someMethod(); // exception thrown here
}

If this is your code, the problem remains the same: agent is not initialized. You must initialize it before calling any of its methods inside the getParameter() method.


问:
how to remove fragment over an activity layout
I am really new to android development. I have created a simple main activity and add an icon on top left. Clicking it I can show a  blank fragment.on my screen replacing a layout which is loaded in onCreate method.  Now clicking  another icon I want to hide that fragment and load that layout again. How to do that?? any helps??
Below is  my code</p>

```<code> //part of oncreate where my layout is loaded
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            }

     // part of code when icon clicked and fragment is loaded
             FragmentManager fragmentManager = getFragmentManager();
             FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
               BlankFragment  frag = new BlankFragment();
             fragmentTransaction.replace(R.id.content_main, frag);
                        fragmentTransaction.commit();

                        //another nearby icon clicked
    //now i want to replace this fragment from content_main layout

    //what code to add??
</code>```

答:
If I got your question right, then  this is the right answer I guess.

```<code> //keep track of all fragments you add by tagging

 fragmentTransacaction.add(R.id.content, new FragA(), "first");

 //and when removeing
 Fragment f = getFragmentManager().findFragmentByTag("first");
 if(f!=null) fragmentTransac.remove(f);
 fragmentTransac.commit();
</code>```

I got this from here

Body:
I am really new to android development. I have created a simple main activity and add an icon on top left. Clicking it I can show a  blank fragment.on my screen replacing a layout which is loaded in onCreate method.  Now clicking  another icon I want to hide that fragment and load that layout again. How to do that?? any helps??
Below is  my code

 //part of oncreate where my layout is loaded
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            }

     // part of code when icon clicked and fragment is loaded
             FragmentManager fragmentManager = getFragmentManager();
             FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
               BlankFragment  frag = new BlankFragment();
             fragmentTransaction.replace(R.id.content_main, frag);
                        fragmentTransaction.commit();

                        //another nearby icon clicked
    //now i want to replace this fragment from content_main layout

    //what code to add??

Body:
If I got your question right, then  this is the right answer I guess.

 //keep track of all fragments you add by tagging

 fragmentTransacaction.add(R.id.content, new FragA(), "first");

 //and when removeing
 Fragment f = getFragmentManager().findFragmentByTag("first");
 if(f!=null) fragmentTransac.remove(f);
 fragmentTransac.commit();

I got this from here


问:
Check Linux distribution name
I have to get the Linux distribution name from a Python script. There is a dist method in the platform module:

```<code>import platform
platform.dist()
</code>```

But under my Arch Linux it returns:

```<code>>>> platform.dist()
('', '', '')
</code>```

Why? How can I get the name?

PS. I have to check whether the distribution is Debian-based.

Update: I found here Python site, that dist() is deprecated since 2.6.

```<code>>>> platform.linux_distribution()
('', '', '')
</code>```

答:
The reason because of which platform.linux_distribution does not identify some distributions is the non-standardized way distributions provide version-related information on themselves.

I've written a package called distro (now used by pip) which aims to replace distro.linux_distribution. It works on many distributions which might return weird or empty tuples when using platform.

https://github.com/nir0s/distro (distro, on pypi)

It provides a much more elaborate API to retrieve distribution related information.

```<code>$ python
Python 2.7.12 (default, Nov  7 2016, 11:55:55)
[GCC 6.2.1 20160830] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import distro
>>> distro.linux_distribution()
(u'Antergos Linux', '', u'ARCHCODE')
</code>```

By the way, platform.linux_distribution is to be removed in Python 3.7.

Title: Check Linux distribution name

Body:
I have to get the Linux distribution name from a Python script. There is a dist method in the platform module:

import platform
platform.dist()

But under my Arch Linux it returns:

>>> platform.dist()
('', '', '')

Why? How can I get the name?

PS. I have to check whether the distribution is Debian-based.

Update: I found here Python site, that dist() is deprecated since 2.6.

>>> platform.linux_distribution()
('', '', '')

Body:
The reason because of which platform.linux_distribution does not identify some distributions is the non-standardized way distributions provide version-related information on themselves.

I've written a package called distro (now used by pip) which aims to replace distro.linux_distribution. It works on many distributions which might return weird or empty tuples when using platform.

https://github.com/nir0s/distro (distro, on pypi)

It provides a much more elaborate API to retrieve distribution related information.

$ python
Python 2.7.12 (default, Nov  7 2016, 11:55:55)
[GCC 6.2.1 20160830] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import distro
>>> distro.linux_distribution()
(u'Antergos Linux', '', u'ARCHCODE')

By the way, platform.linux_distribution is to be removed in Python 3.7.

ContentLicense: CC BY-SA 4.0


问:
Find commits that modify file names matching a pattern in a GIT repository
I'd like to find commits in my code base that add video files to throw them out.
Is there a way to look for these files in git ?

For example let's say all videos have a filename ending with the extension .wmv ; I'd like to find all commits introducing these files and get rid of them with a fixup or something.

Any ideas ?

答:
You can try this:

```<code>git log --follow *.wmv
</code>```

this will list all commits (with hash) that modified wmv files.

Body:
You can try this:

git log --follow *.wmv

this will list all commits (with hash) that modified wmv files.


问:
How can I display my Interstitial by clicking on a new tab?
in my MainActivity onCreate im loading the Interstitial Ad like this:

```<code>AdRequest adRequest = new AdRequest.Builder().build();

mInterstitialAd = new InterstitialAd(MainActivity.this);
mInterstitialAd.setAdUnitId("MY ID");
mInterstitialAd.loadAd(adRequest);
</code>```

And I also have this code in my MainActivity:

```<code>    public void displayInterstitial() {

        mInterstitialAd.setAdListener(new AdListener() {
            public void onAdLoaded() {
                if (mInterstitialAd.isLoaded()) {
                    mInterstitialAd.show();
                }
            }
        });
    }
}
</code>```

Now if I try to say displayInterstitial(); in my fragment onCreateView like this:

```<code>public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView=inflater.inflate(R.layout.lustiges_layout,container,false);

    displayInterstitial();

    myGridView = (GridView)rootView.findViewById(R.id.gridView3);
    myGridView.setAdapter(new CustomGridAdapter(getActivity(), items3));

    return rootView;
}
</code>```

It says "cannot resolve methood 'displayInterstitial()'"
How can I show my Interstitial Ad when the Fragment opens?

答:
If MainActivity is parent activity of your fragment on which you want to call displayInterstitial(); method then you can do it in this way.

```<code>((MainActivity)getActivity()).displayInterstitial();
</code>```

Body:
in my MainActivity onCreate im loading the Interstitial Ad like this:

AdRequest adRequest = new AdRequest.Builder().build();

mInterstitialAd = new InterstitialAd(MainActivity.this);
mInterstitialAd.setAdUnitId("MY ID");
mInterstitialAd.loadAd(adRequest);

And I also have this code in my MainActivity:

    public void displayInterstitial() {

        mInterstitialAd.setAdListener(new AdListener() {
            public void onAdLoaded() {
                if (mInterstitialAd.isLoaded()) {
                    mInterstitialAd.show();
                }
            }
        });
    }
}

Now if I try to say displayInterstitial(); in my fragment onCreateView like this:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView=inflater.inflate(R.layout.lustiges_layout,container,false);

    displayInterstitial();

    myGridView = (GridView)rootView.findViewById(R.id.gridView3);
    myGridView.setAdapter(new CustomGridAdapter(getActivity(), items3));

    return rootView;
}

It says "cannot resolve methood 'displayInterstitial()'"
How can I show my Interstitial Ad when the Fragment opens?

Body:
If MainActivity is parent activity of your fragment on which you want to call displayInterstitial(); method then you can do it in this way.

((MainActivity)getActivity()).displayInterstitial();


问:
Unit testing async method: How to explicitly assert that the internal task was cancelled
I was recently writing an async method that calls a external long running async method so I decided to pass CancellationToken enabling cancellation. The method can be called concurrently.

Implementation has combined exponential backoff and timeout techniques described in Stephen Cleary's book Concurrency in C# Cookbook as follows;

```<code>/// <summary>
/// Sets bar
/// </summary>
/// <param name="cancellationToken">The cancellation token that cancels the operation</param>
/// <returns>A <see cref="Task"/> representing the task of setting bar value</returns>
/// <exception cref="OperationCanceledException">Is thrown when the task is cancelled via <paramref name="cancellationToken"/></exception>
/// <exception cref="TimeoutException">Is thrown when unable to get bar value due to time out</exception>
public async Task FooAsync(CancellationToken cancellationToken)
{
    TimeSpan delay = TimeSpan.FromMilliseconds(250);
    for (int i = 0; i < RetryLimit; i++)
    {
        if (i != 0)
        {
            await Task.Delay(delay, cancellationToken);
            delay += delay; // Exponential backoff
        }

        await semaphoreSlim.WaitAsync(cancellationToken); // Critical section is introduced for long running operation to prevent race condition

        using (CancellationTokenSource cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
        {
            cancellationTokenSource.CancelAfter(TimeSpan.FromMilliseconds(Timeout));
            CancellationToken linkedCancellationToken = cancellationTokenSource.Token;

            try
            {
                cancellationToken.ThrowIfCancellationRequested();
                bar = await barService.GetBarAsync(barId, linkedCancellationToken).ConfigureAwait(false);

                break;
            }
            catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
            {
                if (i == RetryLimit - 1)
                {
                    throw new TimeoutException("Unable to get bar, operation timed out!");
                }

                // Otherwise, exception is ignored. Will give it another try
            }
            finally
            {
                semaphoreSlim.Release();
            }
        }
    }
}
</code>```

I wonder if I should write a unit test that explicitly asserts that the internal task barService.GetBarAsync() is cancelled whenever FooAsync() is cancelled. If so how to implement it cleanly?

On top of that, should I ignore implementation details and just test what client/caller is concerned as described in method summary (bar is updated, cancel triggers OperationCanceledException, timeout triggers TimeoutException).

If not, should I get my feet wet and start implementing unit tests for following cases:

Testing it is thread-safe (monitor acquired only by single thread at a time)

Testing the retry mechanism

Testing the server is not flooded

Testing maybe even a regular exception is propagated to caller

答:
Thanks to Stephen Cleary for the nod to Polly retry.  Perhaps of interest to future readers, all the functionality in the original poster's code sample could now be built from ready-made Polly primitives which are already unit-tested:

Timeout policy for timeout by timing-out cancellation token (including combining with a user-supplied cancellation token)

Bulkhead policy for parallelization throttling/mutual exclusion

WaitAndRetry for retry, including cancellation during waits

PolicyWrap to combine.

All Polly policies are fully unit-tested, sync and async-compatible, thread-safe for concurrent executions, and have pass-through cancellation support.

So, the intention of the original code could be achieved something like:

```<code>Policy retry = Policy.Handle<WhateverExceptions>().WaitAndRetryAsync(RetryLimit, retryAttempt => TimeSpan.FromMilliseconds(250 * Math.Pow(2, retryAttempt)));
Policy mutex = Policy.BulkheadAsync(1);
Policy timeout = Policy.TimeoutAsync(/* define overall timeout */);

bar = await timeout.WrapAsync(retry).WrapAsync(mutex).ExecuteAsync(ct => barService.GetBarAsync(barId, ct), cancellationToken);
</code>```

I'll add some comments about unit-testing (the OP's original question) to the comments to Stephen's (much more relevant) answer to that.

Body:
I was recently writing an async method that calls a external long running async method so I decided to pass CancellationToken enabling cancellation. The method can be called concurrently.

Implementation has combined exponential backoff and timeout techniques described in Stephen Cleary's book Concurrency in C# Cookbook as follows;

///
/// Sets bar
///
/// <param name="cancellationToken">The cancellation token that cancels the operation</param>
/// <returns>A <see cref="Task"/> representing the task of setting bar value</returns>
/// <exception cref="OperationCanceledException">Is thrown when the task is cancelled via <paramref name="cancellationToken"/></exception>
/// <exception cref="TimeoutException">Is thrown when unable to get bar value due to time out</exception>
public async Task FooAsync(CancellationToken cancellationToken)
{
    TimeSpan delay = TimeSpan.FromMilliseconds(250);
    for (int i = 0; i < RetryLimit; i++)
    {
        if (i != 0)
        {
            await Task.Delay(delay, cancellationToken);
            delay += delay; // Exponential backoff
        }

        await semaphoreSlim.WaitAsync(cancellationToken); // Critical section is introduced for long running operation to prevent race condition

        using (CancellationTokenSource cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
        {
            cancellationTokenSource.CancelAfter(TimeSpan.FromMilliseconds(Timeout));
            CancellationToken linkedCancellationToken = cancellationTokenSource.Token;

            try
            {
                cancellationToken.ThrowIfCancellationRequested();
                bar = await barService.GetBarAsync(barId, linkedCancellationToken).ConfigureAwait(false);

                break;
            }
            catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
            {
                if (i == RetryLimit - 1)
                {
                    throw new TimeoutException("Unable to get bar, operation timed out!");
                }

                // Otherwise, exception is ignored. Will give it another try
            }
            finally
            {
                semaphoreSlim.Release();
            }
        }
    }
}

I wonder if I should write a unit test that explicitly asserts that the internal task barService.GetBarAsync() is cancelled whenever FooAsync() is cancelled. If so how to implement it cleanly?

On top of that, should I ignore implementation details and just test what client/caller is concerned as described in method summary (bar is updated, cancel triggers OperationCanceledException, timeout triggers TimeoutException).

If not, should I get my feet wet and start implementing unit tests for following cases:

Testing it is thread-safe (monitor acquired only by single thread at a time)

Testing the retry mechanism

Testing the server is not flooded

Testing maybe even a regular exception is propagated to caller

Body:
Thanks to Stephen Cleary for the nod to Polly retry.  Perhaps of interest to future readers, all the functionality in the original poster's code sample could now be built from ready-made Polly primitives which are already unit-tested:

Timeout policy for timeout by timing-out cancellation token (including combining with a user-supplied cancellation token)

Bulkhead policy for parallelization throttling/mutual exclusion

WaitAndRetry for retry, including cancellation during waits

PolicyWrap to combine.

All Polly policies are fully unit-tested, sync and async-compatible, thread-safe for concurrent executions, and have pass-through cancellation support.

So, the intention of the original code could be achieved something like:

Policy retry = Policy.Handle<WhateverExceptions>().WaitAndRetryAsync(RetryLimit, retryAttempt => TimeSpan.FromMilliseconds(250 * Math.Pow(2, retryAttempt)));
Policy mutex = Policy.BulkheadAsync(1);
Policy timeout = Policy.TimeoutAsync(/* define overall timeout */);

bar = await timeout.WrapAsync(retry).WrapAsync(mutex).ExecuteAsync(ct => barService.GetBarAsync(barId, ct), cancellationToken);

I'll add some comments about unit-testing (the OP's original question) to the comments to Stephen's (much more relevant) answer to that.


问:
WPF - ObservableCollection casting
I have a method named 'PersonsMeeting' that gets as parameter ObservableCollection of Person. Can I somehow deliver it an ObservableCollection of Employee ? what casting do I need ?

p.s - I don't want to get rid of the ObservableCollection type in the method since I'm using it's functionality.

```<code>public partial class MainWindow : Window
{
    public ObservableCollection<Employee> Emp { get; set; }

    public MainWindow()
    {
        Emp = new ObservableCollection<Employee>();

        InitializeComponent();
        PersonsMeeting(Emp); // How Do I Cast this ?!?!?!??
    }

    private void PersonsMeeting(ObservableCollection<Person> persons)
    {
        // ....
    }
}

public class Person{}
public class Employee : Person{}
</code>```

答:
Since you already know that every Employee is a Person, you can simply use Enumerable.Cast to cast the elements to the type needed:

    PersonsMeeting(Emp.Cast());

```<code>PersonsMeeting(new ObservableCollection<Person>(Emp.Cast<Person>()));
</code>```

But this will most likely not produce the results you expect since you're really creating a new ObservableCollection rather than utilizing the existing one.

Update 2

I notice that the PersonsMeeting method is private and that you're only ever calling it with an ObservableCollection<Employee>.

If that's the case, then you're trying to use an unnecessary abstraction in your private method. You can safely get rid of that and simply modify PersonsMeeting to take an ObservableCollection<Employee>.

The other option is to change the way your class is exposing its data. If you want to keep the abstraction, make your class look like:

```<code>public partial class MainWindow : Window
{
    private ReadOnlyObservableCollection<Person> _readOnlyEmp = null;
    private ObservableCollection<Person> _emp = new ObservableCollection<Person>;

    public ReadOnlyObservableCollection<Person> Emp
    {
        if(_readOnlyEmp = null)
            _readOnlyEmp = new ReadOnlyObservableCollection<Person>(_emp);

        return _readOnlyEmp;
    }

    public void AddEmployee(Employee e)
    {
        _emp.Add(e);
    }

    public void RemoveEmployee(Employee e)
    {
        _emp.Remove(e);
    }
}
</code>```

Title: WPF - ObservableCollection casting

Body:
I have a method named 'PersonsMeeting' that gets as parameter ObservableCollection of Person. Can I somehow deliver it an ObservableCollection of Employee ? what casting do I need ?

p.s - I don't want to get rid of the ObservableCollection type in the method since I'm using it's functionality.

public partial class MainWindow : Window
{
    public ObservableCollection<Employee> Emp { get; set; }

    public MainWindow()
    {
        Emp = new ObservableCollection<Employee>();

        InitializeComponent();
        PersonsMeeting(Emp); // How Do I Cast this ?!?!?!??
    }

    private void PersonsMeeting(ObservableCollection<Person> persons)
    {
        // ....
    }
}

public class Person{}
public class Employee : Person{}

Body:
Since you already know that every Employee is a Person, you can simply use Enumerable.Cast to cast the elements to the type needed:

    PersonsMeeting(Emp.Cast());

PersonsMeeting(new ObservableCollection<Person>(Emp.Cast<Person>()));

But this will most likely not produce the results you expect since you're really creating a new ObservableCollection rather than utilizing the existing one.

Update 2

I notice that the PersonsMeeting method is private and that you're only ever calling it with an ObservableCollection<Employee>.

If that's the case, then you're trying to use an unnecessary abstraction in your private method. You can safely get rid of that and simply modify PersonsMeeting to take an ObservableCollection<Employee>.

The other option is to change the way your class is exposing its data. If you want to keep the abstraction, make your class look like:

public partial class MainWindow : Window
{
    private ReadOnlyObservableCollection<Person> _readOnlyEmp = null;
    private ObservableCollection<Person> _emp = new ObservableCollection<Person>;

    public ReadOnlyObservableCollection<Person> Emp
    {
        if(_readOnlyEmp = null)
            _readOnlyEmp = new ReadOnlyObservableCollection<Person>(_emp);

        return _readOnlyEmp;
    }

    public void AddEmployee(Employee e)
    {
        _emp.Add(e);
    }

    public void RemoveEmployee(Employee e)
    {
        _emp.Remove(e);
    }
}


问:
Elastic_Grid | "Uncaught TypeError: Cannot read property 'toLowerCase' of undefined"
Putting together a personal & project portfolio, and trying to use Vu Khanh Truong's "elastic_grid" jQuery plugin for the actual portfolio. You can view it here.  The problem is that it seems to be causing the following errors on my page:

1) I have a header for the portfolio section, and when I load the page with the plugin running, it makes my header disappear.

2) There're supposed to be filtering buttons that appear based on different tags used to categorize your content, and those don't appear.

3) It loads the preview thumbnail images for the different categories I'm using, but when I click on them, it doesn't load the modal with the full-size images (and descriptions) as it's supposed to.

When I open the console in Chrome, I get this error:

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

I tried creating a JSFiddle to post to replicate the problem I'm having, but I guess JSFiddle doesn't let you use certain scripts or something? 'Cuz whenever I try to include all of the scripts I'm using on the page, it gives me MIME type errors in the console.

I've installed & am using the plugin according to the documentation, and I'm not the best at de-constructing Javascript, so I can't figure out why I'm getting these errors. :P If anybody can help, I would appreciate it.

HTML

```<code><!-- "DOCTYPE" Declaration -->
<!DOCTYPE HTML>

<!-- Start HTML -->
<html lang="en">

    <!-- Start HTML Header -->
    <head>
        <title>My Portfolio</title>

        <!-- Stylesheets -->
        <link href="bootstrap/css/bootstrap.css" rel="stylesheet" type="text/css" /><!-- Bootstrap.css -->
        <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css" /><!-- Font-Awesome -->
        <link href="elastic/css/elastic_grid.min.css" rel="stylesheet" type="text/css" /><!-- Elastic CSS -->
        <link href="mycss.css" rel="stylesheet" type="text/css" /><!-- Custom CSS -->

        <!--Javascripts -->
        <script src="jquery/jquery.js"></script><!-- jQuery -->
        <script src="bootstrap/js/bootstrap.js"></script><!-- Bootstrap jQuery -->
        <script src="jquery/jquery.scrollTo.js"></script><!-- "scrollTo" Smooth Scrolling jQuery plugin -->
        <!-- Elastic -->
        <script src="elastic/js/modernizr.custom.js"></script><!-- Modernizr -->
        <script src="elastic/js/classie.js"></script><!-- Classie -->
        <script src="elastic/js/elastic_grid.min.js"></script> <!-- Elastic -->
        <!-- Initializing & Customizing JS -->
        <script src="js/my.js"></script><!-- Personal Javascript for initializing & using Javascript & jQuery plugins -->

    </head>

    <!-- Start Page Body -->
    <body data-spy="scroll" data-target="#topNav" data-offset="75">

        <!-- Start Navigation -->
        <nav id="topNav" class="navbar navbar-inverse navbar-fixed-top" role="navigation">

            <div class="navbar-header">

                <div class="navbar-collapse collapse " id="myNavbar" role="navigation">

                <!-- Site Logo -->
                <a href="#home"><img src="imgs/logo_ph.png" alt="Logo placeholder" class="navbar-brand img-responsive" /></a>

                <!-- Start Navbar Links -->
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>

                <ul class="nav navbar-nav navbar-right nav-pills">
                    <li role="presentation"><a href="#about">About Me</a></li>
                    <li role="presentation"><a href="#portfolio">Portfolio</a></li>
                    <li role="presentation"><a href="#contact">Contact Me</a></li>
                    <li role="presentation"><a href="#footer"><i class="text-center fa fa-angle-double-down fa-lg"></i></a></li>
                </ul>

                </div>
            </div>
        </nav>
        <!-- End Navigation -->

        <!-- Start Site Container -->
        <div class="container container-fluid" id="home">

            <br><br>

            <!-- Start "About Me" Section -->
            <section id="about" class="secB center-block">
                <h1 class="text-center">About Me</h1>
                <br><br>
                <img class="me-left" src="imgs/me-1.png" alt="Me" />
                <p>This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
<img class="me-right" src="imgs/me-1.png" alt="Me" />
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text </p>
            <div class="clearfix"></div>
            </section>
            <!-- End "About Me" Section -->

            <!-- Start "Portfolio" Section -->
            <section id="portfolio" class="secA center-block">
                <h1 class="text-center">Sample Work</h1>
                <br><br>
                <div id="portfolio">

                    <script type="text/javascript">

    $(function(){

        $("#portfolio").elastic_grid({
            'filterEffect': 'fallperspective',
            'hoverDirection': true,
            'hoverDelay': 0,
            'hoverInverse': false,
            'expandingSpeed': 500,
            'expandingHeight': 500,
                'items' :
                [
                    {
                        'title'         : 'Covers',
                        'description'   : ' A collection of media covers I\'ve designed',
                        'thumbnail'     : ['imgs/covers/s/1.jpg', 'imgs/covers/s/2.jpg'],
                        'large'         : ['imgs/covers/l/1.jpg', 'imgs/covers/l/2.jpg'],
                        'button_list'   :
                        [
                            { 'title':'Demo', 'url' : 'http://bonchen.net/' },
                            { 'title':'Download', 'url':'http://porfolio.bonchen.net/'}
                        ],
                        'tags'          : ['Covers']
                    },
                     {
                        'title'         : 'Logos',
                        'description'   : ' A collection of business logos I\'ve designed',
                        'thumbnail'     : ['imgs/logos/s/1.jpg', 'imgs/logos/s/2.jpg'],
                        'large'         : ['imgs/logos/l/1.jpg', 'imgs/logos/l/2.jpg'],
                        'button_list'   :
                        [
                            { 'title':'Demo', 'url' : 'http://bonchen.net/' },
                            { 'title':'Download', 'url':'http://porfolio.bonchen.net/'}
                        ],
                        'tags'          : ['Logos']
                    }
                ]
        });
    });
</script

                </div>
            </section>
            <!-- End "Portfolio" Section -->

            <!-- Start "Contact" Section -->
            <section id="contact" class="secB center-block">
            <h1 class="text-center">Hire Me!</h1>
            <h5 class="text-center">...or you know...just HMU to chat. :P</h5>
                <br><br>
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
                </section>
            <!-- End "Contact" Section -->

        <!-- End Site Container -->
        </div>

            <!-- Start "Footer" Section -->
                <footer class="footer center-block" id="footer">

                    <!-- Footer Content-->
                    <div class="footer-content">

                        <!-- Footer text -->
                        <div class="footer-text text-center">
                            <span class="text-primary">Port-FAUX-lio</span> | © Husayn Muhammad 2016
                        </div>

                        <!-- Social Media -->
                        <div class="footer-icons-box text-center">
                            <div class="fa-stack fa-2x sm-icon">
                                <a href="mailto:cloud4xL@gmail.com">
                                    <i class="fa fa-circle fa-stack-2x"></i>
                                    <i class="fa fa-envelope fa-stack-1x fa-inverse"></i>
                                </a>
                            </div>
                            <div class="fa-stack fa-2x sm-icon">
                                <a href="http://twitter.com/cloud4xL" target="_blank">
                                    <i class="fa fa-circle fa-stack-2x"></i>
                                    <i class="fa fa-twitter fa-stack-1x fa-inverse"></i>
                                </a>
                            </div>
                            <div class="fa-stack fa-2x sm-icon">
                                <a href="http://freecodecamp.com/cloud4xL" target="_blank">
                                    <i class="fa fa-circle fa-stack-2x"></i>
                                    <i class="fa fa-free-code-camp fa-stack-1x fa-inverse"></i>
                                </a>
                            </div>
                            <div class="fa-stack fa-2x sm-icon">
                                <a href="https://www.linkedin.com/in/husayn-muhammad-040614106?trk=nav_responsive_tab_profile" target="_blank">
                                    <i class="fa fa-circle fa-stack-2x"></i>
                                    <i class="fa fa-linkedin fa-stack-1x fa-inverse"></i>
                                </a>
                            </div>
                        </div>

                        <div class="clearfix"></div>

                    </div>
                </footer>
                <!-- End "Footer" Section -->

    <!-- End Body -->
    </body>

    <!-- End HTML -->
</html>
</code>```

CSS

```<code>body {

    background-color: #e1e1e1;
    min-width: 430px !important;

}

/****** TOP NAVIGATION STYLES ******/

.navbar {

    background-color: #f2f2f2 !important; /*#190c03*/
    box-shadow: 0 1px 2px 2px rgba(0, 0, 0, 0.5);

}

.navbar-brand {

    float: left !important;
    height: auto !important;
    transform: translateX(0);
    opacity: 1;
    transition: transform 0.4s, opacity 0.4s;

}

.navbar-brand:hover {

    transform: translateX(25px);
    opacity: 0;
    transition: transform 0.4s, opacity 0.4s;

}

.navbar-right {

    margin-right: 15px !important;

}

.navbar-header {

    position: relative !important;
    float: left !important;
    width: 100% !important;

}

.navbar-toggle {

    /* margin-top: 0px !important; */

}

.navbar ul {

    float: right !important;

}

.nav-pills > li {

    border: 1px solid rgba(0, 0, 0, 0.4);
    background-color: #d8661A;
    border-radius: 5px;
    margin-top: 3.5%;
    margin-right: 5px;
    box-shadow: 0 4px 2px 0 rgba(0, 0, 0, 0.4);
    transform: scale(1, 1);
    transition: box-shadow 0.4s, transform 0.4s;

}

.nav-pills > li:hover {

    transform: translateY(-5px);
    border: 1px solid rgba(0, 0, 0, 0.7);
    transition: transform 0.4s, border 0.4s;

}

.navbar-inverse .navbar-nav > .active > a {

    background-color: transparent !important;

}

.nav-pills > li.active {

    transform: translateY(-5px);
    height: 50%;
    border: 1px solid rgba(0, 0, 0, 0.7);
    color: white !important;
    background-color: #337ab7 !important;
    transition: transform 0.4s, color 0.4s, background-color 0.4s;

}

.nav-pills > li a {

    color: white !important;
    border-bottom: 1px solid transparent !important;
    transition: color 0.4s, border-bottom 0.4s !important;

}

.nav-pills > li.active > a:hover {

    color: white !important;

}

/****** HEADER IMAGE STYLES ******/

.mast {

    width: auto;
    position: relative;
    height: 600px;
    margin-top: 7%;
    margin-bottom: 2%;
    /* box-shadow: 0 4px 2px 0px rgba(0, 0, 0, 0.7); */

}

/****** <SECTION> STYLES ******/

.secA, .secB {

    width: auto;
    min-height: 400px;
    height: auto;
    padding: 4% 10% 8%;
    border-left: 1px solid rgba(255, 255, 255, 0.1);
    border-right: 1px solid rgba(255, 255, 255, 0.1);
}

.secA {

    background-color: rgba(0, 0, 0, 0.4);
    overflow: auto !important;
    border-top: 1px solid rgba(0, 0, 0, 0.2);
    border-bottom: 1px solid rgba(0, 0, 0, 0.2);

}

.secB {

    background-color: rgba(0, 0, 0, 0.2);

}

/****** ABOUT ME SECTION STYLES ******/

.me-left {

    float: left;
    max-height: 200px;
    border: 5px solid black;
    border-radius: 50%;
    padding-left: 8px;
    margin: 10px 10px 10px 0px;
    background-color: white;
    transform: scaleX(-1);

}

.me-right {

    float: right;
    max-height: 200px;
    border: 5px solid black;
    border-radius: 50%;
    padding-left: 8px;
    margin: 10px 0px 10px 10px;
    background-color: white

}

/*********************************

**********sdFilterMe CSS**********

#sdfm-wrapper img,
.sdfm-overlay {

    //Define the WIDTH of sdFilterMe Images
    width: 200px !important;
    //Define the HEIGHT of sdFilterMe Images
    height: 200px !important;
    border-radius: 7px;
    overflow: hidden !important;

}

.sdfm-inner-wrapper {

    border-radius: 10px;
    margin: 5px !important;

}

.sdfm-overlay {

    background-color: rgba(0, 0, 0, 0.7) !important;
    color: white !important;
    font-size: 0.35em !important;
    text-overflow: clip !important;

}

.sdfm-overlay span {

    padding: 5% !important;
    margin: 8% auto !important;
    max-width: 85% !important;
    height: auto !important;
    word-wrap: break-word !important;
    border-radius: 2px !important;

}

*********************************/

/****** FOOTER STYLES ******/

.footer {

    width: auto;
    /* min-height: 150px; */
    /*margin-bottom: 5px !important;*/
    background-color: #1b1d1e;
    padding: 1.5% 5%;
    z-index: 3;
    border-top: 1px solid red;

}

.footer-content {

    /* border: 1px solid yellow; */
    margin: 0 auto;
    padding: 10px;
    display: flex;
    flex-flow: row wrap;
    justify-content: center;

}

.footer-text {

    font-size: 1.5em;
    font-weight: normal;
    color: rgba(255, 255, 255, 0.7);
    /* border: 1px solid white; */
    width: auto;
    padding: 5px;
    margin-left: 25px;
    margin-right: 25px;
    margin-top: 0.73%;
    display: flex;
    flex-flow: row wrap;
    align-self: flex-start;
    justify-content: center;

}

.footer-icons-box {

    /* border: 1px solid red; */
    width: auto;
    padding: auto;
    margin-left: 25px;
    margin-right: 25px;
    display: flex;
    flex-flow: row wrap;
    align-self: flex-end;

}

.sm-icon {

    display: inline-block;
    text-align: right;

}

.fa-circle {

    color: rgba(255, 255, 255, 0.9);
    transition: all 0.4s;

}

.footer-icons-box .fa-envelope,
.fa-twitter, .fa-free-code-camp, .fa-linkedin {

    color: #1b1d1e;
    transform: scale(1, 1);
    transition: all 0.4s;

}

.footer-icons-box .fa-envelope:hover,
.fa-twitter:hover, .fa-free-code-camp:hover,
.fa-linkedin:hover  {

    color: #337ab7 !important;
    transform: scale(0.8, 0.8);
    transition: all 0.4s;

}
</code>```

JS (from the "my.js" file I referenced in the HTML section above)

```<code>/* Begin 'scrollTo' */

$(document).ready(function() {
    $('#topNav a').click(function() {
        $.scrollTo(this.hash, 1200, {offset: -70}, {easing:'swing'});
        return false;
    });
});

/* End 'scrollTo' */
</code>```

答:
In Elastic_grid.js search for 'if(numOfTag > 1){
         Creating the "Everything" option in the menu:
           createList("config.something");
            $.each(itemsByTags, function(I, i) {
                createList(I)
            })'

and change the line in bold with createList("All");

Body:
Putting together a personal & project portfolio, and trying to use Vu Khanh Truong's "elastic_grid" jQuery plugin for the actual portfolio. You can view it here.  The problem is that it seems to be causing the following errors on my page:

1) I have a header for the portfolio section, and when I load the page with the plugin running, it makes my header disappear.

2) There're supposed to be filtering buttons that appear based on different tags used to categorize your content, and those don't appear.

3) It loads the preview thumbnail images for the different categories I'm using, but when I click on them, it doesn't load the modal with the full-size images (and descriptions) as it's supposed to.

When I open the console in Chrome, I get this error:

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

I tried creating a JSFiddle to post to replicate the problem I'm having, but I guess JSFiddle doesn't let you use certain scripts or something? 'Cuz whenever I try to include all of the scripts I'm using on the page, it gives me MIME type errors in the console.

I've installed & am using the plugin according to the documentation, and I'm not the best at de-constructing Javascript, so I can't figure out why I'm getting these errors. :P If anybody can help, I would appreciate it.

HTML

<!DOCTYPE HTML>

        <title>My Portfolio</title>

        <link href="bootstrap/css/bootstrap.css" rel="stylesheet" type="text/css" />
        <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
        <link href="elastic/css/elastic_grid.min.css" rel="stylesheet" type="text/css" />
        <link href="mycss.css" rel="stylesheet" type="text/css" />

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

                </button>

About Me

Portfolio

Contact Me

About Me

This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text

This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text

Sample Work

Hire Me!

...or you know...just HMU to chat. :P

This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text

                            Port-FAUX-lio | © Husayn Muhammad 2016

CSS

body {

    background-color: #e1e1e1;
    min-width: 430px !important;

}

/****** TOP NAVIGATION STYLES ******/

.navbar {

    background-color: #f2f2f2 !important; /*#190c03*/
    box-shadow: 0 1px 2px 2px rgba(0, 0, 0, 0.5);

}

.navbar-brand {

    float: left !important;
    height: auto !important;
    transform: translateX(0);
    opacity: 1;
    transition: transform 0.4s, opacity 0.4s;

}

.navbar-brand:hover {

    transform: translateX(25px);
    opacity: 0;
    transition: transform 0.4s, opacity 0.4s;

}

.navbar-right {

    margin-right: 15px !important;

}

.navbar-header {

    position: relative !important;
    float: left !important;
    width: 100% !important;

}

.navbar-toggle {

    /* margin-top: 0px !important; */

}

.navbar ul {

    float: right !important;

}

.nav-pills > li {

    border: 1px solid rgba(0, 0, 0, 0.4);
    background-color: #d8661A;
    border-radius: 5px;
    margin-top: 3.5%;
    margin-right: 5px;
    box-shadow: 0 4px 2px 0 rgba(0, 0, 0, 0.4);
    transform: scale(1, 1);
    transition: box-shadow 0.4s, transform 0.4s;

}

.nav-pills > li:hover {

    transform: translateY(-5px);
    border: 1px solid rgba(0, 0, 0, 0.7);
    transition: transform 0.4s, border 0.4s;

}

.navbar-inverse .navbar-nav > .active > a {

    background-color: transparent !important;

}

.nav-pills > li.active {

    transform: translateY(-5px);
    height: 50%;
    border: 1px solid rgba(0, 0, 0, 0.7);
    color: white !important;
    background-color: #337ab7 !important;
    transition: transform 0.4s, color 0.4s, background-color 0.4s;

}

.nav-pills > li a {

    color: white !important;
    border-bottom: 1px solid transparent !important;
    transition: color 0.4s, border-bottom 0.4s !important;

}

.nav-pills > li.active > a:hover {

    color: white !important;

}

/****** HEADER IMAGE STYLES ******/

.mast {

    width: auto;
    position: relative;
    height: 600px;
    margin-top: 7%;
    margin-bottom: 2%;
    /* box-shadow: 0 4px 2px 0px rgba(0, 0, 0, 0.7); */

}

/******
 STYLES ******/

.secA, .secB {

    width: auto;
    min-height: 400px;
    height: auto;
    padding: 4% 10% 8%;
    border-left: 1px solid rgba(255, 255, 255, 0.1);
    border-right: 1px solid rgba(255, 255, 255, 0.1);
}

.secA {

    background-color: rgba(0, 0, 0, 0.4);
    overflow: auto !important;
    border-top: 1px solid rgba(0, 0, 0, 0.2);
    border-bottom: 1px solid rgba(0, 0, 0, 0.2);

}

.secB {

    background-color: rgba(0, 0, 0, 0.2);

}

/****** ABOUT ME SECTION STYLES ******/

.me-left {

    float: left;
    max-height: 200px;
    border: 5px solid black;
    border-radius: 50%;
    padding-left: 8px;
    margin: 10px 10px 10px 0px;
    background-color: white;
    transform: scaleX(-1);

}

.me-right {

    float: right;
    max-height: 200px;
    border: 5px solid black;
    border-radius: 50%;
    padding-left: 8px;
    margin: 10px 0px 10px 10px;
    background-color: white

}

/*********************************

**********sdFilterMe CSS**********

#sdfm-wrapper img,
.sdfm-overlay {

    //Define the WIDTH of sdFilterMe Images
    width: 200px !important;
    //Define the HEIGHT of sdFilterMe Images
    height: 200px !important;
    border-radius: 7px;
    overflow: hidden !important;

}

.sdfm-inner-wrapper {

    border-radius: 10px;
    margin: 5px !important;

}

.sdfm-overlay {

    background-color: rgba(0, 0, 0, 0.7) !important;
    color: white !important;
    font-size: 0.35em !important;
    text-overflow: clip !important;

}

.sdfm-overlay span {

    padding: 5% !important;
    margin: 8% auto !important;
    max-width: 85% !important;
    height: auto !important;
    word-wrap: break-word !important;
    border-radius: 2px !important;

}

*********************************/

/****** FOOTER STYLES ******/

.footer {

    width: auto;
    /* min-height: 150px; */
    /*margin-bottom: 5px !important;*/
    background-color: #1b1d1e;
    padding: 1.5% 5%;
    z-index: 3;
    border-top: 1px solid red;

}

.footer-content {

    /* border: 1px solid yellow; */
    margin: 0 auto;
    padding: 10px;
    display: flex;
    flex-flow: row wrap;
    justify-content: center;

}

.footer-text {

    font-size: 1.5em;
    font-weight: normal;
    color: rgba(255, 255, 255, 0.7);
    /* border: 1px solid white; */
    width: auto;
    padding: 5px;
    margin-left: 25px;
    margin-right: 25px;
    margin-top: 0.73%;
    display: flex;
    flex-flow: row wrap;
    align-self: flex-start;
    justify-content: center;

}

.footer-icons-box {

    /* border: 1px solid red; */
    width: auto;
    padding: auto;
    margin-left: 25px;
    margin-right: 25px;
    display: flex;
    flex-flow: row wrap;
    align-self: flex-end;

}

.sm-icon {

    display: inline-block;
    text-align: right;

}

.fa-circle {

    color: rgba(255, 255, 255, 0.9);
    transition: all 0.4s;

}

.footer-icons-box .fa-envelope,
.fa-twitter, .fa-free-code-camp, .fa-linkedin {

    color: #1b1d1e;
    transform: scale(1, 1);
    transition: all 0.4s;

}

.footer-icons-box .fa-envelope:hover,
.fa-twitter:hover, .fa-free-code-camp:hover,
.fa-linkedin:hover  {

    color: #337ab7 !important;
    transform: scale(0.8, 0.8);
    transition: all 0.4s;

}

JS (from the "my.js" file I referenced in the HTML section above)

/* Begin 'scrollTo' */

$(document).ready(function() {
    $('#topNav a').click(function() {
        $.scrollTo(this.hash, 1200, {offset: -70}, {easing:'swing'});
        return false;
    });
});

/* End 'scrollTo' */


问:
PostrgeSQL + Django on Debian 8
Good day, I've got a Debian 8 server where I'm running a few of django test apps and I want to connect them to PostgreSQL instead of SQLite. Can you please help me with this problem ?

this is settings.py of my project (DATABASES block)

```<code>DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': 'testProject',
    'USER': 'admin',
    'PASSWORD': 'adminPassword',
    'HOST': 'localhost',
    'PORT': '',
 }
}
</code>```

I think I've installed it successfully by

sudo apt-get install python-pip python-dev libpq-dev postgresql postgresql-contrib

and

```<code>CREATE DATABASE testProject;
CREATE USER admin WITH PASSWORD 'adminPassword';
GRANT ALL PRIVILEGES ON DATABASE testProject TO admin;
</code>```

And when I try to access page, It shows "server refused connection" or something like that.

Thank you guys and have a nice day !

答:
Have you migrated your database?

python manage.py makemigrations
 python manage.py migrate

Title: PostrgeSQL + Django on Debian 8

Body:
Good day, I've got a Debian 8 server where I'm running a few of django test apps and I want to connect them to PostgreSQL instead of SQLite. Can you please help me with this problem ?

this is settings.py of my project (DATABASES block)

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': 'testProject',
    'USER': 'admin',
    'PASSWORD': 'adminPassword',
    'HOST': 'localhost',
    'PORT': '',
 }
}

I think I've installed it successfully by

sudo apt-get install python-pip python-dev libpq-dev postgresql postgresql-contrib

and

CREATE DATABASE testProject;
CREATE USER admin WITH PASSWORD 'adminPassword';
GRANT ALL PRIVILEGES ON DATABASE testProject TO admin;

And when I try to access page, It shows "server refused connection" or something like that.

Thank you guys and have a nice day !


问:
Test single linked list for cycle
Is there a way to check if a single-linked list contains cycles for linear time without copying and modifying the list?

I thought we could try to sort this list topologically. If cannot there is somr cycle... But it seems it's not gonna work.

答:
You can do it in constant space without altering the array.

The method is known as Floyd's cycle-finding algorithm. It is based on the idea of going through the list with two pointers moving at different speeds. Eventually, if and only if the list contains a cycle, the pointers will meet. Also, the algorithm finds the point where the loop starts. Check the provided link for more details.

Title: Test single linked list for cycle


问:
Swift collectionViewCells are not showing
I have got this Swift code
`

```<code>let cellId="cellId"

class FeedController: UICollectionViewController{
override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.title = "Centill"

    collectionView?.reloadData()
    collectionView?.backgroundColor = UIColor(white: 0.95, alpha: 1)
    collectionView?.register(FeedCell.self, forCellWithReuseIdentifier: cellId)
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 3
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell=collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath);
    cell.backgroundColor = .yellow
    return cell
}

}

class FeedCell: UICollectionViewCell {

override init(frame: CGRect){
    super.init(frame: frame)

    setupViews()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
func setupViews(){
    backgroundColor = .yellow
}
}
</code>```

`
But unfortunately my cells are not showing.It only shows navigation bar and background color.what may be the problem with my code?

答:
You have to provide the size for collection view cell. add the below code snippet</p>

```<code>func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    // calculate and return the height
}
</code>```

Body:
I have got this Swift code
`

let cellId="cellId"

class FeedController: UICollectionViewController{
override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.title = "Centill"

    collectionView?.reloadData()
    collectionView?.backgroundColor = UIColor(white: 0.95, alpha: 1)
    collectionView?.register(FeedCell.self, forCellWithReuseIdentifier: cellId)
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 3
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell=collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath);
    cell.backgroundColor = .yellow
    return cell
}

}

class FeedCell: UICollectionViewCell {

override init(frame: CGRect){
    super.init(frame: frame)

    setupViews()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
func setupViews(){
    backgroundColor = .yellow
}
}

`
But unfortunately my cells are not showing.It only shows navigation bar and background color.what may be the problem with my code?

Body:
You have to provide the size for collection view cell. add the below code snippet

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    // calculate and return the height
}


问:
Are password upper/lower/number/symbol rules pointless with salted passwords
I'm working on a basic password system using the password_hash function, and was wondering about the need for the familiar 'Choose a password with uppercase, lowercase, number and symbol' rules.

PHP's password_hash automatically generates a strong random salt, adds it to the password and hashes the result. Then it outputs a final string that has three sections:

The algorithm used and number of times it encoded the data

The random salt

The resulting hash

These sections are concatenated into a single string:

For example a password 'password' is processed as follows:

```<code>$password = 'password';
//using password_hash with Blowfish encryption
    $hashtext = password_hash($password, PASSWORD_BCRYPT);

//user tries to log in with password $login
//which is hashed with the same encoder and salt as contained in $hashtext
if (password_verify ($login , $hashtext )) {
        echo 'Password good';
    }else {
        echo 'Wrong password';
    }
</code>```

Assume that the $hashtext is stored in a database which later is hacked so that this is read and the encoding type and salt is known. Is the strength of the security now based solely on the strength of the password? ie the hacker sets up a function with the same encoder and salt value and runs through a dictionary of possible passwords until the resultant output is the same as $hashtext, confirming that the dictionary value being checked is the original password.

I assume that the randomness and complexity of the salt alone makes this process probably impractical, but would also making the original password p@55Word really add much to the security?

Yes, I realise that those are terrible choices for passwords!

Any help would be appreciated!

Many thanks,
Kw

答:
Salting, key-stretching, and password complexity rules have their own purposes and are not related to each other. The password_hash() function...

adds a salt, to prevent the usage of rainbow-tables

makes the password hashing slow, so brute-forcing becomes much more expensive

➽ makes sure, that there is no easier way to find the plaintext password, than with brute-forcing.

All these measures won't help if a user chooses a very weak password like 1234, because this is one of the first combinations an attacker will ever test. That's why password complexity rules where invented, in the hope that the users will choose stronger passwords.

This leads to the question, if such password complexity rules really make the passwords stronger (but this is independend of questions about hashing techniques). Here the discussion becomes a bit opinion based.

It is my own opinion, that complex rules will even decrease password security, because humans can't remember tons of strong passwords, and because they can interfere with good password schemes. People can get very inventive to circumvent such rules, the password Password-2017 will match most rules but is of course a very weak one. So my advice is to enforce only those two rules:

Require a minimum length of 8 characters for a password.

Make a list of the most common passwords and reject them. The minimum length will already rule out a lot of those passwords.

Body:
I'm working on a basic password system using the password_hash function, and was wondering about the need for the familiar 'Choose a password with uppercase, lowercase, number and symbol' rules.

PHP's password_hash automatically generates a strong random salt, adds it to the password and hashes the result. Then it outputs a final string that has three sections:

The algorithm used and number of times it encoded the data

The random salt

The resulting hash

These sections are concatenated into a single string:

For example a password 'password' is processed as follows:

$password = 'password';
//using password_hash with Blowfish encryption
    $hashtext = password_hash($password, PASSWORD_BCRYPT);

//user tries to log in with password $login
//which is hashed with the same encoder and salt as contained in $hashtext
if (password_verify ($login , $hashtext )) {
        echo 'Password good';
    }else {
        echo 'Wrong password';
    }

Assume that the $hashtext is stored in a database which later is hacked so that this is read and the encoding type and salt is known. Is the strength of the security now based solely on the strength of the password? ie the hacker sets up a function with the same encoder and salt value and runs through a dictionary of possible passwords until the resultant output is the same as $hashtext, confirming that the dictionary value being checked is the original password.

I assume that the randomness and complexity of the salt alone makes this process probably impractical, but would also making the original password p@55Word really add much to the security?

Yes, I realise that those are terrible choices for passwords!

Any help would be appreciated!

Many thanks,
Kw


问:
Neo4j - Can't use aggregate functions inside of aggregate functions
everyone! I have a Neo4j database which contains information about visitors who visit a number of checkpoints at specific moments of time. visitors, visits and checkpoints are represented as nodes.

Each visitor is identified by his/her device MAC address, each checkpoint has a unique id.

Each visit node contains an EnterTime property, which is the time (num of millisec since 1970) when the visitor with some specific MAC address is first noticed near the respective checkpoint.

Note: the duration of a visit should be calculated as the difference between EnterTime of the next visit and the EnterTime of this visit.

My goal is to find some statistics about the visits, for example,
1) the average time of a visit by a specific visitor,
2) the average time of a visit to a specific store,
3) the most popular store (i. e. the store with the longest TOTAL time of visits
4) the most popular store (i. e. the store with the longest AVERAGE time of visits) etc.

The database is created with this cypher query:

```<code>//Create visitors:
CREATE (Visitor1: Visitor {MAC:'00:0a:95:9d:68:16'})
CREATE (Visitor2: Visitor {MAC:'00:0a:95:9d:68:17'})
CREATE (Visitor3: Visitor {MAC:'00:0a:95:9d:68:18'})

//Create CheckPoints:
CREATE (CheckPoint1: CheckPoint {CheckPointId: 1})
CREATE (CheckPoint2: CheckPoint {CheckPointId: 2})
CREATE (CheckPoint3: CheckPoint {CheckPointId: 3})
CREATE (CheckPoint4: CheckPoint {CheckPointId: 4})
CREATE (CheckPoint5: CheckPoint {CheckPointId: 5})

//Create visits:
//by visitor 1:
CREATE  (Visitor1)-[:MAKES]->(Visit1: Visit {EnterTime: 1488358800000})-[:TO]->(CheckPoint1)
CREATE  (Visitor1)-[:MAKES]->(Visit2: Visit {EnterTime: 1488359400000})-[:TO]->(CheckPoint2)
CREATE  (Visitor1)-[:MAKES]->(Visit3: Visit {EnterTime: 1488361200000})-[:TO]->(CheckPoint3)
CREATE  (Visitor1)-[:MAKES]->(Visit4: Visit {EnterTime: 1488363600000})-[:TO]->(CheckPoint4)
CREATE  (Visitor1)-[:MAKES]->(Visit5: Visit {EnterTime: 1488364800000})-[:TO]->(CheckPoint5)
CREATE  (Visitor1)-[:MAKES]->(Visit6: Visit {EnterTime: 1488365400000})-[:TO]->(CheckPoint1)

//by visitor 2:
CREATE  (Visitor2)-[:MAKES]->(Visit7: Visit {EnterTime: 1488358800000})-[:TO]->(CheckPoint1)
CREATE  (Visitor2)-[:MAKES]->(Visit8: Visit {EnterTime: 1488360300000})-[:TO]->(CheckPoint4)
CREATE  (Visitor2)-[:MAKES]->(Visit9: Visit {EnterTime: 1488362400000})-[:TO]->(CheckPoint2)
CREATE  (Visitor2)-[:MAKES]->(Visit10: Visit {EnterTime: 1488363000000})-[:TO]->(CheckPoint1)

//by visitor 3:
CREATE  (Visitor3)-[:MAKES]->(Visit11: Visit {EnterTime: 1488353820000})-[:TO]->(CheckPoint1)
CREATE  (Visitor3)-[:MAKES]->(Visit12: Visit {EnterTime: 1488354600000})-[:TO]->(CheckPoint4)
CREATE  (Visitor3)-[:MAKES]->(Visit13: Visit {EnterTime: 1488358200000})-[:TO]->(CheckPoint3)
CREATE  (Visitor3)-[:MAKES]->(Visit14: Visit {EnterTime: 1488359700000})-[:TO]->(CheckPoint1)
</code>```

Please, help me write the queries 1 – 4 correctly.
So far, I have this query, which outputs the visit duration to each checkpoint by a specific visitor (it works correctly):

```<code>match (vr: Visitor {MAC: '00:0a:95:9d:68:16'})-->(v1: Visit)-->(cp1: CheckPoint)
optional match (vr: Visitor {MAC: '00:0a:95:9d:68:16'})-->(v2: Visit)-->(cp2: CheckPoint)
where v2.EnterTime > v1.EnterTime
return cp1.CheckPointId, v1.EnterTime, min((v2.EnterTime - v1.EnterTime) / 60000) as visit_duration
order by v1.EnterTime;
</code>```

But when I am trying to average the visit duration time:

```<code>match (vr: Visitor {MAC: '00:0a:95:9d:68:16'})-->(v1: Visit)-->(cp1: CheckPoint)
optional match (vr: Visitor {MAC: '00:0a:95:9d:68:16'})-->(v2: Visit)-->(cp2: CheckPoint)
where v2.EnterTime > v1.EnterTime
return avg(min((v2.EnterTime - v1.EnterTime) / 60000)) as avg_visit_duration;
</code>```

It returns an error message:

```<code>Error occurred: Can't use aggregate functions inside of aggregate functions.
</code>```

Probably, I need to use WITH clause, but so far I have been unable to write a query using WITH clause which gives the correct result (110 minutes).

Any ideas? Your help will be much appreciated! Thanks!

答:
stdob--'s answer is great. Here is another solution. It is a bit overcomplicated for this query, but could be useful for your other queries:</p>

```<code>MATCH (vr:Visitor {MAC: '00:0a:95:9d:68:16'})-->(v:Visit)-->(:CheckPoint)
WITH vr, v
ORDER BY v.EnterTime
WITH vr, collect(v.EnterTime / 60000) AS visitTimes
WITH vr, visitTimes, range(0, length(visitTimes) - 2) AS indices
WITH vr, reduce(acc = [], i in indices | acc +  [visitTimes[i+1] - visitTimes[i]]) AS timeDifferences
UNWIND timeDifferences AS timeDifference
RETURN vr, sum(timeDifference)
</code>```

Body:
everyone! I have a Neo4j database which contains information about visitors who visit a number of checkpoints at specific moments of time. visitors, visits and checkpoints are represented as nodes.

Each visitor is identified by his/her device MAC address, each checkpoint has a unique id.

Each visit node contains an EnterTime property, which is the time (num of millisec since 1970) when the visitor with some specific MAC address is first noticed near the respective checkpoint.

Note: the duration of a visit should be calculated as the difference between EnterTime of the next visit and the EnterTime of this visit.

My goal is to find some statistics about the visits, for example,
1) the average time of a visit by a specific visitor,
2) the average time of a visit to a specific store,
3) the most popular store (i. e. the store with the longest TOTAL time of visits
4) the most popular store (i. e. the store with the longest AVERAGE time of visits) etc.

The database is created with this cypher query:

//Create visitors:
CREATE (Visitor1: Visitor {MAC:'00:0a:95:9d:68:16'})
CREATE (Visitor2: Visitor {MAC:'00:0a:95:9d:68:17'})
CREATE (Visitor3: Visitor {MAC:'00:0a:95:9d:68:18'})

//Create CheckPoints:
CREATE (CheckPoint1: CheckPoint {CheckPointId: 1})
CREATE (CheckPoint2: CheckPoint {CheckPointId: 2})
CREATE (CheckPoint3: CheckPoint {CheckPointId: 3})
CREATE (CheckPoint4: CheckPoint {CheckPointId: 4})
CREATE (CheckPoint5: CheckPoint {CheckPointId: 5})

//Create visits:
//by visitor 1:
CREATE  (Visitor1)-[:MAKES]->(Visit1: Visit {EnterTime: 1488358800000})-[:TO]->(CheckPoint1)
CREATE  (Visitor1)-[:MAKES]->(Visit2: Visit {EnterTime: 1488359400000})-[:TO]->(CheckPoint2)
CREATE  (Visitor1)-[:MAKES]->(Visit3: Visit {EnterTime: 1488361200000})-[:TO]->(CheckPoint3)
CREATE  (Visitor1)-[:MAKES]->(Visit4: Visit {EnterTime: 1488363600000})-[:TO]->(CheckPoint4)
CREATE  (Visitor1)-[:MAKES]->(Visit5: Visit {EnterTime: 1488364800000})-[:TO]->(CheckPoint5)
CREATE  (Visitor1)-[:MAKES]->(Visit6: Visit {EnterTime: 1488365400000})-[:TO]->(CheckPoint1)

//by visitor 2:
CREATE  (Visitor2)-[:MAKES]->(Visit7: Visit {EnterTime: 1488358800000})-[:TO]->(CheckPoint1)
CREATE  (Visitor2)-[:MAKES]->(Visit8: Visit {EnterTime: 1488360300000})-[:TO]->(CheckPoint4)
CREATE  (Visitor2)-[:MAKES]->(Visit9: Visit {EnterTime: 1488362400000})-[:TO]->(CheckPoint2)
CREATE  (Visitor2)-[:MAKES]->(Visit10: Visit {EnterTime: 1488363000000})-[:TO]->(CheckPoint1)

//by visitor 3:
CREATE  (Visitor3)-[:MAKES]->(Visit11: Visit {EnterTime: 1488353820000})-[:TO]->(CheckPoint1)
CREATE  (Visitor3)-[:MAKES]->(Visit12: Visit {EnterTime: 1488354600000})-[:TO]->(CheckPoint4)
CREATE  (Visitor3)-[:MAKES]->(Visit13: Visit {EnterTime: 1488358200000})-[:TO]->(CheckPoint3)
CREATE  (Visitor3)-[:MAKES]->(Visit14: Visit {EnterTime: 1488359700000})-[:TO]->(CheckPoint1)

Please, help me write the queries 1 – 4 correctly.
So far, I have this query, which outputs the visit duration to each checkpoint by a specific visitor (it works correctly):

match (vr: Visitor {MAC: '00:0a:95:9d:68:16'})-->(v1: Visit)-->(cp1: CheckPoint)
optional match (vr: Visitor {MAC: '00:0a:95:9d:68:16'})-->(v2: Visit)-->(cp2: CheckPoint)
where v2.EnterTime > v1.EnterTime
return cp1.CheckPointId, v1.EnterTime, min((v2.EnterTime - v1.EnterTime) / 60000) as visit_duration
order by v1.EnterTime;

But when I am trying to average the visit duration time:

match (vr: Visitor {MAC: '00:0a:95:9d:68:16'})-->(v1: Visit)-->(cp1: CheckPoint)
optional match (vr: Visitor {MAC: '00:0a:95:9d:68:16'})-->(v2: Visit)-->(cp2: CheckPoint)
where v2.EnterTime > v1.EnterTime
return avg(min((v2.EnterTime - v1.EnterTime) / 60000)) as avg_visit_duration;

It returns an error message:

Error occurred: Can't use aggregate functions inside of aggregate functions.

Probably, I need to use WITH clause, but so far I have been unable to write a query using WITH clause which gives the correct result (110 minutes).

Any ideas? Your help will be much appreciated! Thanks!

Body:
stdob--'s answer is great. Here is another solution. It is a bit overcomplicated for this query, but could be useful for your other queries:

MATCH (vr:Visitor {MAC: '00:0a:95:9d:68:16'})-->(v:Visit)-->(:CheckPoint)
WITH vr, v
ORDER BY v.EnterTime
WITH vr, collect(v.EnterTime / 60000) AS visitTimes
WITH vr, visitTimes, range(0, length(visitTimes) - 2) AS indices
WITH vr, reduce(acc = [], i in indices | acc +  [visitTimes[i+1] - visitTimes[i]]) AS timeDifferences
UNWIND timeDifferences AS timeDifference
RETURN vr, sum(timeDifference)