问:
How to consistently access whether a user is authenticated in view
I'm trying to restrict user access to content in an express app using passport.js as authentication middleware. The way I'd like to do this is by loading all restricted views into a block in a base template using pug.js template inheritance:

```<code>// All views extend this base template
doctype html
html
   head
   body
      h1 This is my base template
      if(authenticated)
         // Child templates overwrite this block with their content
         block content
      else
         // Otherwise, prompt user to log in
         a(href='/login') login
</code>```

I've read that I can access values saved in res.locals in the view, but such values are scoped to that response and I'll have to pass a value like 'authenticated: true' to every template I end up rendering using the above method.  Is there a better way to consistently access session data across all views without code duplication or perhaps a better way to approach restricting user access in express apps in general?

答:
Unless I'm misunderstanding the question, you should not have to reset authenticated to be true every time the template is rendered. Pug will pass any variables you specify to the template without getting in the way of their values. The innards of your route need to pass the authenticated variable after you determine whether or not someone actually is authenticated.

route.js

```<code>var authenticated = true; // However you determine authenticated to be true or false
res.render('/yourpage', {
    authenticated: authenticated
});
</code>```

Your Pug code would remain the same. If authenticated is true, the user can see that content. If not, they'll be prompted to log in.

Body:
I'm trying to restrict user access to content in an express app using passport.js as authentication middleware. The way I'd like to do this is by loading all restricted views into a block in a base template using pug.js template inheritance:

// All views extend this base template
doctype html
html
   head
   body
      h1 This is my base template
      if(authenticated)
         // Child templates overwrite this block with their content
         block content
      else
         // Otherwise, prompt user to log in
         a(href='/login') login

I've read that I can access values saved in res.locals in the view, but such values are scoped to that response and I'll have to pass a value like 'authenticated: true' to every template I end up rendering using the above method.  Is there a better way to consistently access session data across all views without code duplication or perhaps a better way to approach restricting user access in express apps in general?

Body:
Unless I'm misunderstanding the question, you should not have to reset authenticated to be true every time the template is rendered. Pug will pass any variables you specify to the template without getting in the way of their values. The innards of your route need to pass the authenticated variable after you determine whether or not someone actually is authenticated.

route.js

var authenticated = true; // However you determine authenticated to be true or false
res.render('/yourpage', {
    authenticated: authenticated
});

Your Pug code would remain the same. If authenticated is true, the user can see that content. If not, they'll be prompted to log in.


来源: stackexchange

问:
Passing object key as an argument for parameter retrieval
I've built an AngularJS factory:

```<code>angular.module('app.services', [])

.factory('StorageService', function($localStorage) {
    $localStorage.$default({
        objA : ['foo','bar'],
        objB : []
    });
    var _getByKey = function(storageItem){
        return $localStorage.storageItem;
    }

    return {
        get : _getByKey
    };

});
</code>```

In my controller, I'm trying to retrieve it as such:

```<code>angular.module('app.controllers', [])
.controller('testCtrl', function($scope, StorageService) {
    console.log(StorageService.get(objA));
}
</code>```

I will be having several objects stored in the localStorage and I want a flexibility to retrieve them via the factory rather than injecting the $localStorage dependency together with the factory.

I strongly believe the issue is lying in the factory's parameter passing. Some JavaScript hack that my brain is not processing. LOL. Any ideas? ^_^

UPDATE: Sorry guys, I totally forgot the error~ Basically, when this code is executed, I get "ReferenceError: objA is not defined"

答:
Your syntax here is not quite right.  What you are trying to do is pass the property name you want to retrieve;  What you are actually doing is passing a variable, which hasn't been declared yet.

So the first part you need to change is:

```<code>console.log(StorageService.get('objA'));
</code>```

Pass a string value, rather than a variable.

Inside your .get() method, you are attempting to retrieve the property based on the value that was passed in, but what you are actually doing is looking for the property storageItem, which won't exist.  If you want to use the value of storageItem, you need to use the bracket syntax.

```<code>return $localStorage[storageItem];
</code>```

Demo

ContentLicense: CC BY-SA 3.0

Body:
I've built an AngularJS factory:

angular.module('app.services', [])

.factory('StorageService', function($localStorage) {
    $localStorage.$default({
        objA : ['foo','bar'],
        objB : []
    });
    var _getByKey = function(storageItem){
        return $localStorage.storageItem;
    }

    return {
        get : _getByKey
    };

});

In my controller, I'm trying to retrieve it as such:

angular.module('app.controllers', [])
.controller('testCtrl', function($scope, StorageService) {
    console.log(StorageService.get(objA));
}

I will be having several objects stored in the localStorage and I want a flexibility to retrieve them via the factory rather than injecting the $localStorage dependency together with the factory.

I strongly believe the issue is lying in the factory's parameter passing. Some JavaScript hack that my brain is not processing. LOL. Any ideas? ^_^

UPDATE: Sorry guys, I totally forgot the error~ Basically, when this code is executed, I get "ReferenceError: objA is not defined"

Body:
Your syntax here is not quite right.  What you are trying to do is pass the property name you want to retrieve;  What you are actually doing is passing a variable, which hasn't been declared yet.

So the first part you need to change is:

console.log(StorageService.get('objA'));

Pass a string value, rather than a variable.

Inside your .get() method, you are attempting to retrieve the property based on the value that was passed in, but what you are actually doing is looking for the property storageItem, which won't exist.  If you want to use the value of storageItem, you need to use the bracket syntax.

return $localStorage[storageItem];

Demo


问:
How to pass an inherited class with nontype template to it's parent reference in C++
Consider the following code: collection technically is a vector with sort method in addition.

```<code>template<class T>
class collection
{
public:
  std::vector<T> vec;
  void sort(sortType& U, bool compare(T, T))
  {
      U.doSort(vec, compare) ;
  }
}
</code>```

And this is class sortType

```<code>template<class T>
class sortType
{
 protected:
   doSort(std::vector<T>&,  bool compare(T, T));
}
</code>```

The following code is some different sorting methods that I want to use

```<code>template<class T>
class insertionsort : public sortType
{
 public:
   doSort(std::vector<T>&, bool compare(T, T))
    {
      //code of insertion sort
    }
}

template<class T>
class quicksort : public sortType
{
 public:
   doSort(std::vector<T>&, bool compare(T, T))
    {
      //code of quicksort
    }
}
</code>```

compare is a function look like this:

```<code>template <class T>
bool greater( T l, T r)
{
    if (l<r) return true;
    return false;
}
</code>```

I want to use the previous class like this:

```<code>insertionsort U = insertionsort() ;
collectionObj.sort(U, greater) ;
</code>```

Unfortunately, visual studio announced that I cannot pass the insertionsort class to sortType class. How could I fix it and use something like those previous.
Thank for helpings

答:
here:

```<code>void sort(sortType& U, bool compare(T, T))
</code>```

you are trying to pass sortType, but it is a template; actual type is sortType<T>, so function signature should be

```<code>void sort(sortType<T>& U, bool compare(T, T))
</code>```

also, what n.m. mentioned in comments

Body:
Consider the following code: collection technically is a vector with sort method in addition.

template<class T>
class collection
{
public:
  std::vector<T> vec;
  void sort(sortType& U, bool compare(T, T))
  {
      U.doSort(vec, compare) ;
  }
}

And this is class sortType

template<class T>
class sortType
{
 protected:
   doSort(std::vector<T>&,  bool compare(T, T));
}

The following code is some different sorting methods that I want to use

template<class T>
class insertionsort : public sortType
{
 public:
   doSort(std::vector<T>&, bool compare(T, T))
    {
      //code of insertion sort
    }
}

template<class T>
class quicksort : public sortType
{
 public:
   doSort(std::vector<T>&, bool compare(T, T))
    {
      //code of quicksort
    }
}

compare is a function look like this:

template <class T>
bool greater( T l, T r)
{
    if (l<r) return true;
    return false;
}

I want to use the previous class like this:

insertionsort U = insertionsort() ;
collectionObj.sort(U, greater) ;

Unfortunately, visual studio announced that I cannot pass the insertionsort class to sortType class. How could I fix it and use something like those previous.
Thank for helpings

Body:
here:

void sort(sortType& U, bool compare(T, T))

you are trying to pass sortType, but it is a template; actual type is sortType<T>, so function signature should be

void sort(sortType<T>& U, bool compare(T, T))

also, what n.m. mentioned in comments


问:
PHP class method return type
Is it possible to define the return type like this?</p>

```<code>public static function bool Test($value)
{
      return $value; //this value will be bool
}
</code>```

答:
Since the release of PHP7 they have now introduced Return Type Declarations to PHP.

You define the return type by appending : type when you define the function:

```<code>public function foo() : array
{
    return array();
}
</code>```

Default Weak Mode

By default PHP uses the Weak mode. The documentation explains it in the following way:

In the default weak mode, returned values will be coerced to the correct type if they are not already of that type

For example, see the following example where the function returns a string, even though the defined return type is int

```<code>function myInt() : int {
    return "1";
}

echo gettype(myInt());
// Output is "integer"
</code>```

Strong/Strict Mode

You can also tell PHP to enter strict/strong mode when handling return types by setting declare(strict_types=1). What this means is that PHP will throw a TypeError if a function returns the wrong type. The PHP documentation explain it in the following way:

In strong mode, the returned value must be of the correct type, otherwise a TypeError will be thrown.

```<code>declare(strict_types=1);
function myInt() : int {
    return "1";
}

echo gettype(myInt());
// Throws an TypeError
</code>```

ContentLicense: CC BY-SA 4.0

Title: PHP class method return type

Body:
Is it possible to define the return type like this?

public static function bool Test($value)
{
      return $value; //this value will be bool
}

Body:
Since the release of PHP7 they have now introduced Return Type Declarations to PHP.

You define the return type by appending : type when you define the function:

public function foo() : array
{
    return array();
}

Default Weak Mode

By default PHP uses the Weak mode. The documentation explains it in the following way:

In the default weak mode, returned values will be coerced to the correct type if they are not already of that type

For example, see the following example where the function returns a string, even though the defined return type is int

function myInt() : int {
    return "1";
}

echo gettype(myInt());
// Output is "integer"

Strong/Strict Mode

You can also tell PHP to enter strict/strong mode when handling return types by setting declare(strict_types=1). What this means is that PHP will throw a TypeError if a function returns the wrong type. The PHP documentation explain it in the following way:

In strong mode, the returned value must be of the correct type, otherwise a TypeError will be thrown.

declare(strict_types=1);
function myInt() : int {
    return "1";
}

echo gettype(myInt());
// Throws an TypeError


问:
Frame names being assigned automatically
What's so special with Frames that when you create them run-time it gets assigned a name automatically ? This causes a problem when you use them in a loop i.e. :

```<code>for i := 0 to 3 do
  TMyFrame.Create(self); //Error on 2nd pass
</code>```

On first pass, the frame is explicityl named 'MyFrame'.
On second pass, it will try to name it again 'MyFrame' which
obivously will cause an exception as there is already a
component with such name.

The other components or forms are happy to be created without
me assigning them a name. What gives ?

This is on Delphi 2006 btw.

Cheers

答:
Co-incidentally I just bumped into this myself (again).

If you take the name out of your frame component then Delphi moans that "Root Component must have a name" - I guess it because somewhere Delphi is calling RegisterClass(RootComponentName) and then to create it (or a descendent) it's calling Findclass(RootComponentName) or similar. As you can do this yourself to create components that you don't actually know the classname of a design time, why would Delphi not do the same?

Whereas with a TButton etc. it is already a registered Class.

ContentLicense: CC BY-SA 2.5

Body:
What's so special with Frames that when you create them run-time it gets assigned a name automatically ? This causes a problem when you use them in a loop i.e. :

for i := 0 to 3 do
  TMyFrame.Create(self); //Error on 2nd pass

On first pass, the frame is explicityl named 'MyFrame'.
On second pass, it will try to name it again 'MyFrame' which
obivously will cause an exception as there is already a
component with such name.

The other components or forms are happy to be created without
me assigning them a name. What gives ?

This is on Delphi 2006 btw.

Cheers


问:
Bootstrap 3 Flush footer to bottom. not fixed
I am using Bootstrap 3 for a site I am designing.

I want to have a footer like this sample.
Sample

Please note that I don't want it FIXED so bootstrap navbar-fixed-bottom does not solve my problem. I just want it to be always at the bottom of the content and also be responsive.

Any guide will be very much appreciated.

EDIT:

Sorry if I wasn't clear.
What happens now is that when the content body does not have enough content. My footer moves up and then it leaves an empty space at the bottom.

This is what i have now for my navbar

```<code><nav class="navbar navbar-inverse navbar-bottom" style="padding:0 0 120px 0">
        <div class="container">
            <div class="row">
                <div class="col-sm-4">
                    <h5 id='footer-header'> SITEMAP </h3>
                    <div class="col-sm-4" style="padding: 0 0 0 0px">
                        <p>News</p>
                        <p>contact</p>
                    </div>
                    <div class="col-sm-4" style="padding: 0 0 0 0px">
                        <p>FAQ</p>
                        <p>Privacy Policy</p>
                    </div>
                </div>
                <div class="col-sm-4">
                    <h5 id='footer-header'> xxxx </h3>
                    <p>yyyyyyyyyyyyy</p>
                </div>
                <div class="col-sm-4">
                    <h5 id='footer-header'> xxxxx </h3>
                    <p>uuuuuuuuuuuuuuu</p>
                </div>
            </div>
        </div>
    </nav>
</code>```

CSS

```<code>.navbar-bottom {
min-height: 300px;
margin-top: 100px;
background-color: #28364f;
padding-top: 35px;
color:#FFFFFF;
}
</code>```

答:
Or this</p>

```<code><footer class="navbar navbar-default navbar-fixed-bottom">
    <p class="text-muted" align="center">This is a footer</p>
</footer>
</code>```

Body:
I am using Bootstrap 3 for a site I am designing.

I want to have a footer like this sample.
Sample

Please note that I don't want it FIXED so bootstrap navbar-fixed-bottom does not solve my problem. I just want it to be always at the bottom of the content and also be responsive.

Any guide will be very much appreciated.

EDIT:

Sorry if I wasn't clear.
What happens now is that when the content body does not have enough content. My footer moves up and then it leaves an empty space at the bottom.

This is what i have now for my navbar

 SITEMAP

News

contact

FAQ

Privacy Policy

 xxxx

yyyyyyyyyyyyy

 xxxxx

uuuuuuuuuuuuuuu

CSS

.navbar-bottom {
min-height: 300px;
margin-top: 100px;
background-color: #28364f;
padding-top: 35px;
color:#FFFFFF;
}

Body:
Or this

<footer class="navbar navbar-default navbar-fixed-bottom">
    <p class="text-muted" align="center">This is a footer</p>
</footer>


问:
C# DateTime format in Arrays
Currently my function outputs date as 6/6/2016 and I need to be able to make it as 06/06/2016 for all the data. I found DateTime.Now.ToString("dd") is a solution. But when I do parts[0].DateTime.Now.ToString("dd") it doesn't accept it.</p>

```<code>private static string FormatDate(string sDate)
{
    // "6/16/1989"
    //mysql format 06-16-1989

    string[] parts = sDate.Split('/');

    //sDay.DateTime.Now.ToString("dd");

    return $"'{parts[2]}-{parts[1]}-{parts[0]}'";
}
</code>```

答:
You can use DateTime.ParseExact() which will
tell you when the passed in value does not have a correct format by throwing an exception. An example would be </p>

```<code>string sDate = "6/6/2016";

        try
        {
            DateTime dt = DateTime.ParseExact(sDate, "d/M/yyyy", CultureInfo.InvariantCulture);

            Console.WriteLine(dt.ToString("yyyy-MM-dd"));
        }
        catch (Exception e) {

            Console.WriteLine(e.Message);
        }
</code>```

Title: C# DateTime format in Arrays

Body:
Currently my function outputs date as 6/6/2016 and I need to be able to make it as 06/06/2016 for all the data. I found DateTime.Now.ToString("dd") is a solution. But when I do parts[0].DateTime.Now.ToString("dd") it doesn't accept it.

private static string FormatDate(string sDate)
{
    // "6/16/1989"
    //mysql format 06-16-1989

    string[] parts = sDate.Split('/');

    //sDay.DateTime.Now.ToString("dd");

    return $"'{parts[2]}-{parts[1]}-{parts[0]}'";
}

Body:
You can use DateTime.ParseExact() which will
tell you when the passed in value does not have a correct format by throwing an exception. An example would be

string sDate = "6/6/2016";

        try
        {
            DateTime dt = DateTime.ParseExact(sDate, "d/M/yyyy", CultureInfo.InvariantCulture);

            Console.WriteLine(dt.ToString("yyyy-MM-dd"));
        }
        catch (Exception e) {

            Console.WriteLine(e.Message);
        }


问:
SMTP Send Mail Task Failing
I have already gone through multiple links before posting and it is not a repeat question.I am not pretty sure that i should post it here or on server fault.

I am trying to configure the SMTP email task but running into error mentioned below.
System.Net.WebException: Unable to connect to the remote server
System.Net.Sockets.SocketException:An attempt was made to access a socket in a way forbidden by its access permissions ipaddress:25

I also tried to verify using powershell, if the SMTP is fine and below are the results:

Using Send-mailmessage : It is working really fine

Using Net.Mail.SmtpClient : I could send email to organization email ids but not outside.

Can someone help me understand where exactly the problem could be.

答: The problem was Antivirus was blocking the requests from SSIS but was allowing the powershell requests.</p>

Title: SMTP Send Mail Task Failing


问:
Connection timeout for SQL server
Can I increase the timeout by modifying the connection string in the web.config?

答:
Yes, you could append ;Connection Timeout=30 to your connection string and specify the value you wish.

The timeout value set in the Connection Timeout property is a time expressed in seconds. If this property isn't set, the timeout value for the connection is the default value (15 seconds).

Moreover, setting the timeout value to 0, you are specifying that your attempt to connect waits an infinite time. As described in the documentation, this is something that you shouldn't set in your connection string:

A value of 0 indicates no limit, and should be avoided in a
  ConnectionString because an attempt to connect waits indefinitely.

Title: Connection timeout for SQL server


问:
Why does content size of UITableView Change
I have a UITableView that I am loading my data in 3 blocks. I load the latest 10 records and when user pulls up using the UIRefreshControl, I load the preceding 10 and show the last row from the previous block. I store the previous content size right before I load the new set from database

```<code>previousContentSizeHeight = tableView.contentSize.height
</code>```

and then when data comes and update my array, I use previous to calculate the new content size of table

```<code>let difference = tableView.contentSize.height -
     previousContentSizeHeight - MinimumCellHeight

self.messageTableView.setContentOffset(CGPoint(x: 0, y: difference), animated: false)
</code>```

This works for the most part. It behaves correctly after the viewDidAppear when loading the first set and when loading the 2nd set, but in the third set it starts changing in content size. It gets decreased! My understanding is if I am adding data to it (not deleting anything), the content size should only grow.
I have in multiple places in my code readings of the table content size like this event:

```<code>func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    print("tableView.contentSize.height is: \(tableView.contentSize.height)")
}
</code>```

as I am scrolling up and down, I see the number decrease and sometimes increase and decrease
Why does content size changes in size!?

NOTE: I want to stick to using the content offset. I have more luck with it than IndexPath.

UPDATE #1
@Sohil R. Memon: I tried your suggestion. Per screenshot, I added a print statement and as you can see the viewDidLayoutSubviews is still not executing. i tried inside the endDisplaying with self.messageTableView and just tableView

答:
Once the cell are displayed and didEndDisplaying is called, there are more things to process and when you scroll cellForItem calls again and that gives you different sizes.

In order to get the exact contentSize of UITableView once all the cells are displayed, you can get it from below method. Just write the below method in your UIViewController class.

```<code>override func viewDidLayoutSubviews() {
    print(tableView.contentSize.height) //Exact Content Size of UITableView
}

func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    tableView.layoutIfNeeded()
}
</code>```

Hope this helps!

Body:
I have a UITableView that I am loading my data in 3 blocks. I load the latest 10 records and when user pulls up using the UIRefreshControl, I load the preceding 10 and show the last row from the previous block. I store the previous content size right before I load the new set from database

previousContentSizeHeight = tableView.contentSize.height

and then when data comes and update my array, I use previous to calculate the new content size of table

let difference = tableView.contentSize.height -
     previousContentSizeHeight - MinimumCellHeight

self.messageTableView.setContentOffset(CGPoint(x: 0, y: difference), animated: false)

This works for the most part. It behaves correctly after the viewDidAppear when loading the first set and when loading the 2nd set, but in the third set it starts changing in content size. It gets decreased! My understanding is if I am adding data to it (not deleting anything), the content size should only grow.
I have in multiple places in my code readings of the table content size like this event:

func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    print("tableView.contentSize.height is: \(tableView.contentSize.height)")
}

as I am scrolling up and down, I see the number decrease and sometimes increase and decrease
Why does content size changes in size!?

NOTE: I want to stick to using the content offset. I have more luck with it than IndexPath.

UPDATE #1
@Sohil R. Memon: I tried your suggestion. Per screenshot, I added a print statement and as you can see the viewDidLayoutSubviews is still not executing. i tried inside the endDisplaying with self.messageTableView and just tableView

Body:
Once the cell are displayed and didEndDisplaying is called, there are more things to process and when you scroll cellForItem calls again and that gives you different sizes.

In order to get the exact contentSize of UITableView once all the cells are displayed, you can get it from below method. Just write the below method in your UIViewController class.

override func viewDidLayoutSubviews() {
    print(tableView.contentSize.height) //Exact Content Size of UITableView
}

func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    tableView.layoutIfNeeded()
}

Hope this helps!


问:
Create/Edit/Save data in a jQuery pop-up for ASP.NET-MVC and Linq2Sql
I have a MVC page which allows creation and editing of a subcontract.  When the user has to select a company for the subcontract, I would like for them to have the option to create a new company.  I've made a jQuery pop-up with the company fields, but I don't know how to then save this information to the company table.  I would also like to be able to use the same pop-up to allow the user to edit the information for an existing company, but need direction in how to send the information to the pop-up.</p>

答:
I was looking for a solution to this question today.

Found a really nice opensource solution with demo.  I figure I'll link it here to save others' time.  It's call jQuery Inline Edit.

http://www.codenothing.com/archives/jquery/inline-text-edit/


问:
Ansible template module not parsing with_items variable
I am using a simple template with only variables in it.
This is how my task looks like in my playbook (actually a role being used from my playbook):

```<code>- name: Ensure the conf file exists
  template:
    src: file.conf.j2
    dest: '/opt/file.conf'
  with_items: '{{ myrole }}'
</code>```

I keep variables in group_vars. Any variable in file.conf.j2 will be expanded correctly, like {{ myrole_user }} but fails when expanding one of with_items variables, like {{ myrole.applicationName }}.

My group_vars looks like this:

```<code>myrole_user: regularuser
myrole:
  -  { applicationName: foo, othervar: bar }
</code>```

And this is the Ansible error:

"msg": "AnsibleUndefinedVariable: 'list object' has no attribute 'applicationName'"

答:
You defined a list called myrole and then try to access a value of the key myrole.applicationName, so you get an error message that the list does not contain the key/attribute (which is true -- a list contains only an ordered set of elements).

Ansible with_ loops by default* set a variable named item containing the value of the element in the current iteration, so in the template you should refer to the item (not to the myrole variable which remains intact):

```<code>{{ item.applicationName }}
</code>```

* you can change this with loop_var setting in the loop control section.

Body:
I am using a simple template with only variables in it.
This is how my task looks like in my playbook (actually a role being used from my playbook):

- name: Ensure the conf file exists
  template:
    src: file.conf.j2
    dest: '/opt/file.conf'
  with_items: '{{ myrole }}'

I keep variables in group_vars. Any variable in file.conf.j2 will be expanded correctly, like {{ myrole_user }} but fails when expanding one of with_items variables, like {{ myrole.applicationName }}.

My group_vars looks like this:

myrole_user: regularuser
myrole:
  -  { applicationName: foo, othervar: bar }

And this is the Ansible error:

"msg": "AnsibleUndefinedVariable: 'list object' has no attribute 'applicationName'"

Body:
You defined a list called myrole and then try to access a value of the key myrole.applicationName, so you get an error message that the list does not contain the key/attribute (which is true -- a list contains only an ordered set of elements).

Ansible with_ loops by default* set a variable named item containing the value of the element in the current iteration, so in the template you should refer to the item (not to the myrole variable which remains intact):

{{ item.applicationName }}

* you can change this with loop_var setting in the loop control section.


问:
Copy data from 2 sheets into a single sheet in interleaving format
I have 2 sets of data in 2 sheets having same columns in each sheet.
I want to copy both the sets of data from 2 sheets into a 3rd sheet but in the following format:-

```<code>Sheet1
Name Age Gender
Mayur 23  M
Alex  24  M
Maria 25  F
April 19  F

Sheet2
Name Age Gender
Mayur 21  M
Maria 24  F
Alex  24  M
June  20  F

Sheet3
Name1 Name2 Age1 Age2 Gender1 Gender2
Mayur Mayur  23   21     M       M
Alex  Alex   24   24     M       M
Maria Maria  25   24     F       F
April        19          F
      June        20             F
</code>```

Now there is one primary column i.e. Name. This column will never be empty.
Both the sheets may not have the data in the same sequence.
Both the sheets may have different entries for the same name.
There could be a name missing in any of the sheets

I have written the whole code which does the following:-

I find out Names from sheet1 in sheet2 & then copy corresponding entries for that name from both the sheets to sheet3.

If a name is not found in sheet2 then it's data is copied as it is as shown above & finally Names in sheet2 are searched in sheet1 if any name is not present in there those entries are copied in sheet3.

Now the searching part runs quite well performance wise but the copying part takes a lot of time.

I have tried other methods of copying the data as well but none runs quite fast.
In actual data there are more than 200 columns & millions of rows.
The whole process runs for more than 6-7 hours.

Could anyone please let me know any alternative faster way of achieving this.
Even if that could reduce the time to an hour or 2 from 7 hours that's still great.

Also I need to highlight the descrepancies which I'm doing that by changing the cell color when there is a mismatch in the data while copying from both the sheets.

Below is the code

```<code>Sub findUsingArray()
Dim i As Long
Dim j As Variant
Dim noOfColumnsA As Integer
Dim maxNoOfColumns As Integer
Dim noOfRowsA As Long
Dim noOfRowsB As Long
Dim arrayColumnA() As Variant
Dim arrayColumnB() As Variant
Dim sheet1 As Worksheet
Dim sheet2 As Worksheet
Dim primaryKeyColumn As Integer
Dim result As Long

Set sheet1 = ThisWorkbook.Sheets("Sheet1")
Set sheet2 = ThisWorkbook.Sheets("Sheet2")

noOfColumnsA = sheet1.Cells(1, Columns.Count).End(xlToLeft).Column

maxNoOfColumns = noOfColumnsA * 2

noOfRowsA = sheet1.Cells(Rows.Count, 1).End(xlUp).Row

noOfRowsB = sheet2.Cells(Rows.Count, 1).End(xlUp).Row

'createHeader maxNoOfColumns Used to create header in 3rd sheet

primaryKeyColumn = 1

ReDim arrayColumnA(noOfRowsA)
ReDim arrayColumnB(noOfRowsB)

arrayColumnA = sheet1.Range(sheet1.Cells(1, primaryKeyColumn), sheet1.Cells(noOfRowsA, primaryKeyColumn))

arrayColumnB = sheet2.Range(sheet2.Cells(1, primaryKeyColumn), sheet2.Cells(noOfRowsB, primaryKeyColumn))

    result = 2

        For i = 2 To noOfRowsA
            j = Application.Match(arrayColumnA(i, 1), sheet2.Range(sheet2.Cells(1, primaryKeyColumn), sheet2.Cells(noOfRowsB, primaryKeyColumn)), 0)

                If Not IsError(j) Then
                    result = copyInaRowUsingArray(i, result, j, maxNoOfColumns)
                Else
                    result = copyMissingRow(1, i, result, maxNoOfColumns)
                End If
        Next i

    For i = 2 To noOfRowsB
        j = Application.Match(arrayColumnB(i, 1), sheet1.Range(sheet1.Cells(1, primaryKeyColumn), sheet1.Cells(noOfRowsA, primaryKeyColumn)), 0)

        If IsError(j) Then
            result = copyMissingRow(2, i, result, maxNoOfColumns)
        End If

    Next i
End Sub

Function copyInaRowUsingArray(sheet1Index As Long, newRowIndex As Long, sheet2index As Variant, noOfColumns As Integer)
Dim i As Long
Dim j As Long
Dim val As Variant
Dim valueA As String
Dim valueB As String
Dim arrayA() As Variant
Dim arrayB() As Variant
Dim sheet1 As Worksheet
Dim sheet2 As Worksheet
Dim sheet3 As Worksheet
Dim rowColoured As Boolean

j = 1

Set sheet1 = ThisWorkbook.Sheets("Sheet1")
Set sheet2 = ThisWorkbook.Sheets("Sheet2")
Set sheet3 = ThisWorkbook.Sheets("Sheet3")

 arrayA = Application.Transpose(Application.Transpose(sheet1.Range(sheet1.Cells(sheet1Index, 1), sheet1.Cells(sheet1Index, noOfColumns)).Value))
 arrayB = Application.Transpose(Application.Transpose(sheet2.Range(sheet2.Cells(sheet2index, 1), sheet2.Cells(sheet2index, noOfColumns)).Value))

 rowColoured = False

With sheet3

    For i = 1 To noOfColumns

        valueA = arrayA(j)
        If Not valueA = "" Then
            .Cells(newRowIndex, i).Value = valueA
        End If
        i = i + 1

        valueB = arrayB(j)
        If Not valueB = "" Then
            .Cells(newRowIndex, i).Value = valueB
        End If

        If Not StrComp(CStr(valueA), CStr(valueB)) = 0 Then
            If Not rowColoured Then
                .Range(.Cells(newRowIndex, 1), .Cells(newRowIndex, noOfColumns)).Interior.ColorIndex = 35
                rowColoured = True
            End If

            .Cells(newRowIndex, i).Interior.ColorIndex = 34
            .Cells(newRowIndex, i - 1).Interior.ColorIndex = 34
        End If

        j = j + 1

    Next i

    copyInaRowUsingArray = newRowIndex + 1
End With
End Function

Function copyMissingRow(sheetNo As Integer, sheetIndex As Long, newRowIndex As Long, noOfColumns As Integer)

Dim i As Long
Dim j As Long
Dim val As Variant
Dim valueA As String
Dim valueB As String
Dim arrayA() As Variant
Dim arrayB() As Variant
Dim sheet1 As Worksheet
Dim sheet2 As Worksheet
Dim sheet3 As Worksheet

j = 1

Set sheet3 = ThisWorkbook.Sheets("Sheet3")

With sheet3
    If sheetNo = 1 Then
        Set sheet1 = ThisWorkbook.Sheets("Sheet1")

        ReDim arrayA(noOfColumns)
        arrayA = Application.Transpose(Application.Transpose(sheet1.Range(sheet1.Cells(sheetIndex, 1), sheet1.Cells(sheetIndex, noOfColumns)).Value))

        For i = 1 To noOfColumns

            valueA = arrayA(j)
            If Not valueA = "" Then
                .Cells(newRowIndex, i).Value = valueA
            End If
            i = i + 1
            j = j + 1

        Next i

        .Range(.Cells(newRowIndex, 1), .Cells(newRowIndex, noOfColumns)).Interior.ColorIndex = 46

    Else

        Set sheet2 = ThisWorkbook.Sheets("Sheet2")

        ReDim arrayB(noOfColumns)
        arrayB = Application.Transpose(Application.Transpose(sheet2.Range(sheet2.Cells(sheetIndex, 1), sheet2.Cells(sheetIndex, noOfColumns)).Value))

        For i = 1 To noOfColumns

            i = i + 1

            valueB = arrayB(j)
            If Not valueB = "" Then
                .Cells(newRowIndex, i).Value = valueB
            End If

            j = j + 1

        Next i

        .Range(.Cells(newRowIndex, 1), .Cells(newRowIndex, noOfColumns)).Interior.ColorIndex = 3

    End If

     copyMissingRow = newRowIndex + 1

End With
End Function
</code>```

答:
As per one of the comments, a dictionary should help do what it is you're after.  The dictionary used here saves, from sheet(2), the name as the key and the corresponding row as the value.

```<code>Option Explicit

Sub CopyRng(frmSht As Worksheet, frmRow As Integer, offset As Integer, toRow As Integer)
  Dim r As Integer
  For r = 1 To 3:
    Sheets(3).Cells(toRow, offset + 2 * r).Value = frmSht.Cells(frmRow, r).Value
  Next
End Sub

Sub InterleaveRows()
  Dim dict As Object
  Set dict = CreateObject("Scripting.Dictionary")

  With Sheets(2)
    Dim r As Integer, r2 As Integer, r3 As Integer: r3 = 2
    Dim val As String
    For r = 2 To .Range("A" & .Rows.Count).End(xlUp).row:
      dict(.Cells(r, "A").Value) = r
    Next
  End With

  CopyRng Sheets(1), 1, -1, 1
  CopyRng Sheets(2), 1, 0, 1

  For r = 2 To Sheets(1).Range("A" & Sheets(1).Rows.Count).End(xlUp).row:
    val = Sheets(1).Cells(r, "A").Value
    If (dict.Exists(val)) Then
      r2 = dict(val)
      CopyRng Sheets(1), r, -1, r3
      CopyRng Sheets(2), r2, 0, r3
      dict.Remove val
    Else
      CopyRng Sheets(1), r, -1, r3
    End If
    r3 = r3 + 1
  Next

  For r = 0 To dict.Count - 1
    r2 = dict.items()(r)
    CopyRng Sheets(2), r2, 0, r3
    r3 = r3 + 1
  Next

End Sub
</code>```

The first loop of the 'InterLeaveRows' subroutine populates the dictionary by going through all the entries in Sheet(2).  The next two lines writes out the header to sheet(3).  The 2nd loop then writes out all values to Sheet(3) that are either in the dictionary (ie in both Sheet(1) and Sheet(2)) or just in Sheet(1); note while doing so entries from the dictionary that are written to Sheet(3) are deleted from the dictionary.  The last loop writes out key/val pairs that remain in the dictionary.  These are entries that are only in Sheet(2).

Body:
I have 2 sets of data in 2 sheets having same columns in each sheet.
I want to copy both the sets of data from 2 sheets into a 3rd sheet but in the following format:-

Sheet1
Name Age Gender
Mayur 23  M
Alex  24  M
Maria 25  F
April 19  F

Sheet2
Name Age Gender
Mayur 21  M
Maria 24  F
Alex  24  M
June  20  F

Sheet3
Name1 Name2 Age1 Age2 Gender1 Gender2
Mayur Mayur  23   21     M       M
Alex  Alex   24   24     M       M
Maria Maria  25   24     F       F
April        19          F
      June        20             F

Now there is one primary column i.e. Name. This column will never be empty.
Both the sheets may not have the data in the same sequence.
Both the sheets may have different entries for the same name.
There could be a name missing in any of the sheets

I have written the whole code which does the following:-

I find out Names from sheet1 in sheet2 & then copy corresponding entries for that name from both the sheets to sheet3.

If a name is not found in sheet2 then it's data is copied as it is as shown above & finally Names in sheet2 are searched in sheet1 if any name is not present in there those entries are copied in sheet3.

Now the searching part runs quite well performance wise but the copying part takes a lot of time.

I have tried other methods of copying the data as well but none runs quite fast.
In actual data there are more than 200 columns & millions of rows.
The whole process runs for more than 6-7 hours.

Could anyone please let me know any alternative faster way of achieving this.
Even if that could reduce the time to an hour or 2 from 7 hours that's still great.

Also I need to highlight the descrepancies which I'm doing that by changing the cell color when there is a mismatch in the data while copying from both the sheets.

Below is the code

Sub findUsingArray()
Dim i As Long
Dim j As Variant
Dim noOfColumnsA As Integer
Dim maxNoOfColumns As Integer
Dim noOfRowsA As Long
Dim noOfRowsB As Long
Dim arrayColumnA() As Variant
Dim arrayColumnB() As Variant
Dim sheet1 As Worksheet
Dim sheet2 As Worksheet
Dim primaryKeyColumn As Integer
Dim result As Long

Set sheet1 = ThisWorkbook.Sheets("Sheet1")
Set sheet2 = ThisWorkbook.Sheets("Sheet2")

noOfColumnsA = sheet1.Cells(1, Columns.Count).End(xlToLeft).Column

maxNoOfColumns = noOfColumnsA * 2

noOfRowsA = sheet1.Cells(Rows.Count, 1).End(xlUp).Row

noOfRowsB = sheet2.Cells(Rows.Count, 1).End(xlUp).Row

'createHeader maxNoOfColumns Used to create header in 3rd sheet

primaryKeyColumn = 1

ReDim arrayColumnA(noOfRowsA)
ReDim arrayColumnB(noOfRowsB)

arrayColumnA = sheet1.Range(sheet1.Cells(1, primaryKeyColumn), sheet1.Cells(noOfRowsA, primaryKeyColumn))

arrayColumnB = sheet2.Range(sheet2.Cells(1, primaryKeyColumn), sheet2.Cells(noOfRowsB, primaryKeyColumn))

    result = 2

        For i = 2 To noOfRowsA
            j = Application.Match(arrayColumnA(i, 1), sheet2.Range(sheet2.Cells(1, primaryKeyColumn), sheet2.Cells(noOfRowsB, primaryKeyColumn)), 0)

                If Not IsError(j) Then
                    result = copyInaRowUsingArray(i, result, j, maxNoOfColumns)
                Else
                    result = copyMissingRow(1, i, result, maxNoOfColumns)
                End If
        Next i

    For i = 2 To noOfRowsB
        j = Application.Match(arrayColumnB(i, 1), sheet1.Range(sheet1.Cells(1, primaryKeyColumn), sheet1.Cells(noOfRowsA, primaryKeyColumn)), 0)

        If IsError(j) Then
            result = copyMissingRow(2, i, result, maxNoOfColumns)
        End If

    Next i
End Sub

Function copyInaRowUsingArray(sheet1Index As Long, newRowIndex As Long, sheet2index As Variant, noOfColumns As Integer)
Dim i As Long
Dim j As Long
Dim val As Variant
Dim valueA As String
Dim valueB As String
Dim arrayA() As Variant
Dim arrayB() As Variant
Dim sheet1 As Worksheet
Dim sheet2 As Worksheet
Dim sheet3 As Worksheet
Dim rowColoured As Boolean

j = 1

Set sheet1 = ThisWorkbook.Sheets("Sheet1")
Set sheet2 = ThisWorkbook.Sheets("Sheet2")
Set sheet3 = ThisWorkbook.Sheets("Sheet3")

 arrayA = Application.Transpose(Application.Transpose(sheet1.Range(sheet1.Cells(sheet1Index, 1), sheet1.Cells(sheet1Index, noOfColumns)).Value))
 arrayB = Application.Transpose(Application.Transpose(sheet2.Range(sheet2.Cells(sheet2index, 1), sheet2.Cells(sheet2index, noOfColumns)).Value))

 rowColoured = False

With sheet3

    For i = 1 To noOfColumns

        valueA = arrayA(j)
        If Not valueA = "" Then
            .Cells(newRowIndex, i).Value = valueA
        End If
        i = i + 1

        valueB = arrayB(j)
        If Not valueB = "" Then
            .Cells(newRowIndex, i).Value = valueB
        End If

        If Not StrComp(CStr(valueA), CStr(valueB)) = 0 Then
            If Not rowColoured Then
                .Range(.Cells(newRowIndex, 1), .Cells(newRowIndex, noOfColumns)).Interior.ColorIndex = 35
                rowColoured = True
            End If

            .Cells(newRowIndex, i).Interior.ColorIndex = 34
            .Cells(newRowIndex, i - 1).Interior.ColorIndex = 34
        End If

        j = j + 1

    Next i

    copyInaRowUsingArray = newRowIndex + 1
End With
End Function

Function copyMissingRow(sheetNo As Integer, sheetIndex As Long, newRowIndex As Long, noOfColumns As Integer)

Dim i As Long
Dim j As Long
Dim val As Variant
Dim valueA As String
Dim valueB As String
Dim arrayA() As Variant
Dim arrayB() As Variant
Dim sheet1 As Worksheet
Dim sheet2 As Worksheet
Dim sheet3 As Worksheet

j = 1

Set sheet3 = ThisWorkbook.Sheets("Sheet3")

With sheet3
    If sheetNo = 1 Then
        Set sheet1 = ThisWorkbook.Sheets("Sheet1")

        ReDim arrayA(noOfColumns)
        arrayA = Application.Transpose(Application.Transpose(sheet1.Range(sheet1.Cells(sheetIndex, 1), sheet1.Cells(sheetIndex, noOfColumns)).Value))

        For i = 1 To noOfColumns

            valueA = arrayA(j)
            If Not valueA = "" Then
                .Cells(newRowIndex, i).Value = valueA
            End If
            i = i + 1
            j = j + 1

        Next i

        .Range(.Cells(newRowIndex, 1), .Cells(newRowIndex, noOfColumns)).Interior.ColorIndex = 46

    Else

        Set sheet2 = ThisWorkbook.Sheets("Sheet2")

        ReDim arrayB(noOfColumns)
        arrayB = Application.Transpose(Application.Transpose(sheet2.Range(sheet2.Cells(sheetIndex, 1), sheet2.Cells(sheetIndex, noOfColumns)).Value))

        For i = 1 To noOfColumns

            i = i + 1

            valueB = arrayB(j)
            If Not valueB = "" Then
                .Cells(newRowIndex, i).Value = valueB
            End If

            j = j + 1

        Next i

        .Range(.Cells(newRowIndex, 1), .Cells(newRowIndex, noOfColumns)).Interior.ColorIndex = 3

    End If

     copyMissingRow = newRowIndex + 1

End With
End Function

Body:
As per one of the comments, a dictionary should help do what it is you're after.  The dictionary used here saves, from sheet(2), the name as the key and the corresponding row as the value.

Option Explicit

Sub CopyRng(frmSht As Worksheet, frmRow As Integer, offset As Integer, toRow As Integer)
  Dim r As Integer
  For r = 1 To 3:
    Sheets(3).Cells(toRow, offset + 2 * r).Value = frmSht.Cells(frmRow, r).Value
  Next
End Sub

Sub InterleaveRows()
  Dim dict As Object
  Set dict = CreateObject("Scripting.Dictionary")

  With Sheets(2)
    Dim r As Integer, r2 As Integer, r3 As Integer: r3 = 2
    Dim val As String
    For r = 2 To .Range("A" & .Rows.Count).End(xlUp).row:
      dict(.Cells(r, "A").Value) = r
    Next
  End With

  CopyRng Sheets(1), 1, -1, 1
  CopyRng Sheets(2), 1, 0, 1

  For r = 2 To Sheets(1).Range("A" & Sheets(1).Rows.Count).End(xlUp).row:
    val = Sheets(1).Cells(r, "A").Value
    If (dict.Exists(val)) Then
      r2 = dict(val)
      CopyRng Sheets(1), r, -1, r3
      CopyRng Sheets(2), r2, 0, r3
      dict.Remove val
    Else
      CopyRng Sheets(1), r, -1, r3
    End If
    r3 = r3 + 1
  Next

  For r = 0 To dict.Count - 1
    r2 = dict.items()(r)
    CopyRng Sheets(2), r2, 0, r3
    r3 = r3 + 1
  Next

End Sub

The first loop of the 'InterLeaveRows' subroutine populates the dictionary by going through all the entries in Sheet(2).  The next two lines writes out the header to sheet(3).  The 2nd loop then writes out all values to Sheet(3) that are either in the dictionary (ie in both Sheet(1) and Sheet(2)) or just in Sheet(1); note while doing so entries from the dictionary that are written to Sheet(3) are deleted from the dictionary.  The last loop writes out key/val pairs that remain in the dictionary.  These are entries that are only in Sheet(2).


问:
sqlplus remote connection giving ORA-21561
I have installed sqlplus based on instruction given here

```<code>sqlplus 'username/password@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.0.100)(PORT=1521))(CONNECT_DATA=(SID=ORCL)))'
</code>```

This is giving me error

```<code>SQL*Plus: Release 11.2.0.4.0 Production on Fri Jul 10 16:10:38 2015

Copyright (c) 1982, 2013, Oracle.  All rights reserved.

ERROR:
ORA-21561: OID generation failed

Enter user-name:
</code>```

What is the solution for this problem?

PS: I have already added hostname and hosts have already have value.

答:
This issue can also be cause by wrong permissions on the /etc/hosts file. If it is not readable for the Oracle uid, the errors will show.

Make sure your /etc/hosts is readable by everybody:

```<code>$ ls -l /etc/hosts
-rw-r--r--    1 root     system        7446 Mar 28 23:03 /etc/hosts
$
</code>```

Body:
I have installed sqlplus based on instruction given here

sqlplus 'username/password@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.0.100)(PORT=1521))(CONNECT_DATA=(SID=ORCL)))'

This is giving me error

SQL*Plus: Release 11.2.0.4.0 Production on Fri Jul 10 16:10:38 2015

Copyright (c) 1982, 2013, Oracle.  All rights reserved.

ERROR:
ORA-21561: OID generation failed

Enter user-name:

What is the solution for this problem?

PS: I have already added hostname and hosts have already have value.

Body:
This issue can also be cause by wrong permissions on the /etc/hosts file. If it is not readable for the Oracle uid, the errors will show.

Make sure your /etc/hosts is readable by everybody:

$ ls -l /etc/hosts
-rw-r--r--    1 root     system        7446 Mar 28 23:03 /etc/hosts
$


问:
how to separate click event from siblings?
I finally got my nav to show and hide the submenu on click, but what's happening now is that when I click, to have it slideToggle, is affecting its siblings and opening and closing at the same time.

my structure look something like this:

Home

Item1

SubItem - 1

SubItem - 2

SubItem - 3

SubItem - 4

SubItem - 5

Item - 2

SubItem - 1

SubItem - 2

SubItem - 3

SubItem - 4

SubItem - 5

Item - 3

            <
SubItem - 1

SubItem - 2

SubItem - 3

SubItem - 4

SubItem - 5

Item - 4

Item - 5

About

Services

Blog

Contact

```
</div>
</div>
</p>

<p>and this is my jQuery:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$('.has-children ul').click(function(e){
    e.stopPropagation();
    var el = (event.target || event.srcElement);
    console.log('clicked');
    $(this).find('ul.submenu').slideToggle();
     $(el).find('span').toggleClass('arrow-down arrow-up');
  });</code>```

So if I click on the li with the class of has children, all my uls with class of submenu are opening at the same time.
Perhaps I am doing more than I am supposed to here, all the help would be appreciate it.

答:
try this code (i have added more correct span finding) </p>

```<code>$('.has-children ul').click(function(e){
e.stopPropagation();
var el = (event.target || event.srcElement);
console.log('clicked');
$(this).find('ul.submenu').slideToggle();
 $(this).parent().find('span').toggleClass('arrow-down arrow-up');
});
</code>```

Body:
I finally got my nav to show and hide the submenu on click, but what's happening now is that when I click, to have it slideToggle, is affecting its siblings and opening and closing at the same time.

my structure look something like this:

Home

Item1

SubItem - 1

SubItem - 2

SubItem - 3

SubItem - 4

SubItem - 5

Item - 2

SubItem - 1

SubItem - 2

SubItem - 3

SubItem - 4

SubItem - 5

Item - 3

            <
SubItem - 1

SubItem - 2

SubItem - 3

SubItem - 4

SubItem - 5

Item - 4

Item - 5

About

Services

Blog

Contact

and this is my jQuery:

$('.has-children ul').click(function(e){
    e.stopPropagation();
    var el = (event.target || event.srcElement);
    console.log('clicked');
    $(this).find('ul.submenu').slideToggle();
     $(el).find('span').toggleClass('arrow-down arrow-up');
  });

So if I click on the li with the class of has children, all my uls with class of submenu are opening at the same time.
Perhaps I am doing more than I am supposed to here, all the help would be appreciate it.

Body:
try this code (i have added more correct span finding)

$('.has-children ul').click(function(e){
e.stopPropagation();
var el = (event.target || event.srcElement);
console.log('clicked');
$(this).find('ul.submenu').slideToggle();
 $(this).parent().find('span').toggleClass('arrow-down arrow-up');
});


问:
Angular ActionCable call method in component when notification received
I'm trying to practice using ActionCable in Angular.  I created a quick Rails application that I put up on Heroku and then created an Angular application with the actioncable npm module as a dependency.

I configured my Rails appplication to allow http://localhost:4200 as an origin while I play around with my Angular app in development.  I also didn't make this an API application because I wanted to have a working UI from the get-go.  So I can log into the Rails application, send a message, and my separate Angular application is subscribed to that channel as well.  I'm successfully receiving those notifications/messages.

Now I'd like to render something in Angular based on that message.  I think I'm missing something pretty silly here, but I cannot refer to methods in the component that instantiates the subscription to that channel in the receive callback of the subscription.

```<code>import {
  ComponentFactoryResolver,
  ComponentRef,
  OnInit,
  ViewContainerRef,
  Component,
  ViewChild,
  Output
} from '@angular/core';
import * as ActionCable from 'actioncable';
import { MessageComponent } from 'app/message/message.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  messageRef: ComponentRef<MessageComponent>;
  @ViewChild('message', { read: ViewContainerRef }) message: ViewContainerRef;

  title = 'app works!';
  private cable: ActionCable.Cable;
  private subscription: ActionCable.Channel;

  constructor(
    private componentFactoryResolver: ComponentFactoryResolver,
    private viewContainerRef: ViewContainerRef) {
  }

  public ngOnInit(): void {
    this.cable = ActionCable.createConsumer('wss://<my-heroku-app>.herokuapp.com/cable');
    this.subscription = this.cable.subscriptions.create(
      'RoomChannel',
      {
         connected: this.connected,
         disconnected: this.disconnected,
         received: this.received,
      });
   }

  private showMessage(messageString) {
    if (!this.messageRef) {
      const messageComponent = this.componentFactoryResolver.resolveComponentFactory(MessageComponent);
      this.messageRef = this.message.createComponent(messageComponent);
    }
    this.messageRef.instance.message = messageString;
    this.messageRef.changeDetectorRef.detectChanges();
  }

  private connected() {
    console.log('connected!');
  }

  private disconnected() {
    console.log('disconnected!');
  }

  private received(data: any) {
    console.log('received');
    // What do I put here? `this` is of type Subscription,
    // and thus, I can't call `this.showMessage(data.message)`
  }
}
</code>```

I want to use some sort of predicate or inject something into that context (sorry if I'm not using the right terminology), but I am just not sure how to do this.  I plan on cleaning things up instead of having this all in the AppComponent class, but for now I'm just trying to learn.

Any ideas?  Thanks!

答:
The answer seems to be this:</p>

```<code>this.cable = ActionCable.createConsumer(this.url)
this.subscription = this.cable.subscriptions.create(
  'RoomChannel',
  {
    connected: this.connected,
    disconnected: this.disconnected,
    // The key here, apparently, is to use a fat-arrow
    // function so that the `this` I care about is
    // lexicographically scoped.  I still need to better
    // understand what exactly that means, but I have a
    // general idea.
    received: (data) => this.received(data)
  });
</code>```

Body:
I'm trying to practice using ActionCable in Angular.  I created a quick Rails application that I put up on Heroku and then created an Angular application with the actioncable npm module as a dependency.

I configured my Rails appplication to allow http://localhost:4200 as an origin while I play around with my Angular app in development.  I also didn't make this an API application because I wanted to have a working UI from the get-go.  So I can log into the Rails application, send a message, and my separate Angular application is subscribed to that channel as well.  I'm successfully receiving those notifications/messages.

Now I'd like to render something in Angular based on that message.  I think I'm missing something pretty silly here, but I cannot refer to methods in the component that instantiates the subscription to that channel in the receive callback of the subscription.

import {
  ComponentFactoryResolver,
  ComponentRef,
  OnInit,
  ViewContainerRef,
  Component,
  ViewChild,
  Output
} from '@angular/core';
import * as ActionCable from 'actioncable';
import { MessageComponent } from 'app/message/message.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  messageRef: ComponentRef<MessageComponent>;
  @ViewChild('message', { read: ViewContainerRef }) message: ViewContainerRef;

  title = 'app works!';
  private cable: ActionCable.Cable;
  private subscription: ActionCable.Channel;

  constructor(
    private componentFactoryResolver: ComponentFactoryResolver,
    private viewContainerRef: ViewContainerRef) {
  }

  public ngOnInit(): void {
    this.cable = ActionCable.createConsumer('wss://<my-heroku-app>.herokuapp.com/cable');
    this.subscription = this.cable.subscriptions.create(
      'RoomChannel',
      {
         connected: this.connected,
         disconnected: this.disconnected,
         received: this.received,
      });
   }

  private showMessage(messageString) {
    if (!this.messageRef) {
      const messageComponent = this.componentFactoryResolver.resolveComponentFactory(MessageComponent);
      this.messageRef = this.message.createComponent(messageComponent);
    }
    this.messageRef.instance.message = messageString;
    this.messageRef.changeDetectorRef.detectChanges();
  }

  private connected() {
    console.log('connected!');
  }

  private disconnected() {
    console.log('disconnected!');
  }

  private received(data: any) {
    console.log('received');
    // What do I put here? `this` is of type Subscription,
    // and thus, I can't call `this.showMessage(data.message)`
  }
}

I want to use some sort of predicate or inject something into that context (sorry if I'm not using the right terminology), but I am just not sure how to do this.  I plan on cleaning things up instead of having this all in the AppComponent class, but for now I'm just trying to learn.

Any ideas?  Thanks!

Body:
The answer seems to be this:

this.cable = ActionCable.createConsumer(this.url)
this.subscription = this.cable.subscriptions.create(
  'RoomChannel',
  {
    connected: this.connected,
    disconnected: this.disconnected,
    // The key here, apparently, is to use a fat-arrow
    // function so that the `this` I care about is
    // lexicographically scoped.  I still need to better
    // understand what exactly that means, but I have a
    // general idea.
    received: (data) => this.received(data)
  });


问:
How to improve query performance to s3 data from Athena
I have partitioned data stored in S3 in hive format like this.

```<code>bucket/year=2017/month=3/date=1/filename.json
bucket/year=2017/month=3/date=2/filename1.json
bucket/year=2017/month=3/date=3/filename2.json
</code>```

Every partition has around 1,000,000 records. I have created table and partitions in Athena for this.

Now running query from Athena

```<code>select count(*) from mts_data_1 where year='2017' and month='3' and date='1'
</code>```

this query is taking 1800 seconds to scan 1,000,000 records.

So my question is how can I improve this query performance?

答:
I think the problem is that Athena has to read so many files from S3.  250 MB isn't so much data, but 1,000,000 files is a lot of files.  Athena query performance will improve dramatically if you reduce the number of files, and compressing the aggregated files will help some more.  How many files do you need for one day's partition?  Even with one-minute resolution, you would need less than 1,500 files. If the current query time is ~30 minutes, you might easily start with a lot less.

There are many options for aggregating and compressing your records:

AWS's Kinesis Firehose is a fairly simple way to start on exactly this sort of problem.

A streaming data processing tool like Apache NiFi would offer a richer set of tranformation, aggregation, and compression options.  I've written a blog post  about using Apache NiFi to stream data to S3 for Athena, covering these same issues.

Body:
I have partitioned data stored in S3 in hive format like this.

bucket/year=2017/month=3/date=1/filename.json
bucket/year=2017/month=3/date=2/filename1.json
bucket/year=2017/month=3/date=3/filename2.json

Every partition has around 1,000,000 records. I have created table and partitions in Athena for this.

Now running query from Athena

select count(*) from mts_data_1 where year='2017' and month='3' and date='1'

this query is taking 1800 seconds to scan 1,000,000 records.

So my question is how can I improve this query performance?


问:
how put directory in string , in dart?
I want to know what the current directory is. I don't want to shell out to run pwd. Is there an easy way to do this in Dart?
and also,
Is there a way, put name of directory into a string?</p>

答:
Re the current directory, from the documentation from the Directory class in dart:io (emphasis added).

In addition to being used as an instance to access the file system,
  Directory has a number of static properties, such as systemTemp, which
  gets the system's temporary directory, and the getter and setter
  current, which you can use to access or change the current directory.

To get the name of a Directory as a string just use toString(), or perhaps the path property.

Title: how put directory in string , in dart?


问:
How to click on the basis of style attribute in java selenium
I want to click on element which appears like a button on webpage using style attribute of div tag.

But I am not able to do so. I referred stack overflow but with the help of that its returning blank element . I don't want any text. I want that it should be clicked and the list appears and I want to select one item from that list. So how to do that?

Below is my code :

```<code><div style="width: auto; height: 386px;" class="QvGraph">
<img src=" " style="width: 710px; height: 386px; cursor: crosshair; visibility: visible; display: block;"></img>
<div style="cursor: pointer; position: absolute; top: 4px; left: 588px; height: 18px; width: 27px;" class="Qv_Hotspot"></div>
<div style="cursor: pointer; position: absolute; top: 3px; left: 3px; height: 18px; width: 18px;" class="Qv_Hotspot"></div></div>
</div>
</code>```

I have tried this below code, but it didn't get work for me.

```<code>driver.findElement(By.xpath("//div[@class ='Qv_HotSpot']")).getAttribute("cursor: pointer; position: absolute; top: 4px; left: 588px; height: 18px; width: 27px;");
</code>```

I am badly stuck here .Thanks in advance !

答:
Try this below code.

If you want to click on
 tag style attribute use below code.

```<code>driver.findElement(By.xpath("//div[@class='Qv_Hotspot'][@style='cursor: pointer; position: absolute; top: 4px; left: 588px; height: 18px; width: 27px;']")).click();
</code>```

Explanation of xpath:- Use class and style attribute of
 tag.

Body:
I want to click on element which appears like a button on webpage using style attribute of div tag.

But I am not able to do so. I referred stack overflow but with the help of that its returning blank element . I don't want any text. I want that it should be clicked and the list appears and I want to select one item from that list. So how to do that?

Below is my code :

I have tried this below code, but it didn't get work for me.

driver.findElement(By.xpath("//div[@class ='Qv_HotSpot']")).getAttribute("cursor: pointer; position: absolute; top: 4px; left: 588px; height: 18px; width: 27px;");

I am badly stuck here .Thanks in advance !

Body:
Try this below code.

If you want to click on <div> tag style attribute use below code.

driver.findElement(By.xpath("//div[@class='Qv_Hotspot'][@style='cursor: pointer; position: absolute; top: 4px; left: 588px; height: 18px; width: 27px;']")).click();

Explanation of xpath:- Use class and style attribute of <div> tag.


问:
IndexedDB work in Android native app
We've got application to view some specific materials. Among material types there is HTML5 presentation that is shown in WebView widget inside app. And now we need to get detailed information about this view (for example slide show duration, list element pick where it is available, etc).

It is what customer wants - we can't change it.

We decided to use IndexedDB inside HTML5 to store information locally. Now storing works (as I know :) ). Next problem is to get this information by app and it is not solved yet. Unfortunately google didn't help me.

How to get information from IndexedDB file if I know its path? Or do you know another way to transfer data from html to native app?

P.S. Writing custom browser could not be solution.

Update

Found solution to load file from JS. In chrome browser it automatically saves in downloads. In android app I'm setting to WebView object DownloadListener to listen file save event.

Catching save file works perfect. But the url path is looks like blob:file/... and I can't get info from it. Tried using ContentResolver, create File object, replace blob: string with nothing, start ACTION_VIEW intent - nothing helped.

Update

Tried to use DownloadManager and DownloadManager.Request - it throws following exception

```<code>java.lang.IllegalArgumentException: Can only download HTTP/HTTPS URIs: file:///fa4857ad-0e86-454a-a341-123729e9ece0
</code>```

Same with blob:file uri.

答:
You can solve the problem by hack by calling the JavaScript function from Java and returning the required attributes in specific pattern. To implement this

Create the javascript function which will return the attributes in
specific pattern.

Create the WebChromClient and override onJsAlert() method. message
parameter of onJsAlert has the returned string of message. Parse the
message string to get the required attributes.

Call the JavaScript function from Java code to get the value.

```<code>final class MyWebChromeClient extends WebChromeClient {
    @Override
    public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
        result.confirm();
        // Parse the message to get the required attributes
        Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
        return true;
   }
}
</code>```

To call the JavaScript function to get the data use the below code. Here testFunction() is the fucntion which will return the data in string format.

```<code>webView.loadUrl("javascript:alert(testFunction())");
</code>```

Create the instance of WebChromeClient and set in webview and also don't forget to enable the JavaScript.

```<code>WebView webView = (WebView)findViewById(R.id.web_view);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new MyWebChromeClient());
</code>```

Title: IndexedDB work in Android native app

Body:
We've got application to view some specific materials. Among material types there is HTML5 presentation that is shown in WebView widget inside app. And now we need to get detailed information about this view (for example slide show duration, list element pick where it is available, etc).

It is what customer wants - we can't change it.

We decided to use IndexedDB inside HTML5 to store information locally. Now storing works (as I know :) ). Next problem is to get this information by app and it is not solved yet. Unfortunately google didn't help me.

How to get information from IndexedDB file if I know its path? Or do you know another way to transfer data from html to native app?

P.S. Writing custom browser could not be solution.

Update

Found solution to load file from JS. In chrome browser it automatically saves in downloads. In android app I'm setting to WebView object DownloadListener to listen file save event.

Catching save file works perfect. But the url path is looks like blob:file/... and I can't get info from it. Tried using ContentResolver, create File object, replace blob: string with nothing, start ACTION_VIEW intent - nothing helped.

Update

Tried to use DownloadManager and DownloadManager.Request - it throws following exception

java.lang.IllegalArgumentException: Can only download HTTP/HTTPS URIs: file:///fa4857ad-0e86-454a-a341-123729e9ece0

Same with blob:file uri.

Body:
You can solve the problem by hack by calling the JavaScript function from Java and returning the required attributes in specific pattern. To implement this

Create the javascript function which will return the attributes in
specific pattern.

Create the WebChromClient and override onJsAlert() method. message
parameter of onJsAlert has the returned string of message. Parse the
message string to get the required attributes.

Call the JavaScript function from Java code to get the value.

final class MyWebChromeClient extends WebChromeClient {
    @Override
    public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
        result.confirm();
        // Parse the message to get the required attributes
        Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
        return true;
   }
}

To call the JavaScript function to get the data use the below code. Here testFunction() is the fucntion which will return the data in string format.

webView.loadUrl("javascript:alert(testFunction())");

Create the instance of WebChromeClient and set in webview and also don't forget to enable the JavaScript.

WebView webView = (WebView)findViewById(R.id.web_view);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new MyWebChromeClient());


问:
C#: Can't get value of cells in grid view
```<code>GridView1.Rows[0].Cells[0].Text
</code>```

Why can't I get the value of the cell in grid view.
Instead, it is giving me "&nbsp"

答:
You can Try code

```<code>string str;
str = DataGridView1.Rows[DataGridView.SelectedRows[0].Index].Cells[X].Value.ToString();
</code>```

Or

```<code>textBox1.Text = dataGridView1.CurrentRow.Cells[X].Value.ToString();
</code>```

Body:
GridView1.Rows[0].Cells[0].Text

Why can't I get the value of the cell in grid view.
Instead, it is giving me "&nbsp"

Body:
You can Try code

string str;
str = DataGridView1.Rows[DataGridView.SelectedRows[0].Index].Cells[X].Value.ToString();

Or

textBox1.Text = dataGridView1.CurrentRow.Cells[X].Value.ToString();


问:
Can a delim be used more than once for strtok in C?
Is there a way to use a delim more then once for strtok? I can only get the code to work for either load or init but not both. Example code in which strtok is used to token input from the user in the form of load # or init #,#,direction:</p>

```<code>if ((tok = strtok(choice, " ")) && strcmp(tok, COMMAND_LOAD) == 0){
    tok = NULL;
    if((tok = strtok(tok, " ")) != NULL){
    /*some code*/
    }
}
else if((tok = strtok(choice, " ")) && strcmp(tok, COMMAND_INIT) == 0){
    tok = NULL;
    if((tok = strtok(tok, ",")) != NULL){
    /*some code*/
    }
}
</code>```

答:
The strtok function is not reentrant, you can not use it for multiple simultaneously tokenizations.

Use strtok_s instead, if you have it. Or strtok_r is you have it.

Body:
Is there a way to use a delim more then once for strtok? I can only get the code to work for either load or init but not both. Example code in which strtok is used to token input from the user in the form of load # or init #,#,direction:

if ((tok = strtok(choice, " ")) && strcmp(tok, COMMAND_LOAD) == 0){
    tok = NULL;
    if((tok = strtok(tok, " ")) != NULL){
    /*some code*/
    }
}
else if((tok = strtok(choice, " ")) && strcmp(tok, COMMAND_INIT) == 0){
    tok = NULL;
    if((tok = strtok(tok, ",")) != NULL){
    /*some code*/
    }
}


问:
Aligning text and image on UIButton with imageEdgeInsets and titleEdgeInsets
I would like to place an icon left of the two lines of text such that there's about 2-3 pixels of space between the image and the start of text. The control itself is Center aligned horizontally (set through Interface Builder)

The button would resemble something like this:

```<code>|                  |
|[Image] Add To    |
|        Favorites |
</code>```

I'm trying to configure this with contentEdgeInset, imageEdgeInsets and titleEdgeInsets to no avail. I understand that a negative value expands the edge while a positive value shrinks it to move it closer to the center.

I tried:

```<code>[button setTitleEdgeInsets:UIEdgeInsetsMake(0, -image.size.width, 0, 0)];
[button setImageEdgeInsets:UIEdgeInsetsMake(0, button.titleLabel.bounds.size.width, 0, 0)];
</code>```

but this doesn't display it correctly. I've been tweaking the values but going from say -5 to -10 on the left inset value doesn't appear to move it in expected manner. -10 will scoot the text all the way to the left so I expected -5 to scoot it half way from the left side but it doesn't.

What's the logic behind insets? I'm not familiar with image placements and related terminology.

I used this SO question as a reference but something about my values isn't right.
UIButton: how to center an image and a text using imageEdgeInsets and titleEdgeInsets?

答:
In Xcode 8.0 you can simply do it by changing insets in size inspector.

Select the UIButton ->  Attributes Inspector -> go to size inspector and modify the content, image and title insets.

And if you want to change image on right side you can simply change the semantic property to Force Right-to-left in Attribute inspector .

Body:
I would like to place an icon left of the two lines of text such that there's about 2-3 pixels of space between the image and the start of text. The control itself is Center aligned horizontally (set through Interface Builder)

The button would resemble something like this:

|                  |
|[Image] Add To    |
|        Favorites |

I'm trying to configure this with contentEdgeInset, imageEdgeInsets and titleEdgeInsets to no avail. I understand that a negative value expands the edge while a positive value shrinks it to move it closer to the center.

I tried:

[button setTitleEdgeInsets:UIEdgeInsetsMake(0, -image.size.width, 0, 0)];
[button setImageEdgeInsets:UIEdgeInsetsMake(0, button.titleLabel.bounds.size.width, 0, 0)];

but this doesn't display it correctly. I've been tweaking the values but going from say -5 to -10 on the left inset value doesn't appear to move it in expected manner. -10 will scoot the text all the way to the left so I expected -5 to scoot it half way from the left side but it doesn't.

What's the logic behind insets? I'm not familiar with image placements and related terminology.

I used this SO question as a reference but something about my values isn't right.
UIButton: how to center an image and a text using imageEdgeInsets and titleEdgeInsets?


问:
Python Firebase replace the auto-generated Key
I was adding some data to Firebase with Python and I want to use the MD5 strings I generated as the unique index for each record.
The auto-generated key in Firebase looks like "-KgMvzKKxVgj4RKN-3x5". Is it possible to replace its value with Python? I know how to do it with Javascript though. Please help... Thanks in advance!

```<code>f = firebase.FirebaseApplication('https://xxxxx.firebaseio.com')
f.post('meeting/',
    {
     "MD5index":MD5String,
     "title": title,
     "date": date,
     "time": time,
     "location": location
     })
</code>```

答:
It sure is. Just use put instead of post:

```<code>f = firebase.FirebaseApplication('https://xxxxx.firebaseio.com')
f.put('meeting/mymeetingkey',
    {
     "MD5index":MD5String,
     "title": title,
     "date": date,
     "time": time,
     "location": location
     })
</code>```

Body:
I was adding some data to Firebase with Python and I want to use the MD5 strings I generated as the unique index for each record.
The auto-generated key in Firebase looks like "-KgMvzKKxVgj4RKN-3x5". Is it possible to replace its value with Python? I know how to do it with Javascript though. Please help... Thanks in advance!

f = firebase.FirebaseApplication('https://xxxxx.firebaseio.com')
f.post('meeting/',
    {
     "MD5index":MD5String,
     "title": title,
     "date": date,
     "time": time,
     "location": location
     })

Body:
It sure is. Just use put instead of post:

f = firebase.FirebaseApplication('https://xxxxx.firebaseio.com')
f.put('meeting/mymeetingkey',
    {
     "MD5index":MD5String,
     "title": title,
     "date": date,
     "time": time,
     "location": location
     })


问:
Multiple cache implementations at method level in Spring Boot
What I want is, two different cache implementations (let's say Redis and EhCache) on one method. Meaning @Cacheable method should cache both Redis and EhCache.

Is it even possible?

答:
Option 1:
Stack the caches. Configure the local cache in Spring. Then wire in the distributed cache via a CacheLoader/CacheWriter. Consistency needs to be carefully evaluated. E.g. if an update goes to the distributed cache, how do you invalidate the local caches? That is not so trivial. Maybe it is easy and not needed for your data, maybe it is near to impossible.

Option 2:
Go with a distributed cache which provides a so called near cache. That is actually the combination you want to do by yourself, but combined in a product. I know that hazelcast and Infinispan offer a near cache. However, your mileage may vary regarding consistency and resilience. I know that hazelcast just recently enhanced the near cache, so it is consistent.

Interesting use case and actually a common problem. Further thoughts and discussion highly appreciated.


问:
Doesn't retrieve the related table data in Entity Framework Core with PostgreSQL
I'm trying Entity Framework Core with PostgreSQL. I have two tables that are one to many relationship. According to the relationship, Movie has a Year and Year has many Movies. But Once I retrieve movies, the year doesn't contain in it, year in each movie is null unless retrieving the years. But after retrieving the years, movies becoming having the years. When I move the year retrieving code line to up. It's happened the same. The years don't have the movies unless retrieving the movies. Then, After retrieving the movies, the selected years becoming having the movies. Can anyone know how to solve it? It's like lazy loading.

Here is my two entity.

```<code>public class T_MOVIE
{
    [Key]
    public long Oid { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public DateTime CreatedDate { get; set; }
    public long? YearOid { get; set; }
    [ForeignKey("YearOid")]
    public T_YEAR MOVIE_YEAR { get; set; }
}

public class T_YEAR
{
    public T_YEAR()
    {
        this.YEAR_MOVIEs = new HashSet<DataModel.T_MOVIE>();
    }
    [Key]
    public long Oid { get; set; }
    public string Name { get; set; }
    public ICollection<T_MOVIE> YEAR_MOVIEs { get; set; }
}
</code>```

And in the OnModelCreating,

```<code>protected override void OnModelCreating(ModelBuilder builder)
{
    builder.Entity<T_MOVIE>().HasKey(m => m.Oid);
    builder.Entity<T_MOVIE>().HasOne(m => m.MOVIE_YEAR).WithMany(m => m.YEAR_MOVIEs);

    builder.Entity<T_YEAR>().HasKey(m => m.Oid);
    builder.Entity<T_YEAR>().HasMany(m => m.YEAR_MOVIEs).WithOne(m => m.MOVIE_YEAR);
}
</code>```

Then, I retrieve the data.

```<code>var movies = _db.T_MOVIE.ToList();
var years = _db.T_YEAR.ToList();
</code>```

Thank you.

答: You have to add "Include()" in your query. Unless doing that, it returns null relations.</p>

Body:
I'm trying Entity Framework Core with PostgreSQL. I have two tables that are one to many relationship. According to the relationship, Movie has a Year and Year has many Movies. But Once I retrieve movies, the year doesn't contain in it, year in each movie is null unless retrieving the years. But after retrieving the years, movies becoming having the years. When I move the year retrieving code line to up. It's happened the same. The years don't have the movies unless retrieving the movies. Then, After retrieving the movies, the selected years becoming having the movies. Can anyone know how to solve it? It's like lazy loading.

Here is my two entity.

public class T_MOVIE
{
    [Key]
    public long Oid { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public DateTime CreatedDate { get; set; }
    public long? YearOid { get; set; }
    [ForeignKey("YearOid")]
    public T_YEAR MOVIE_YEAR { get; set; }
}

public class T_YEAR
{
    public T_YEAR()
    {
        this.YEAR_MOVIEs = new HashSet<DataModel.T_MOVIE>();
    }
    [Key]
    public long Oid { get; set; }
    public string Name { get; set; }
    public ICollection<T_MOVIE> YEAR_MOVIEs { get; set; }
}

And in the OnModelCreating,

protected override void OnModelCreating(ModelBuilder builder)
{
    builder.Entity<T_MOVIE>().HasKey(m => m.Oid);
    builder.Entity<T_MOVIE>().HasOne(m => m.MOVIE_YEAR).WithMany(m => m.YEAR_MOVIEs);

    builder.Entity<T_YEAR>().HasKey(m => m.Oid);
    builder.Entity<T_YEAR>().HasMany(m => m.YEAR_MOVIEs).WithOne(m => m.MOVIE_YEAR);
}

Then, I retrieve the data.

var movies = _db.T_MOVIE.ToList();
var years = _db.T_YEAR.ToList();

Thank you.


问:
Font Size in Datagrid
How to reduce the Font Size of Text in Rows of Data Grid in Flex ?</p>

答: You could change the fontSize style property of the grid and increase the rowHeight at the same time.</p>

Title: Font Size in Datagrid


问:
Is there a way to spoof rooted android's light sensor values
Since Samsungs, note 4 in particular have an ultra bright screen mode (750nits) that automatically activates when the device is exposed to direct sun light I am wondering if in some way I can change the reading of the light sensor so I trick it into that mode whenever I want.

If possible at all, talking about rooted Android.

答: Found a solution. Xposed is required and https://github.com/wardellchandler/disableproxsensor this app or your own implementation of xposed's magic.</p>


问:
VSIX How to get project output type in code
Here is the xml code I got from project.csproj

```<code><?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build"    xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{C5BEBB57-E9AD-4EAF-B7EF-43DF7ACE2B8F}</ProjectGuid>
<OutputType>WinExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>WpfApplication3</RootNamespace>
<AssemblyName>WpfApplication3</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<WarningLevel>4</WarningLevel>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>...
</code>```

Is there any way to cast value of ot to OutputType which is 'WinExe' in code?

Thanks in advance.

答: You can get the project type using ProjectTypeGuids combination value. For example, your project is a WPF C# project. List of ProjectTypeGuids can be found here.</p>

Body:
Here is the xml code I got from project.csproj

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build"    xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{C5BEBB57-E9AD-4EAF-B7EF-43DF7ACE2B8F}</ProjectGuid>
<OutputType>WinExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>WpfApplication3</RootNamespace>
<AssemblyName>WpfApplication3</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<WarningLevel>4</WarningLevel>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>...

Is there any way to cast value of ot to OutputType which is 'WinExe' in code?

Thanks in advance.


问:
How to get entire GIT repo url in TFS?
Only got a repo name and project name from my colleague.

How do I get the entire GIT repo url in TFS? What pattern does it follow?

Could I directly use the url in the browser from web?

答:
Yes, you could directly use the url when you open the repo in the web portal.

A more common approach is using Clone  command in the top right corner. You should either select http or ssh url and just click copy command.

As for the format, the url will be something as below:

```<code>http://yourtfsserver/[CollectionName]/_git/[gitRepoName]
</code>```

More details please take a look at the answer from bryanmac in this question:  Connect to git repository in TFS or Visual Studio Online

Title: How to get entire GIT repo url in TFS?

Body:
Yes, you could directly use the url when you open the repo in the web portal.

A more common approach is using Clone  command in the top right corner. You should either select http or ssh url and just click copy command.

As for the format, the url will be something as below:

http://yourtfsserver/[CollectionName]/_git/[gitRepoName]

More details please take a look at the answer from bryanmac in this question:  Connect to git repository in TFS or Visual Studio Online


问:
Webview shows blank screen
I know the question may be redundant but I've tried many solutions and nothing could have helped me.
In my app, once the user is clicking on a button, it transfers the user to another page. On this page I have a Webview, and a button. They are defined in my xml file as follows:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:layout_weight="1" >

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="right"
    android:text="Log out"
    android:id="@+id/btLogot" />

    <WebView
        android:layout_width="fill_parent"
        android:layout_height="0px"
        android:layout_weight="3"
        android:id="@+id/webView"
         />

</LinearLayout>
</code>```

In the other hand, I have used WebViewClient() and override it with shouldOverrideUrlLoading().
The problem is, nothing happens.
I think my code is alright, but there's something wrong with my xml and weight of my layouts.

So, what's the matter?!

答:
Some people from other discussions said: that you should use Relative Layout with the Webview!

You can try doing this =)

Title: Webview shows blank screen

Body:
I know the question may be redundant but I've tried many solutions and nothing could have helped me.
In my app, once the user is clicking on a button, it transfers the user to another page. On this page I have a Webview, and a button. They are defined in my xml file as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:layout_weight="1" >

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="right"
    android:text="Log out"
    android:id="@+id/btLogot" />

    <WebView
        android:layout_width="fill_parent"
        android:layout_height="0px"
        android:layout_weight="3"
        android:id="@+id/webView"
         />

</LinearLayout>

In the other hand, I have used WebViewClient() and override it with shouldOverrideUrlLoading().
The problem is, nothing happens.
I think my code is alright, but there's something wrong with my xml and weight of my layouts.

So, what's the matter?!


问:
VSTS PowerShell Task and Azure AD cmdlets
I would like to run a PowerShell script during deployment using a PowerShell Script Task in VSTS release. I need to do some operation with Azure Active Directory, but right now I have no access to it, although running locally works fine.

For example running Get-AzureRmADApplication gives "Insufficient privileges to complete the operation".

Any solutions or suggestions to this issue?

P. S. Actually I was using Azure PowerShell task.

答:
I can reproduce the issue, there is a similar issue: New-AzureRmADApplication: Access denied to the specified API version

I submit a new issue Get-AzureRmADApplication Access denied to the specified API version, you can follow up it.


问:
SQL Data Filtering approach
I have a stored procedure that receives 3 parameters that are used to dynamically filter the result set

```<code>create proc MyProc
@Parameter1 int,
@Parameter2 int,
@Paremeter3 int
as
select * from My_table
where
1 = case when @Parameter1 = 0 then 1 when @Parameter1 = Column1 then 1 else 0 end
and
1 = case when @Parameter2 = 0 then 1 when @Parameter2 = Column2 then 1 else 0 end
and
1 = case when @Parameter3 = 0 then 1 when @Parameter3 = Column3 then 1 else 0 end
return
</code>```

The values passed for each parameter can be 0 (for all items) or non-zero for items matching on specific column.

I may have upwards of 20 parameters (example shown only has 3).  Is there a more elegant approach to allow this to scale when the database gets large?

答:
I am using something similar to your idea:

```<code>select *
from TableA
where
    (@Param1 is null or Column1 = @Param1)
    AND (@Param2 is null or Column2 = @Param2)
    AND (@Param3 is null or Column3 = @Param3)
</code>```

It is generally the same, but I used NULLs as neutral value instead of 0. It is more flexible in a sense that it doesn't matter what is the data type of the @Param variables.

Title: SQL Data Filtering approach

Body:
I have a stored procedure that receives 3 parameters that are used to dynamically filter the result set

create proc MyProc
@Parameter1 int,
@Parameter2 int,
@Paremeter3 int
as
select * from My_table
where
1 = case when @Parameter1 = 0 then 1 when @Parameter1 = Column1 then 1 else 0 end
and
1 = case when @Parameter2 = 0 then 1 when @Parameter2 = Column2 then 1 else 0 end
and
1 = case when @Parameter3 = 0 then 1 when @Parameter3 = Column3 then 1 else 0 end
return

The values passed for each parameter can be 0 (for all items) or non-zero for items matching on specific column.

I may have upwards of 20 parameters (example shown only has 3).  Is there a more elegant approach to allow this to scale when the database gets large?

Body:
I am using something similar to your idea:

select *
from TableA
where
    (@Param1 is null or Column1 = @Param1)
    AND (@Param2 is null or Column2 = @Param2)
    AND (@Param3 is null or Column3 = @Param3)

It is generally the same, but I used NULLs as neutral value instead of 0. It is more flexible in a sense that it doesn't matter what is the data type of the @Param variables.


问:
Javascript, looping through an array and the arguments "object"
I can't get my head around this, i'm using filter to loop through an array and filter out all the integers passed as arguments ,i'm not limited in the number of arguments.

But i'm stuck here when it's about to get back to the function the value of the arguments object, at least more that once.

In my code below, obviously it's not fully working because i'm doing a return within the for…in loop, this is where i don't get how I can get the this second loop without having i re-initialised to 0…

function destroyer(arr) {
  var args = arguments.length;
  var arg0 = arguments[0];
  var Nargs = Array.prototype.slice.call(arguments, 1);
  var newArr = [];

    newArr = arg0.filter(filtre);

    /*Only the first argument is
    filtered out,here it's the value "2",
    but should filter out [2,3].
    The expected result is [1,1]*/
    console.log(newArr);
    return newArr;

     function filtre(e){

         for (var i in Nargs){

           return e !== Nargs[i];
         }
     }
}

destroyer([1, 2, 3, 1, 2, 3], 2,3);```

Hope this is clear enough,

Thanks for any input !

Matth.

答:
While rgthree provided a solution very similar to what you already had, I wanted to provide a solution that takes advantage of newer ES6 features for modern browsers. If you run this through Babel, it will result in essentially the same code as in that solution, though it will still require a shim for the includes call.

```<code>function destroyer(source, ...args) {
    return source.filter(el => !args.includes(el));
}
</code>```

Explanation:

...args uses the spread operator to get all but the first argument into an array named args.

We can directly return the filtered array, assuming you don't need to log it and that was just for debugging.

el => !args.includes(el) is an anonymous arrow function. Since no braces are used, it will automatically return the result of the expression.

Since args is an array, we can directly use Array.prototype.includes to check if the current element is in the arguments to be removed. If it exists, we want to remove it and thus invert the return with !. An alternative could be the following: el => args.includes(el) == false.

Body:
I can't get my head around this, i'm using filter to loop through an array and filter out all the integers passed as arguments ,i'm not limited in the number of arguments.

But i'm stuck here when it's about to get back to the function the value of the arguments object, at least more that once.

In my code below, obviously it's not fully working because i'm doing a return within the for…in loop, this is where i don't get how I can get the this second loop without having i re-initialised to 0…

function destroyer(arr) {
  var args = arguments.length;
  var arg0 = arguments[0];
  var Nargs = Array.prototype.slice.call(arguments, 1);
  var newArr = [];

    newArr = arg0.filter(filtre);

    /*Only the first argument is
    filtered out,here it's the value "2",
    but should filter out [2,3].
    The expected result is [1,1]*/
    console.log(newArr);
    return newArr;

     function filtre(e){

         for (var i in Nargs){

           return e !== Nargs[i];
         }
     }
}

destroyer([1, 2, 3, 1, 2, 3], 2,3);

Hope this is clear enough,

Thanks for any input !

Matth.

Body:
While rgthree provided a solution very similar to what you already had, I wanted to provide a solution that takes advantage of newer ES6 features for modern browsers. If you run this through Babel, it will result in essentially the same code as in that solution, though it will still require a shim for the includes call.

function destroyer(source, ...args) {
    return source.filter(el => !args.includes(el));
}

Explanation:

...args uses the spread operator to get all but the first argument into an array named args.

We can directly return the filtered array, assuming you don't need to log it and that was just for debugging.

el => !args.includes(el) is an anonymous arrow function. Since no braces are used, it will automatically return the result of the expression.

Since args is an array, we can directly use Array.prototype.includes to check if the current element is in the arguments to be removed. If it exists, we want to remove it and thus invert the return with !. An alternative could be the following: el => args.includes(el) == false.


问:
Time complexity of c++ array loop
i have the following loop but am unable to calculate the complexity .I need help

```<code>int A[n][n];
for(int i=0; i<n;i++) {
    for(int j=0;j<n;j++) {
        int x;
        cin >> x;
        A[i][j] = x;
    }
}
int sumLine = 0;
for(int k=0;k<n;k++) {
    sumLine += A[k][0];
}
</code>```

i would appreciate

答: Time complexity will be O(n^2). Read more about time complexity here - How to find time complexity of an algorithm . It has some good explanation here. </p>

Title: Time complexity of c++ array loop

Body:
i have the following loop but am unable to calculate the complexity .I need help

int A[n][n];
for(int i=0; i<n;i++) {
    for(int j=0;j<n;j++) {
        int x;
        cin >> x;
        A[i][j] = x;
    }
}
int sumLine = 0;
for(int k=0;k<n;k++) {
    sumLine += A[k][0];
}

i would appreciate


问:
Dynamically Swapping Material Icons with VueJS
Generally, I use static google material icons like this.

```<code><i class="material-icons"></i>
</code>```

However, I want to dynamically change the material icon using a computed property with VueJS. I tried the following:

```<code><i class="material-icons font-size-36-i">{{ materialIconCode }}</i>

computed: {
  materialIconCode: function () {
    return '&#xE85E'
  }
}
</code>```

It does not work instead it displays &# E  E on the page with the numbers missing.

Any ideas?

答:
https://jsfiddle.net/guanzo/tbm75a06/

The mustache syntax interprets the data as text. Use the directive v-html="materialIconCode" to set the html of an element.

Body:
Generally, I use static google material icons like this.



However, I want to dynamically change the material icon using a computed property with VueJS. I tried the following:

{{ materialIconCode }}

computed: {
  materialIconCode: function () {
    return '&#xE85E'
  }
}

It does not work instead it displays &# E  E on the page with the numbers missing.

Any ideas?