问:
Jquery custom trigger anchor tag
Hello every one I am creating custom multistep form but when I click on next button it can't trigger related  anchor tag ( auto click )

Please help me to resolve my issue

Thanks in Advance

$(function() {
  $("#nextBtn").click(function() {
    var $tabs = $("li");
    $tabs.each(function() {

      var activeTab = $(this).hasClass("active");
      if (activeTab == true) {
        //var activeAnch = $(this).children().attr("href");
        alert($(this).next('li').children().attr("href"));
        var nextId = $(this).next('li').children().attr("id");
        //$("#"+nextId).click();// trigger click to #menu 1
      }
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Case</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

<body>
  <ul class="nav nav-pills">
    <li class="active">Home</li>
    <li>Menu 1</li>
    <li>Menu 2</li>
    <li>Menu 3</li>
  </ul>

  <div class="tab-content">
    <div id="home" class="tab-pane fade in active">
      <h3>HOME</h3>
      <span>Form 1</span>
    </div>
    <div id="menu1" class="tab-pane fade">
      <h3>Menu 1</h3>
      <span>Form 2</span>
    </div>
    <div id="menu2" class="tab-pane fade">
      <h3>Menu 2</h3>
      <span>Form 3</span>
    </div>
    <div id="menu3" class="tab-pane fade">
      <h3>Menu 3</h3>
      <span>Form 4</span>
    </div>
  </div>

  <button id="nextBtn">Next</button>

</body>

</html></code>```

答:
What you have tot do is just

```<code>$("#nextBtn").click(function() {
    var $nextLi = $('li.active').next('li');
    if ($nextLi.length) $nextLi.find('a:first').click();
});
</code>```

$(function() {
  $("#nextBtn").click(function() {
    var $nextLi = $('li.active').next('li');
    if ($nextLi.length) {
      $nextLi.find('a:first').click();
    } else {
      $('ul.nav a:first').click();
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Case</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

<body>
  <ul class="nav nav-pills">
    <li class="active">Home</li>
    <li>Menu 1</li>
    <li>Menu 2</li>
    <li>Menu 3</li>
  </ul>

  <div class="tab-content">
    <div id="home" class="tab-pane fade in active">
      <h3>HOME</h3>
      <span>Form 1</span>
    </div>
    <div id="menu1" class="tab-pane fade">
      <h3>Menu 1</h3>
      <span>Form 2</span>
    </div>
    <div id="menu2" class="tab-pane fade">
      <h3>Menu 2</h3>
      <span>Form 3</span>
    </div>
    <div id="menu3" class="tab-pane fade">
      <h3>Menu 3</h3>
      <span>Form 4</span>
    </div>
  </div>

  <button id="nextBtn">Next</button>

</body>

</html></code>```

Title: Jquery custom trigger anchor tag

Body:
Hello every one I am creating custom multistep form but when I click on next button it can't trigger related  anchor tag ( auto click )

Please help me to resolve my issue

Thanks in Advance

$(function() {
  $("#nextBtn").click(function() {
    var $tabs = $("li");
    $tabs.each(function() {

      var activeTab = $(this).hasClass("active");
      if (activeTab == true) {
        //var activeAnch = $(this).children().attr("href");
        alert($(this).next('li').children().attr("href"));
        var nextId = $(this).next('li').children().attr("id");
        //$("#"+nextId).click();// trigger click to #menu 1
      }
    });
  });
});

<!DOCTYPE html>

  <title>Bootstrap Case</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Home

Menu 1

Menu 2

Menu 3

HOME

      Form 1

Menu 1

      Form 2

Menu 2

      Form 3

Menu 3

      Form 4

  <button id="nextBtn">Next</button>

Body:
What you have tot do is just

$("#nextBtn").click(function() {
    var $nextLi = $('li.active').next('li');
    if ($nextLi.length) $nextLi.find('a:first').click();
});

$(function() {
  $("#nextBtn").click(function() {
    var $nextLi = $('li.active').next('li');
    if ($nextLi.length) {
      $nextLi.find('a:first').click();
    } else {
      $('ul.nav a:first').click();
    }
  });
});

<!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Case</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

<body>
  <ul class="nav nav-pills">
    <li class="active"><a data-toggle="pill" href="#home">Home</a></li>
    <li><a data-toggle="pill" href="#menu1">Menu 1</a></li>
    <li><a data-toggle="pill" href="#menu2">Menu 2</a></li>
    <li><a data-toggle="pill" href="#menu3">Menu 3</a></li>
  </ul>

  <div class="tab-content">
    <div id="home" class="tab-pane fade in active">
      <h3>HOME</h3>
      <span>Form 1</span>
    </div>
    <div id="menu1" class="tab-pane fade">
      <h3>Menu 1</h3>
      <span>Form 2</span>
    </div>
    <div id="menu2" class="tab-pane fade">
      <h3>Menu 2</h3>
      <span>Form 3</span>
    </div>
    <div id="menu3" class="tab-pane fade">
      <h3>Menu 3</h3>
      <span>Form 4</span>
    </div>
  </div>

  <button id="nextBtn">Next</button>

</body>

</html>


来源: stackexchange

问:
Entity Framework connection to SQL Azure DB using access token
We have web application which connects to SQL Azure DB. I have configured my application with Application ID and certificate. We would like to make use of Access Token Approach for connecting to SQL Server, As per below link, connecting through token approach to SQL Server is not a reliable approach. Any  recommended way of connecting instead of User ID and Password.

Connect to Azure SQL using Azure Active Directory from an Azure Website?

Can anyone let me know if they have implemented SQL Azure DB AAD token based authentication using entity framework and is it right way for connecting.

答:
According to your description, I followed the tutorial about using AAD Authentication for Azure SQL Database.

As this tutorial mentioned about Azure AD token authentication:

This authentication method allows middle-tier services to connect to Azure SQL Database or Azure SQL Data Warehouse by obtaining a token from Azure Active Directory (AAD). It enables sophisticated scenarios including certificate-based authentication.You must complete four basic steps to use Azure AD token authentication:

Register your application with Azure Active Directory and get the client id for your code.

Create a database user representing the application. (Completed earlier in step 6.)

Create a certificate on the client computer runs the application.

Add the certificate as a key for your application.

Then I followed the code sample in this blog for getting started with this feature, and it works as expected.

Can anyone let me know if they have implemented SQL Azure DB AAD token based authentication using entity framework and is it right way for connecting.

Based on the above code sample, I added EntityFramework 6.1.3 for implementing SQL Azure DB AAD token based authentication using entity framework. After some trials, I could make it work as expected. Here are some details, you could refer to them.

DbContext

```<code>public class BruceDbContext : DbContext
{
    public BruceDbContext()
        : base("name=defaultConnectionString")
    { }

    public BruceDbContext(SqlConnection con) : base(con, true)
    {
        Database.SetInitializer<BruceDbContext>(null);
    }

    public virtual DbSet<User> Users { get; set; }
}
</code>```

DataModel

```<code>[Table("Users")]
public class User
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }
    [StringLength(50)]
    public string UserName { get; set; }
    public DateTime CreateTime { get; set; }
}
</code>```

Program.cs

```<code>class Program
{
    static void Main()
    {
        SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
        builder["Data Source"] = "brucesqlserver.database.windows.net";
        builder["Initial Catalog"] = "brucedb";
        builder["Connect Timeout"] = 30;

        string accessToken = TokenFactory.GetAccessToken();
        if (accessToken == null)
        {
            Console.WriteLine("Fail to acuire the token to the database.");
        }
        using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
        {
            try
            {
                connection.AccessToken = accessToken;
                //working with EF
                using (var model = new BruceDbContext(connection))
                {
                   var users= model.Users.ToList();
                    Console.WriteLine($"Results:{Environment.NewLine}{JsonConvert.SerializeObject(users)}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        Console.WriteLine("Please press any key to stop");
        Console.ReadKey();
    }
}
</code>```

Result

Note: The contained database user for your application principal via CREATE USER [mytokentest] FROM EXTERNAL PROVIDER does not has any permissions to access your database. You need to grant privileges for this user, for more details you could refer to this issue.

Additionally, when you construct the DbContextinstance, you need to implement the SqlConnection instance with a valid AccessToken. AFAIK, you need to handle the token refreshing when the token is expired.

ContentLicense: CC BY-SA 3.0

Body:
According to your description, I followed the tutorial about using AAD Authentication for Azure SQL Database.

As this tutorial mentioned about Azure AD token authentication:

This authentication method allows middle-tier services to connect to Azure SQL Database or Azure SQL Data Warehouse by obtaining a token from Azure Active Directory (AAD). It enables sophisticated scenarios including certificate-based authentication.You must complete four basic steps to use Azure AD token authentication:

Register your application with Azure Active Directory and get the client id for your code.

Create a database user representing the application. (Completed earlier in step 6.)

Create a certificate on the client computer runs the application.

Add the certificate as a key for your application.

Then I followed the code sample in this blog for getting started with this feature, and it works as expected.

Can anyone let me know if they have implemented SQL Azure DB AAD token based authentication using entity framework and is it right way for connecting.

Based on the above code sample, I added EntityFramework 6.1.3 for implementing SQL Azure DB AAD token based authentication using entity framework. After some trials, I could make it work as expected. Here are some details, you could refer to them.

DbContext

public class BruceDbContext : DbContext
{
    public BruceDbContext()
        : base("name=defaultConnectionString")
    { }

    public BruceDbContext(SqlConnection con) : base(con, true)
    {
        Database.SetInitializer<BruceDbContext>(null);
    }

    public virtual DbSet<User> Users { get; set; }
}

DataModel

[Table("Users")]
public class User
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }
    [StringLength(50)]
    public string UserName { get; set; }
    public DateTime CreateTime { get; set; }
}

Program.cs

class Program
{
    static void Main()
    {
        SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
        builder["Data Source"] = "brucesqlserver.database.windows.net";
        builder["Initial Catalog"] = "brucedb";
        builder["Connect Timeout"] = 30;

        string accessToken = TokenFactory.GetAccessToken();
        if (accessToken == null)
        {
            Console.WriteLine("Fail to acuire the token to the database.");
        }
        using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
        {
            try
            {
                connection.AccessToken = accessToken;
                //working with EF
                using (var model = new BruceDbContext(connection))
                {
                   var users= model.Users.ToList();
                    Console.WriteLine($"Results:{Environment.NewLine}{JsonConvert.SerializeObject(users)}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        Console.WriteLine("Please press any key to stop");
        Console.ReadKey();
    }
}

Result

Note: The contained database user for your application principal via CREATE USER [mytokentest] FROM EXTERNAL PROVIDER does not has any permissions to access your database. You need to grant privileges for this user, for more details you could refer to this issue.

Additionally, when you construct the DbContextinstance, you need to implement the SqlConnection instance with a valid AccessToken. AFAIK, you need to handle the token refreshing when the token is expired.


问:
Standard Rate in Resource Center - Project Server 2013/Project Online
I have a standard rate set for a resource (ex. 50/hr) and that resource is assigned to several tasks on a project.  My question is this:  If the resource were to have a rate change, would the system be smart enough to track hours worked on tasks at the $50 rate and track hours worked at the new rate separately?

I had a resource working 24hrs at $50 on three tasks.  I then changed the rate to $25 to see what would happen.  It ended up changing the rate on the 24hrs of work on the 3 tasks to $25, but was hoping it would know that the 24hrs of work should have been at $50/hr and then any additional tasks would be calculated using $25.

How can I accomplish this?

Thanks!

答:
You need to do this in Project Professional, in the Resource Information palette, under the Costs Tab. You can get to this by opening the resource in Project Pro from the Resource Centre

Double Click on the Resource in Project Pro and you get the Resource Info dialog and under the Costs tab you can edit the five available rate cards, including effective dates.

If you know a rate change is coming you can set the effective date in the future, and Project will apply it appropriately.


问:
how to retrieve one to many relationship data in mysql
I have two table

table#1

```<code>name_id |  name
--------|-------
  1     | abc
  2     |  def
</code>```

table#2

```<code>subject_id| name_id |subject
----------|---------|--------
1         | 1       |malayalam
2         | 1       | english
3         | 1       | hindi
4         | 2       | malayalam
5         | 2       | hindi
</code>```

i want to join these two tables and get output in the following format

```<code>id |name |subject1  |subject2 |subject3
---|-----|--------- |---------|--------
1  |abc  |malayalam |english  |hindi
2  |def  |malayalam |hindi    |
</code>```

is it possible in mySql?
can anyone help?

答:
So I'm not exactly sure about the scope of your schema here, because you have a subject_id that doesn't correlate to each subject. For example, subject_id 1 = malayalam but malayalm also equals subject_id 3, but subject_id 3 also equals hindi, while again hindi is also assigned to subject_id 4. Very confusing schema to work with.

You mention it's a one to many, but without knowing more context I don't see that being the case. A person can have more than one subject. One subject can belong to more than 1 person. This is a many to many relationship, which means you should be using 3 tables here.

For the sake of your question, you can use an inner join

```<code>SELECT one.name_id as id, name, subject
FROM one
INNER JOIN two
ON id = two.name_id
ORDER BY id;
</code>```

The output of that query would be:

```<code>1 | abc | malayalam
1 | abc | english
1 | abc | hindi
2 | def | malayalam
2 | def | hindi
</code>```

However, I would highly consider re-designing your database. I mean you want your data in that format, which looks nice with only 3 subjects. But what happens when there's 50 subjects for one person? Would you still want all subjects on one line like that? It's better to break it up, it will save you down the road when your database starts becoming more complex. In many cases, to create a many to many relationship you'll want a 3rd table that connects the two entities, in this case I'd create an Enrolled_Classes table to connect Names and Subjects

Names

```<code>name_id | name
--------------
1       | abc
2       | def
</code>```

Subjects

```<code>subject_id | subject
--------------------
1          | malayalm
2          | english
3          | hindi
</code>```

Enrolled_Classes

```<code>name_id | subject_id
--------------------
1       | 1
1       | 2
1       | 3
2       | 1
2       | 3
</code>```

Then you'd need another join for your query:

```<code>SELECT name, subject
FROM Names
INNER JOIN Enrolled_Classes
ON Names.name_id = Enrolled_Classes.name_id
INNER JOIN Subjects
ON Enrolled_Classes.subject_id = Subjects.subject_id;
</code>```

Same Output

```<code>abc | malayalam
abc | english
abc | hindi
def | malayalam
def | hindi
</code>```

Body:
I have two table

table#1

name_id |  name
--------|-------
  1     | abc
  2     |  def

table#2

subject_id| name_id |subject
----------|---------|--------
1         | 1       |malayalam
2         | 1       | english
3         | 1       | hindi
4         | 2       | malayalam
5         | 2       | hindi

i want to join these two tables and get output in the following format

id |name |subject1  |subject2 |subject3
---|-----|--------- |---------|--------
1  |abc  |malayalam |english  |hindi
2  |def  |malayalam |hindi    |

is it possible in mySql?
can anyone help?

Body:
So I'm not exactly sure about the scope of your schema here, because you have a subject_id that doesn't correlate to each subject. For example, subject_id 1 = malayalam but malayalm also equals subject_id 3, but subject_id 3 also equals hindi, while again hindi is also assigned to subject_id 4. Very confusing schema to work with.

You mention it's a one to many, but without knowing more context I don't see that being the case. A person can have more than one subject. One subject can belong to more than 1 person. This is a many to many relationship, which means you should be using 3 tables here.

For the sake of your question, you can use an inner join

SELECT one.name_id as id, name, subject
FROM one
INNER JOIN two
ON id = two.name_id
ORDER BY id;

The output of that query would be:

1 | abc | malayalam
1 | abc | english
1 | abc | hindi
2 | def | malayalam
2 | def | hindi

However, I would highly consider re-designing your database. I mean you want your data in that format, which looks nice with only 3 subjects. But what happens when there's 50 subjects for one person? Would you still want all subjects on one line like that? It's better to break it up, it will save you down the road when your database starts becoming more complex. In many cases, to create a many to many relationship you'll want a 3rd table that connects the two entities, in this case I'd create an Enrolled_Classes table to connect Names and Subjects

Names

name_id | name
--------------
1       | abc
2       | def

Subjects

subject_id | subject
--------------------
1          | malayalm
2          | english
3          | hindi

Enrolled_Classes

name_id | subject_id
--------------------
1       | 1
1       | 2
1       | 3
2       | 1
2       | 3

Then you'd need another join for your query:

SELECT name, subject
FROM Names
INNER JOIN Enrolled_Classes
ON Names.name_id = Enrolled_Classes.name_id
INNER JOIN Subjects
ON Enrolled_Classes.subject_id = Subjects.subject_id;

Same Output

abc | malayalam
abc | english
abc | hindi
def | malayalam
def | hindi


问:
Total read time in Dataflow job has high variance
I have a Dataflow job that reads log files from my GCS bucket that are split by time and host machine. The structure of the bucket is as follows:

/YYYY/MM/DD/HH/mm/HOST/*.gz

Each job can end up consuming on the order of 10,000+ log files of around 10-100 KB in size.

Normally our job takes approximately 5 minutes to complete. We at times see our jobs spike to 2-3x that amount of time, and find that the majority of the increase is seen in the work items related to reading the data files. How can we reduce this variance on our job execution time? Is there a throughput issue with reading from GCS?

答:
I have a different insight on this. Reading a gzip file implies it is being unzipped first on the worker machine. The unzip on the gzip file is a single core (ideally 1 n1-standard-1 worker) operation because gzip as a compression format is not splittable.

In the above scenario, there might be some files which are significantly larger compared to other files and will most likely result into creating stragglers (workers in the dataflow job that lag behind) which will increase the job execution time.

I can think of two solutions to keep the job execution time as minimum as possible -

Change to a splittable compression format like bzip2 so that all the files are massively parallelised and the read operation is completed as fast as possible.

Make the gzip files as minimum in size as possible so that a large number of workers consume a huge number of files and total execution time is less. For example, having 10 workers read 10 gzip files of 100KB each, have 100 workers read zip files of 10KB each. GCP bills you per minute, so cost should most probably remain the same.


问:
Color points with the color as a column in ggplot2
I have a dataframe where a color is given for each point in a column:

```<code>d<-data.frame(x=1:10,y=1:10,col=c(rep("red",n=5),rep("green",n=5)))
d$col<-as.character(d$col)
ggplot(data=d,aes(x=x,y=y,colour=col))+geom_point()
</code>```

As you can see, the colour is not interpreted as a colour, but a group,

can ggplot handle such cases?

答:
This question has probably been asked and answered before. However, there is another issue in setting up the data.

The OP is creating the data by

```<code>d <- data.frame(x = 1:10,
                y = 1:10,
                col = c(rep("red", n = 5), rep("green", n = 5)))
</code>```

This results in an alternation of the two colours

```<code>d
#    x  y   col
#1   1  1   red
#2   2  2 green
#3   3  3   red
#4   4  4 green
#5   5  5   red
#6   6  6 green
#7   7  7   red
#8   8  8 green
#9   9  9   red
#10 10 10 green
</code>```

Reason is that n is not a defined parameter to the rep() function. According to ?rep, valid parameters are times, lenght.out, and each.

Probably, the OP has meant

```<code>d <- data.frame(x = 1:10,
                y = 1:10,
                col = c(rep("red", 5), rep("green", 5)))
</code>```

which results in successive rows being coloured in the same colour:

```<code>d
#    x  y   col
#1   1  1   red
#2   2  2   red
#3   3  3   red
#4   4  4   red
#5   5  5   red
#6   6  6 green
#7   7  7 green
#8   8  8 green
#9   9  9 green
#10 10 10 green
</code>```

By the way,

```<code>col = c(rep("red", 5), rep("green", 5))
</code>```

can be written more clearly as

```<code>col = rep(c("red", "green"), each = 5)
</code>```

With this, the following plot statements

```<code>library(ggplot2)
# variant 1 (OP's own answer)
ggplot(data = d, aes(x = x, y = y)) + geom_point(colour = d$col)
# variant 2 (aosmith' comment, more "ggplot2-like")
ggplot(data = d, aes(x = x, y = y, colour = col)) + geom_point() +
  scale_colour_identity()
</code>```

produce the same chart:

Body:
I have a dataframe where a color is given for each point in a column:

d<-data.frame(x=1:10,y=1:10,col=c(rep("red",n=5),rep("green",n=5)))
d$col<-as.character(d$col)
ggplot(data=d,aes(x=x,y=y,colour=col))+geom_point()

As you can see, the colour is not interpreted as a colour, but a group,

can ggplot handle such cases?

Body:
This question has probably been asked and answered before. However, there is another issue in setting up the data.

The OP is creating the data by

d <- data.frame(x = 1:10,
                y = 1:10,
                col = c(rep("red", n = 5), rep("green", n = 5)))

This results in an alternation of the two colours

d
#    x  y   col
#1   1  1   red
#2   2  2 green
#3   3  3   red
#4   4  4 green
#5   5  5   red
#6   6  6 green
#7   7  7   red
#8   8  8 green
#9   9  9   red
#10 10 10 green

Reason is that n is not a defined parameter to the rep() function. According to ?rep, valid parameters are times, lenght.out, and each.

Probably, the OP has meant

d <- data.frame(x = 1:10,
                y = 1:10,
                col = c(rep("red", 5), rep("green", 5)))

which results in successive rows being coloured in the same colour:

d
#    x  y   col
#1   1  1   red
#2   2  2   red
#3   3  3   red
#4   4  4   red
#5   5  5   red
#6   6  6 green
#7   7  7 green
#8   8  8 green
#9   9  9 green
#10 10 10 green

By the way,

col = c(rep("red", 5), rep("green", 5))

can be written more clearly as

col = rep(c("red", "green"), each = 5)

With this, the following plot statements

library(ggplot2)
# variant 1 (OP's own answer)
ggplot(data = d, aes(x = x, y = y)) + geom_point(colour = d$col)
# variant 2 (aosmith' comment, more "ggplot2-like")
ggplot(data = d, aes(x = x, y = y, colour = col)) + geom_point() +
  scale_colour_identity()

produce the same chart:


问:
How to increment numeric part of a string by one?
I have a string formed up by numbers and sometimes by letters.

Example AF-1234 or 345ww.

I have to get the numeric part and increment it by one.

how can I do that? maybe with regex?

答:
Here's some Python code that does what you ask. Not too great on my PHP, but I'll see if I can convert it for you.</p>

```<code>>>> import re
>>> match = re.match(r'(\D*)(\d+)(\D*)', 'AF-1234')
>>> match.group(1) + str(int(match.group(2))+1) + match.group(3)
'AF-1235'
</code>```

Body:
Here's some Python code that does what you ask. Not too great on my PHP, but I'll see if I can convert it for you.

>>> import re
>>> match = re.match(r'(\D*)(\d+)(\D*)', 'AF-1234')
>>> match.group(1) + str(int(match.group(2))+1) + match.group(3)
'AF-1235'

ContentLicense: CC BY-SA 2.5


问:
CSS/HTML: What is producing this sub-menu arrow?
Can you see what is causing this up arrow @ this page.

I have right-clicked on it > inspect element, and I am shown:

```<code>.genesis-nav-menu .sub-menu .sub-menu
</code>```

but I see no CSS rules to generate the up arrow there.

答:
The following css code is creating this issue:
.genesis-nav-menu li:last-of-type .sub-menu li:first-child a::after
{left: 90%; }

when this code is removed there is no arrow that is showing right now.

Body:
Can you see what is causing this up arrow @ this page.

I have right-clicked on it > inspect element, and I am shown:

.genesis-nav-menu .sub-menu .sub-menu

but I see no CSS rules to generate the up arrow there.


问:
SSMS 2016 - Mobile reports - creating custom control
Is it possible to create Custom (own) controls for the SQL Server Mobile Report publisher? Meaning own graphes (Gauges), styles, maps, etc...

I was unable to find any information about this topic on Google (or other sites like SO). Few days back we had lectures/training with some developer (basics of Reporting) and he shortly said that it is possible, but we haven't got time to go through it.

My expectations (as an answer) is explanation what tool can be used and/or link to tutorial.

Possibly also some information (with source) that this cannot be created in version 2016.

答:
Short story: It is not possible to create custom control in Mobile Reports Publisher as of now (March 2017). There is no support in the software itself. However Microsoft will allow store/use Power BI reports within Reporting services.

Long story: I've reached out the tutorial guru and discussed this further. We've found that the original statement is not true and mobile reports cannot be adjusted in a way of creating new control or modifying style sheet.

But: Since Mobile reports are sort of family with product called Power BI, Microsoft has decided (as described in MS Technical preview - January 2017) to support Power BI Reports on next version MS Reporting Services. And as there can be done some visualisation changes and even create new controls, most likely we will be also able to create our own control.


问:
Convert string to int[,]
I have weird requirement in matrix clustering.

My inputs are like

```<code>string param = "1100,1110,0110,0001";
</code>```

and what I want is

```<code> var matrix = new[,]
        {
              {1,1,0,0},
              {1,1,1,0},
              {0,1,1,0},
              {0,0,0,1}
        };
</code>```

so It should be array of int[4,4].

What I tried?

I tried many ways for this conversation.

First Of all I convert my string to string[], using below code.

```<code>string[] resultantArray = param.Split(',').ToArray();
</code>```

And then I tried to convert my string[] to int[], using below code.

```<code>var intArray = resultantArray .Select(int.Parse).ToArray();
</code>```

but I ended up with removed leading zeros.

Is there any way,
 I can achieve int[4,4] array from string?

答:
```<code>            string param = "1100,1110,0110,0001";
            string[] resultantArray = param.Split(',').ToArray();

            int n = resultantArray.Count();
            int m = resultantArray[0].Length;
            var matrix = new int[n,m];

            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < m; j++)
                {
                    matrix[i, j] = Convert.ToInt32(resultantArray[i][j].ToString());
                }
            }
</code>```

Title: Convert string to int[,]

Body:
I have weird requirement in matrix clustering.

My inputs are like

string param = "1100,1110,0110,0001";

and what I want is

 var matrix = new[,]
        {
              {1,1,0,0},
              {1,1,1,0},
              {0,1,1,0},
              {0,0,0,1}
        };

so It should be array of int[4,4].

What I tried?

I tried many ways for this conversation.

First Of all I convert my string to string[], using below code.

string[] resultantArray = param.Split(',').ToArray();

And then I tried to convert my string[] to int[], using below code.

var intArray = resultantArray .Select(int.Parse).ToArray();

but I ended up with removed leading zeros.

Is there any way,
 I can achieve int[4,4] array from string?


问:
Volatile and atomic operation in java
I have read article concerning atomic operation in Java but still have some doubts needing to be clarified:

```<code>int volatile num;
public void doSomething() {
  num = 10;  // write operation
  System.out.println(num)   // read
  num = 20;  // write
  System.out.println(num);  // read
}
</code>```

So i have done w-r-w-r 4 operations on 1 method, are they atomic operations? What will happen if multiple threads invoke doSomething() method simultaneously ?

答:
Atomic Operations and Synchronization:

Atomic executions are performed in a single unit of task without getting affected from other executions. Atomic operations are required in multi-threaded environment to avoid data irregularity.

If we are reading/writing an int value then it is an atomic operation. But generally if it is inside a method then if the method is not synchronized many threads can access it which can lead to inconsistent values. However, int++ is not an atomic operation. So by the time one threads read it’s value and increment it by one, other thread has read the older value leading to wrong result.

To solve data inconsistency, we will have to make sure that increment operation on count is atomic, we can do that using Synchronization but Java 5 java.util.concurrent.atomic provides wrapper classes for int and long that can be used to achieve this atomically without usage of Synchronization.

Using int might create data data inconsistencies as shown below:

```<code>public class AtomicClass {

    public static void main(String[] args) throws InterruptedException {

        ThreardProcesing pt = new ThreardProcesing();
        Thread thread_1 = new Thread(pt, "thread_1");
        thread_1.start();
        Thread thread_2 = new Thread(pt, "thread_2");
        thread_2.start();
        thread_1.join();
        thread_2.join();
        System.out.println("Processing count=" + pt.getCount());
    }

}

class ThreardProcesing implements Runnable {
    private int count;

    @Override
    public void run() {
        for (int i = 1; i < 5; i++) {
            processSomething(i);
            count++;
        }
    }

    public int getCount() {
        return this.count;
    }

    private void processSomething(int i) {
        // processing some job
        try {
            Thread.sleep(i * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
</code>```

OUTPUT: count value varies between 5,6,7,8

We can resolve this using java.util.concurrent.atomic that will always output count value as 8 because AtomicInteger method incrementAndGet() atomically increments the current value by one. shown below:

```<code>public class AtomicClass {

    public static void main(String[] args) throws InterruptedException {

        ThreardProcesing pt = new ThreardProcesing();
        Thread thread_1 = new Thread(pt, "thread_1");
        thread_1.start();
        Thread thread_2 = new Thread(pt, "thread_2");
        thread_2.start();
        thread_1.join();
        thread_2.join();
        System.out.println("Processing count=" + pt.getCount());
    }
}

class ThreardProcesing implements Runnable {
    private AtomicInteger count = new AtomicInteger();

    @Override
    public void run() {
        for (int i = 1; i < 5; i++) {
            processSomething(i);
            count.incrementAndGet();
        }
    }

    public int getCount() {
        return this.count.get();
    }

    private void processSomething(int i) {
        // processing some job
        try {
            Thread.sleep(i * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
</code>```

Source: Atomic Operations in java

Title: Volatile and atomic operation in java

Body:
I have read article concerning atomic operation in Java but still have some doubts needing to be clarified:

int volatile num;
public void doSomething() {
  num = 10;  // write operation
  System.out.println(num)   // read
  num = 20;  // write
  System.out.println(num);  // read
}

So i have done w-r-w-r 4 operations on 1 method, are they atomic operations? What will happen if multiple threads invoke doSomething() method simultaneously ?

Body:
Atomic Operations and Synchronization:

Atomic executions are performed in a single unit of task without getting affected from other executions. Atomic operations are required in multi-threaded environment to avoid data irregularity.

If we are reading/writing an int value then it is an atomic operation. But generally if it is inside a method then if the method is not synchronized many threads can access it which can lead to inconsistent values. However, int++ is not an atomic operation. So by the time one threads read it’s value and increment it by one, other thread has read the older value leading to wrong result.

To solve data inconsistency, we will have to make sure that increment operation on count is atomic, we can do that using Synchronization but Java 5 java.util.concurrent.atomic provides wrapper classes for int and long that can be used to achieve this atomically without usage of Synchronization.

Using int might create data data inconsistencies as shown below:

public class AtomicClass {

    public static void main(String[] args) throws InterruptedException {

        ThreardProcesing pt = new ThreardProcesing();
        Thread thread_1 = new Thread(pt, "thread_1");
        thread_1.start();
        Thread thread_2 = new Thread(pt, "thread_2");
        thread_2.start();
        thread_1.join();
        thread_2.join();
        System.out.println("Processing count=" + pt.getCount());
    }

}

class ThreardProcesing implements Runnable {
    private int count;

    @Override
    public void run() {
        for (int i = 1; i < 5; i++) {
            processSomething(i);
            count++;
        }
    }

    public int getCount() {
        return this.count;
    }

    private void processSomething(int i) {
        // processing some job
        try {
            Thread.sleep(i * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

OUTPUT: count value varies between 5,6,7,8

We can resolve this using java.util.concurrent.atomic that will always output count value as 8 because AtomicInteger method incrementAndGet() atomically increments the current value by one. shown below:

public class AtomicClass {

    public static void main(String[] args) throws InterruptedException {

        ThreardProcesing pt = new ThreardProcesing();
        Thread thread_1 = new Thread(pt, "thread_1");
        thread_1.start();
        Thread thread_2 = new Thread(pt, "thread_2");
        thread_2.start();
        thread_1.join();
        thread_2.join();
        System.out.println("Processing count=" + pt.getCount());
    }
}

class ThreardProcesing implements Runnable {
    private AtomicInteger count = new AtomicInteger();

    @Override
    public void run() {
        for (int i = 1; i < 5; i++) {
            processSomething(i);
            count.incrementAndGet();
        }
    }

    public int getCount() {
        return this.count.get();
    }

    private void processSomething(int i) {
        // processing some job
        try {
            Thread.sleep(i * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

Source: Atomic Operations in java


问:
Display percentage on tooltip highchart Angular 2
Hi I have the following highchart configuration for a normal column chart with percentage values.

```<code>private _attendanceInputData: any = {

        chart: { type: 'column' },
        title : { text : 'Daily Attendance Overview' },

        xAxis: {
            categories: this._weekValues
        },
        yAxis: {
            allowDecimals: false,
            title: { text: ''},
            min: 0,
            max: 100,
            labels: {
                formatter:function() {
                    console.log(this.value); //0, 25, 50 , 75 , 100
                    var pcnt = (this.value / 100) * 100;
                    return pcnt + '%';
                }
            }
        },
        credits: {
          enabled: false
        },
        series: [
            {
                name: 'Students',
                data: this._studentAttendance,
                color: '#3366cc'
            },{
                name: 'Staff',
                data: this._staffAttendance,
                color: '#accbfc',
            }
        ]
    };
</code>```

But the tooltip now showing the value but not displaying "%" after the value. How to do that? Sorry am new to highcharts. Thanks in advance guys.

答:
You need to tell Highcharts the format of the Tooltip. To do this, there is the tooltip section in the highcharts object. To render a '%' after each Value you can use the following snippet:

```<code>[...]
credits: {
  enabled: false
},
tooltip: {
  valueSuffix: '%'
},
series: [{
[...]
</code>```

See http://api.highcharts.com/highcharts/tooltip for reference

Body:
Hi I have the following highchart configuration for a normal column chart with percentage values.

private _attendanceInputData: any = {

        chart: { type: 'column' },
        title : { text : 'Daily Attendance Overview' },

        xAxis: {
            categories: this._weekValues
        },
        yAxis: {
            allowDecimals: false,
            title: { text: ''},
            min: 0,
            max: 100,
            labels: {
                formatter:function() {
                    console.log(this.value); //0, 25, 50 , 75 , 100
                    var pcnt = (this.value / 100) * 100;
                    return pcnt + '%';
                }
            }
        },
        credits: {
          enabled: false
        },
        series: [
            {
                name: 'Students',
                data: this._studentAttendance,
                color: '#3366cc'
            },{
                name: 'Staff',
                data: this._staffAttendance,
                color: '#accbfc',
            }
        ]
    };

But the tooltip now showing the value but not displaying "%" after the value. How to do that? Sorry am new to highcharts. Thanks in advance guys.

Body:
You need to tell Highcharts the format of the Tooltip. To do this, there is the tooltip section in the highcharts object. To render a '%' after each Value you can use the following snippet:

[...]
credits: {
  enabled: false
},
tooltip: {
  valueSuffix: '%'
},
series: [{
[...]

See http://api.highcharts.com/highcharts/tooltip for reference


问:
Allow fullscreen landscape only for system AVPlayerViewController
I have an app which uses a UISplitViewController to load a webpage in the Detail View Controller, which has a WKWebView property. Some of the URLs are links to embedded YouTube videos, and some are direct links to .mp4 files. Either way, the video files are loaded automatically (after tapping for the YouTube videos) into a fullscreen system player, which I assume is an AVPlayerViewController. I've seen several posts about subclassing AVPlayerViewController to allow the rotation by implementing supportedInterfaceOrientations, and other posts which recommended either checking the class of the UIWindow's rootViewController presentedViewController in application: supportedInterfaceOrientationsForWindow: or checking a variable on the AppDelegate that was set when the AVPlayerViewController was presented, but none of these solutions have worked for me because I'm not creating or presenting my own instance of AVPlayerViewController, so I'm not sure how to allow the rotation to landscape when these videos are playing.

Is there a way I can tell when the system is playing a video in full screen mode, so I can allow the rotation?

Here are links to some of the posts I've seen already:

MPMoviePlayerViewController | Allow landscape mode

Only ONE VIEW landscape mode

答:
I hope u are still need an answer. I have found solution in Swift, but it is simply convertible in Objective C. I found out, that when using WKWebView (maybe UIWebView, too) full screen video is presented in new UIWindow (at least on iOS 10). That window has blank UIViewController and presented AVFullScreenViewController over it.

So, in ur AppDelegate u should implement application:supportedInterfaceOrientationsForWindow: like this

```<code>func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    if window != self.window, let pvc = window?.rootViewController?.presentedViewController, "\(type(of: pvc))" == "AVFullScreenViewController" {
        return pvc.isBeingDismissed ? .portrait : .all
    }
    return .portrait
}
</code>```

While AVFullScreenViewController is private API class, u could protect urself and replace "AVFullScreenViewController" with String(format: "AV%@ViewController", "FullScreen")

Good luck!

Body:
I hope u are still need an answer. I have found solution in Swift, but it is simply convertible in Objective C. I found out, that when using WKWebView (maybe UIWebView, too) full screen video is presented in new UIWindow (at least on iOS 10). That window has blank UIViewController and presented AVFullScreenViewController over it.

So, in ur AppDelegate u should implement application:supportedInterfaceOrientationsForWindow: like this

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    if window != self.window, let pvc = window?.rootViewController?.presentedViewController, "\(type(of: pvc))" == "AVFullScreenViewController" {
        return pvc.isBeingDismissed ? .portrait : .all
    }
    return .portrait
}

While AVFullScreenViewController is private API class, u could protect urself and replace "AVFullScreenViewController" with String(format: "AV%@ViewController", "FullScreen")

Good luck!


问:
Most efficient way to group, count, then sort?
The data is two columns, City, I need to group by city based on sum.

Table looks something like this (times a million):

```<code>City, People
Boston, 1000
Boston, 2000
New York, 2500
Chicago, 2000
</code>```

In this case Boston would be number 1 with 3000 people. I would need to return the top 5% cities and their people count (sum).

What is the most efficient way to do this? Can pandas scale this up well? Should I keep track of the top 5% or do a sort at the end?

答:
groupby to get sums

rank to get perctiles

```<code>df = pd.read_csv(skipinitialspace=True)
d1 = df.groupby('City').People.sum()
d1.loc[d1.rank(pct=True) >= .95]

City
Boston    3000
Name: People, dtype: int64
</code>```

Body:
The data is two columns, City, I need to group by city based on sum.

Table looks something like this (times a million):

City, People
Boston, 1000
Boston, 2000
New York, 2500
Chicago, 2000

In this case Boston would be number 1 with 3000 people. I would need to return the top 5% cities and their people count (sum).

What is the most efficient way to do this? Can pandas scale this up well? Should I keep track of the top 5% or do a sort at the end?

Body:
groupby to get sums

rank to get perctiles

df = pd.read_csv(skipinitialspace=True)
d1 = df.groupby('City').People.sum()
d1.loc[d1.rank(pct=True) >= .95]

City
Boston    3000
Name: People, dtype: int64


问:
Audio file not play in objective C
```<code>- (void)play {
    NSURL *imgPath = [[NSBundle mainBundle] URLForResource:@"sound" withExtension:@"mp3"];
    NSString *path = [imgPath path];
    NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];
    NSLog(@"%@",data);
    NSError *error;
    self.avPlayer = [[AVAudioPlayer alloc] initWithData:data error:&error];
    [self.avPlayer play];
    }
</code>```

答:
Rather then converting into NSData, you can pass URL to AVAudioPlayer.</p>

```<code>    NSURL *imgPath = [[NSBundle mainBundle] URLForResource:@"sound" withExtension:@"mp3"];

    NSError *error;

    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:imgPath
                                                         error:&error];
    self.player.numberOfLoops = 0; //Infinite
    self.player.delegate  = self;
    [self.player prepareToPlay];
    [self.player play];
</code>```

Title: Audio file not play in objective C

Body:
Rather then converting into NSData, you can pass URL to AVAudioPlayer.

    NSURL *imgPath = [[NSBundle mainBundle] URLForResource:@"sound" withExtension:@"mp3"];

    NSError *error;

    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:imgPath
                                                         error:&error];
    self.player.numberOfLoops = 0; //Infinite
    self.player.delegate  = self;
    [self.player prepareToPlay];
    [self.player play];


问:
How can I make GIT to default to my home folder?
I've just installed GIT on my work machine (Windows 7) connected to the domain at work. When I start the GIT bash it starts on "H:" instead of in my home folder. I think this could be a problem when I'm not connected to the domain since the .ssh folder is located on "H:" instead of my home folder. I have set HOME environment folder to point to c:\Users\MyName, but that doesn't help. My HOMEDRIVE environment variable points to "H:" and the HOMEPATH to "\", but I can't change those.

First question: Will there be an issue when I'm not connected to the domain and the .ssh folder is on a domain drive?
Second question: How do I fix it? :)

答:
Just have bash cd to your home directory when you start it with like cd /home/dan in .bashrc.

I did this in cygwin once as it put my home directory in /bin/%SOMETHING%.


问:
C# Parse XML with repeated pattern of nodes
Hi I have the following xml file:

```<code><?xml version="1.0" encoding="utf-8"?>
<Resources>
    <Category Cause="ONE">
        <Resource Component="AAA" Name="cBackgroundTextA" />
        <Resource Component="BBB" Name="cBackgroundTextB" />
        <Resource Component="CCC" Name="cBackgroundTextC" />
    </Category>
    <Category Cause="TWO">
        <Resource Component="DDD" Name="cBackgroundTextD" />
        <Resource Component="EEE" Name="cBackgroundTextE" />
        <Resource Component="FFF" Name="cBackgroundTextF" />
    </Category>
    <Category Cause="THREE">
        <Resource Component="GGG" Name="cBackgroundTextG" />
        <Resource Component="HHH" Name="cBackgroundTextH" />
        <Resource Component="III" Name="cBackgroundTextI" />
    </Category>
</Resources>
</code>```

How can i get the following:

ONE , AAA , cBackgroundTextA

ONE , BBB , cBackgroundTextB

ONE , CCC , cBackgroundTextC

TWO , DDD , cBackgroundTextD

TWO , EEE , cBackgroundTextE

...

答:
All required information can be gathered using single LINQ query :</p>

```<code>var query = from cat in XmlDocument.Descendants("Category");
            from res in cat.Elements()
            select new ResultDetail
                    {
                        Cause = cat.Attribute("Cause").Value,
                        Component = res.Attribute("Component").Value,
                        Name = res.Attribute("Name").Value
                    };
</code>```

Body:
Hi I have the following xml file:

<?xml version="1.0" encoding="utf-8"?>
<Resources>
    <Category Cause="ONE">
        <Resource Component="AAA" Name="cBackgroundTextA" />
        <Resource Component="BBB" Name="cBackgroundTextB" />
        <Resource Component="CCC" Name="cBackgroundTextC" />
    </Category>
    <Category Cause="TWO">
        <Resource Component="DDD" Name="cBackgroundTextD" />
        <Resource Component="EEE" Name="cBackgroundTextE" />
        <Resource Component="FFF" Name="cBackgroundTextF" />
    </Category>
    <Category Cause="THREE">
        <Resource Component="GGG" Name="cBackgroundTextG" />
        <Resource Component="HHH" Name="cBackgroundTextH" />
        <Resource Component="III" Name="cBackgroundTextI" />
    </Category>
</Resources>

How can i get the following:

ONE , AAA , cBackgroundTextA

ONE , BBB , cBackgroundTextB

ONE , CCC , cBackgroundTextC

TWO , DDD , cBackgroundTextD

TWO , EEE , cBackgroundTextE

...

Body:
All required information can be gathered using single LINQ query :

var query = from cat in XmlDocument.Descendants("Category");
            from res in cat.Elements()
            select new ResultDetail
                    {
                        Cause = cat.Attribute("Cause").Value,
                        Component = res.Attribute("Component").Value,
                        Name = res.Attribute("Name").Value
                    };


问:
Efficiently convert field value to integer from mongo find() using python
Given mongo document like below, how to efficiently find all documents and return student_id field as integer?

```<code> {
     "_id" : ObjectId("58dd757910d81946b8ff853a"),
     "student_id": "4169506398",
     "first_name": "steven",
     "last_name": "smith",
     "date_of_birth": "02-07-1988"
}
{
     "_id" : ObjectId("58dd757910d81946b8ff853b"),
     "student_id": "6902",
     "first_name": "michael",
     "last_name": "clarke",
     "date_of_birth": "05-30-1988"
}
</code>```

Expected result (in Json):

```<code>{
     "student_id": 4169506398
}
{
     "student_id": 6902
}
</code>```

I've 29000 records. Getting documents using db.find({}) and casting student_id to integer when looping might have performance issue.

答:
You can't do this without client side processing or map reduce.

```<code>mylist = map(int, db.collection.distinct('student_id'))
</code>```

which yields a list of student_id of type int in PY2 or iterator object in PY3

You can also use the .aggregate() method as shown here if "student_id" is not unique within the collection and you don't want to de-duplicate the result.

Body:
Given mongo document like below, how to efficiently find all documents and return student_id field as integer?

 {
     "_id" : ObjectId("58dd757910d81946b8ff853a"),
     "student_id": "4169506398",
     "first_name": "steven",
     "last_name": "smith",
     "date_of_birth": "02-07-1988"
}
{
     "_id" : ObjectId("58dd757910d81946b8ff853b"),
     "student_id": "6902",
     "first_name": "michael",
     "last_name": "clarke",
     "date_of_birth": "05-30-1988"
}

Expected result (in Json):

{
     "student_id": 4169506398
}
{
     "student_id": 6902
}

I've 29000 records. Getting documents using db.find({}) and casting student_id to integer when looping might have performance issue.

Body:
You can't do this without client side processing or map reduce.

mylist = map(int, db.collection.distinct('student_id'))

which yields a list of student_id of type int in PY2 or iterator object in PY3

You can also use the .aggregate() method as shown here if "student_id" is not unique within the collection and you don't want to de-duplicate the result.


问:
Create VHD locally and restore in Azure Cloud Powershell
I downloaded and ran sysinternals tools Disk2vhd  https://technet.microsoft.com/en-us/sysinternals/ee656415

I Created a .vhd of my C: drive and I want to push it to the Azure Cloud

The confusing thing is that I start reading about using PowerShell and Prepping the virtual machine

```<code>Install-Module AzureRM.Compute -RequiredVersion 2.6.0
</code>```

Well that is fine, but that I need about Sysprep and I'm confused about where to even run this?    Am I supposed to first create an empty IaaS VM image in the cloud and then RDP into it and do Sysprep on that new VM in Azure?

https://learn.microsoft.com/en-us/azure/virtual-machines/windows/upload-generalized-managed

When I read this I start to realize that I'm not suppose to do this on my local machine.

When Sysprep completes, it shuts down the virtual machine. Do not restart the VM.

Any good resources ?

答:
Firstly, you need use Hyper-V to create a VM by with your VHD. More information about using a VHD with Microsoft Hyper-V(Locally) please refer to this link.

Secondly, you could RDP to your VM and execute Sysprep and stop the VM.

Thirdly, you could upload the new VHD to Azure storage account.

Body:
I downloaded and ran sysinternals tools Disk2vhd  https://technet.microsoft.com/en-us/sysinternals/ee656415

I Created a .vhd of my C: drive and I want to push it to the Azure Cloud

The confusing thing is that I start reading about using PowerShell and Prepping the virtual machine

Install-Module AzureRM.Compute -RequiredVersion 2.6.0

Well that is fine, but that I need about Sysprep and I'm confused about where to even run this?    Am I supposed to first create an empty IaaS VM image in the cloud and then RDP into it and do Sysprep on that new VM in Azure?

https://learn.microsoft.com/en-us/azure/virtual-machines/windows/upload-generalized-managed

When I read this I start to realize that I'm not suppose to do this on my local machine.

When Sysprep completes, it shuts down the virtual machine. Do not restart the VM.

Any good resources ?


问:
Spring context files organization and best practices
We have started using Spring framework in my project. After becoming acquainted with the basic features (IoC) we have started using spring aop and spring security as well.

The problem is that we now have more than 8 different context files and I feel we didn't give enough thought for the organization of those files and their roles. New files were introduced as the project evolved.
We have different context files for: metadata, aop, authorization, services, web resources (it's a RESTful application). So when a developer wants to add a new bean it's not always clear in which file he should add it. We need methodology.

The question:

Is there a best practice for spring files organization?

Should the context files encapsulate layers (DAL , Business Logic, Web) or use cases ? or Flows?

答:
I find that I break them out by layer.

When I write unit tests for each layer I override the production context with values pertinent for the tests.

OwnerDisplayName: LiorH


问:
How to get desired height of ListBox so it doesn't have scrollbar and its content fits there
I have a ListBox inside a DockPanel. I want to find out what should be the size of the ListBox so it doesn't have the scroll bar. I use ListBox.DesiredSize but actually DesiredSize is equal to ListBox.ActualWidth / Height and the ListBox has scrollbar because there are more items that can fit its height.
How to get real desired size ?

答:
If you want to get rid of scrollbar in Listbox instead of creating static height in wpf application, you can disable scrollbar property.

In XAML:

```<code><ListBox ScrollViewer.HorizontalScrollBarVisibility="Disabled" />
<ListBox ScrollViewer.VerticalScrollBarVisibility="Disabled" />
</code>```

In C#:

```<code>myListBox.SetValue(ScrollViewer.HorizontalScrollBarVisibilityProperty, ScrollBarVisibility.Disabled);
myListBox.SetValue(ScrollViewer.VerticalScrollBarVisibilityProperty, ScrollBarVisibility.Disabled);
</code>```

You can disable the scrollbar

Or else

```<code>VerticalScrollBarVisibility="Auto"
</code>```

and set any height for Listbox scroll bar will be visible only content reaches its max Listbox height.

Or

Try this to achieve the desired height by binding the ListBox height property to the ActualHeight of the LayoutRoot Grid via the XAML below:

```<code><Grid x:Name="LayoutRoot" Background="LightGray">
<Grid.ColumnDefinitions>
    <ColumnDefinition Width=".24*"/>
    <ColumnDefinition Width=".73*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
    <RowDefinition Height=".9*"/>
    <RowDefinition Height=".1*"/>
</Grid.RowDefinitions>
<ListBox Name="Subdivisions" SelectedItem="{Binding SelectedSubdivisionViewModel}" ItemsSource="{Binding Path=Subdivisions}" Grid.IsSharedSizeScope="True" Height="{Binding ElementName=LayoutRoot, Path=ActualHeight}" >
</code>```

The important bit being:

```<code> Height="{Binding ElementName=LayoutRoot, Path=ActualHeight}"
</code>```

Also achievable via ancestor type:

```<code> Height="{Binding Path=ActualHeight, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}}}"
</code>```

Its my working code you can change it from grid to Dockpanel.

Body:
If you want to get rid of scrollbar in Listbox instead of creating static height in wpf application, you can disable scrollbar property.

In XAML:

<ListBox ScrollViewer.HorizontalScrollBarVisibility="Disabled" />
<ListBox ScrollViewer.VerticalScrollBarVisibility="Disabled" />

In C#:

myListBox.SetValue(ScrollViewer.HorizontalScrollBarVisibilityProperty, ScrollBarVisibility.Disabled);
myListBox.SetValue(ScrollViewer.VerticalScrollBarVisibilityProperty, ScrollBarVisibility.Disabled);

You can disable the scrollbar

Or else

VerticalScrollBarVisibility="Auto"

and set any height for Listbox scroll bar will be visible only content reaches its max Listbox height.

Or

Try this to achieve the desired height by binding the ListBox height property to the ActualHeight of the LayoutRoot Grid via the XAML below:

<Grid x:Name="LayoutRoot" Background="LightGray">
<Grid.ColumnDefinitions>
    <ColumnDefinition Width=".24*"/>
    <ColumnDefinition Width=".73*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
    <RowDefinition Height=".9*"/>
    <RowDefinition Height=".1*"/>
</Grid.RowDefinitions>
<ListBox Name="Subdivisions" SelectedItem="{Binding SelectedSubdivisionViewModel}" ItemsSource="{Binding Path=Subdivisions}" Grid.IsSharedSizeScope="True" Height="{Binding ElementName=LayoutRoot, Path=ActualHeight}" >

The important bit being:

 Height="{Binding ElementName=LayoutRoot, Path=ActualHeight}"

Also achievable via ancestor type:

 Height="{Binding Path=ActualHeight, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}}}"

Its my working code you can change it from grid to Dockpanel.


问:
How to create autocomplete form with MaterializeCss?
I am looking for autocomplete form for MaterializeCss, any plugins for this? i has try to use select2 but that's css not looks good</p>

答:
Visit the link for demo https://ampersandacademy.com/demo/autocomplete/

you can easily achieve the autocomplete functionality using the Devberidge plugin.

Get Devbridge plugin using https://github.com/devbridge/jQuery-Autocomplete

```<code> <script type="text/javascript">

$(document).ready(function() {

          $("#country").devbridgeAutocomplete({
            //lookup: countries,
            serviceUrl:"getCountry.php", //tell the script where to send requests
              type:'POST',

              //callback just to show it's working
              onSelect: function (suggestion) {
                 // $('#selection').html('You selected: ' + suggestion.value + ', ' + suggestion.data);
                },
            showNoSuggestionNotice: true,
            noSuggestionNotice: 'Sorry, no matching results',

          });

});
</code>```

Here the getCountry.php file returns the JSON data. For more info visit https://ampersandacademy.com/tutorials/materialize-css/materialize-css-framework-ajax-autocomplete-example-using-php

Body:
Visit the link for demo https://ampersandacademy.com/demo/autocomplete/

you can easily achieve the autocomplete functionality using the Devberidge plugin.

Get Devbridge plugin using https://github.com/devbridge/jQuery-Autocomplete

 <script type="text/javascript">

$(document).ready(function() {

          $("#country").devbridgeAutocomplete({
            //lookup: countries,
            serviceUrl:"getCountry.php", //tell the script where to send requests
              type:'POST',

              //callback just to show it's working
              onSelect: function (suggestion) {
                 // $('#selection').html('You selected: ' + suggestion.value + ', ' + suggestion.data);
                },
            showNoSuggestionNotice: true,
            noSuggestionNotice: 'Sorry, no matching results',

          });

});

Here the getCountry.php file returns the JSON data. For more info visit https://ampersandacademy.com/tutorials/materialize-css/materialize-css-framework-ajax-autocomplete-example-using-php


问:
facebook sdk getuser() always return 0 after login?
Below is my controller. I am trying to login using facebook php sdk. In it getuser() function always return 0 after login.  What is the problem?

```<code><?php defined('BASEPATH') OR exit('No direct script access allowed');
class User_Authentication extends CI_Controller
{
    function __construct() {
        parent::__construct();
        // Load user model
        $this->load->model('user');
    }

    public function index(){

       // Include the facebook api php libraries
        include_once APPPATH."libraries/facebook-api-php-codexworld/facebook.php";

        // Facebook API Configuration
        $appId = '1863771173889202';
        $appSecret = 'e86b25ccab12bc88c46aac322ebc40eb';
        $redirectUrl = base_url() . 'user_authentication/';
        $fbPermissions = 'email';

        //Call Facebook API
        $facebook = new Facebook(array(
          'appId'  => $appId,
          'secret' => $appSecret

        ));
        $fbuser = $facebook->getUser();

        if ($fbuser) {
            $userProfile = $facebook->api('/me?fields=id,first_name,last_name,email,gender,locale,picture');
            // Preparing data for database insertion
            $userData['oauth_provider'] = 'facebook';
            $userData['oauth_uid'] = $userProfile['id'];
            $userData['first_name'] = $userProfile['first_name'];
            $userData['last_name'] = $userProfile['last_name'];
            $userData['email'] = $userProfile['email'];
            $userData['gender'] = $userProfile['gender'];
            $userData['locale'] = $userProfile['locale'];
            $userData['profile_url'] = 'https://www.facebook.com/'.$userProfile['id'];
            $userData['picture_url'] = $userProfile['picture']['data']['url'];
            // Insert or update user data
            $userID = $this->user->checkUser($userData);
            if(!empty($userID)){
                $data['userData'] = $userData;
                $this->session->set_userdata('userData',$userData);
            } else {
               $data['userData'] = array();
            }
        } else {
            $fbuser = '';
            $data['authUrl'] = $facebook->getLoginUrl(array('redirect_uri'=>$redirectUrl,'scope'=>$fbPermissions));
        }
        $this->load->view('user_authentication/index',$data);
    }

    public function logout() {
        $this->session->unset_userdata('userData');
        $this->session->sess_destroy();
        redirect('/user_authentication');
    }
}
</code>```

I am a beginner here so please help me resolve my issue.

答:
I think you need to check the redirect_uri and put the proper URL in it.
    Here is the line of code I thinks its help you:

```<code>$loginUrl = $facebook->getLoginUrl(array (
'display' => 'popup',
'redirect_uri' => 'http://localhost/demo/index.php'
));
</code>```

Body:
Below is my controller. I am trying to login using facebook php sdk. In it getuser() function always return 0 after login.  What is the problem?

<?php defined('BASEPATH') OR exit('No direct script access allowed');
class User_Authentication extends CI_Controller
{
    function __construct() {
        parent::__construct();
        // Load user model
        $this->load->model('user');
    }

    public function index(){

       // Include the facebook api php libraries
        include_once APPPATH."libraries/facebook-api-php-codexworld/facebook.php";

        // Facebook API Configuration
        $appId = '1863771173889202';
        $appSecret = 'e86b25ccab12bc88c46aac322ebc40eb';
        $redirectUrl = base_url() . 'user_authentication/';
        $fbPermissions = 'email';

        //Call Facebook API
        $facebook = new Facebook(array(
          'appId'  => $appId,
          'secret' => $appSecret

        ));
        $fbuser = $facebook->getUser();

        if ($fbuser) {
            $userProfile = $facebook->api('/me?fields=id,first_name,last_name,email,gender,locale,picture');
            // Preparing data for database insertion
            $userData['oauth_provider'] = 'facebook';
            $userData['oauth_uid'] = $userProfile['id'];
            $userData['first_name'] = $userProfile['first_name'];
            $userData['last_name'] = $userProfile['last_name'];
            $userData['email'] = $userProfile['email'];
            $userData['gender'] = $userProfile['gender'];
            $userData['locale'] = $userProfile['locale'];
            $userData['profile_url'] = 'https://www.facebook.com/'.$userProfile['id'];
            $userData['picture_url'] = $userProfile['picture']['data']['url'];
            // Insert or update user data
            $userID = $this->user->checkUser($userData);
            if(!empty($userID)){
                $data['userData'] = $userData;
                $this->session->set_userdata('userData',$userData);
            } else {
               $data['userData'] = array();
            }
        } else {
            $fbuser = '';
            $data['authUrl'] = $facebook->getLoginUrl(array('redirect_uri'=>$redirectUrl,'scope'=>$fbPermissions));
        }
        $this->load->view('user_authentication/index',$data);
    }

    public function logout() {
        $this->session->unset_userdata('userData');
        $this->session->sess_destroy();
        redirect('/user_authentication');
    }
}

I am a beginner here so please help me resolve my issue.

Body:
I think you need to check the redirect_uri and put the proper URL in it.
    Here is the line of code I thinks its help you:

$loginUrl = $facebook->getLoginUrl(array (
'display' => 'popup',
'redirect_uri' => 'http://localhost/demo/index.php'
));


问:
Catch error before process odoo9
If enter wrong web code in my below example i get 500: Internal Server Error. Is it possible get validation error alert?

@http.route('/web/process', type="http", auth="public", website=True)
def send_ticket(self, **kwargs):

    values = {}
    for field_name, field_value in kwargs.items():
        values[field_name] = field_value

    if values['web_code'] != "9999":
        raise ValidationError(_('Wrong web code!'))

    vals = {'name': values['web_name']}
    create_new = http.request.env['project.task'].create(vals)
```

答:
in odoo website module you can not raise error like we do in sale and purchase module.

to display error to user you need render same page with error label in your template .

this link many help you more raise warring in odoo website

Title: Catch error before process odoo9


问:
Binary search of a Matrix

Write an efficient algorithm that searches for a value in an m x n
  matrix.

This matrix has the following properties:

-Integers in each row are sorted from left to right.
-The first integer
  of each row is greater than or equal to the last integer of the
  previous row.

Example:

Consider the following matrix:

[

    [1,   3,  5,  7],

[10, 11, 16, 20],
   [23, 30, 34, 50]
]
Given
  target = 3, return 1 ( 1 corresponds to true )

Return 0 / 1 ( 0 if the element is not present, 1 if the element is
  present ) for this problem

My solution works on NetBeans but fails on the website. Any help will be appreciated.
https://www.interviewbit.com/problems/matrix-search/

```<code>public class Solution {

    public int searchMatrix(ArrayList<ArrayList<Integer>> a, int b) {
        int r = a.size();
        int c = a.get(0).size();

        int start = 0;
        int end = r - 1;
        // default value is last row for edge case
        int biRow = r -1; // row to search column

        //binary search 1st value of rows
        while (start <= end) {
            int mid = (start + end) / 2;
            if (b == a.get(mid).get(0)) {
                return 1;
            }

            if (a.get(mid).get(0) < b && b < a.get(end).get(0)) {
                if (mid + 1 >= end) {
                    biRow = mid;
                    break;
                }
            } if (b < a.get(mid).get(0)) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        //binary search column of biRow
        start = 0;
        end = c-1;
        while (start <= end) {
            int mid = (start + end) / 2;
            if (b == a.get(biRow).get(mid)) {
                return 1;
            }
            if (b < a.get(biRow).get(mid)) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        return 0;
    }
}
</code>```

答:
I think the shared program seems to have a logical error.

When updating the end value in the first while loop, if the end value is equal to start, biRow can not be updated.

It worked well when I updated the code like below.

```<code>public class Solution {
    public int searchMatrix(ArrayList<ArrayList<Integer>> a, int b) {
        int r = a.size();
        int c = a.get(0).size();
        int start = 0;
        int end = r - 1;
        // default value is last row for edge case
        int biRow = r -1; // row to search column

        //binary search 1st value of rows
        int mid = 0;
        while (start <= end) {
            mid = (start + end) / 2;
            if ( b >= a.get(mid).get(0) && b <= a.get(mid).get(c-1)) {
                break;
            }
            if (b < a.get(mid).get(0)) {
                end = mid-1;
            } else {
                start = mid+1;
            }
       }

        biRow = mid;

        //binary search column of biRow
        start = 0;
        end = c-1;
        while (start <= end) {
            mid = (start + end) / 2;
            if (b == a.get(biRow).get(mid)) {
                return 1;
            }
            if (b < a.get(biRow).get(mid)) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        return 0;
    }
}
</code>```

Title: Binary search of a Matrix

Body:
Write an efficient algorithm that searches for a value in an m x n
  matrix.

This matrix has the following properties:

-Integers in each row are sorted from left to right.
-The first integer
  of each row is greater than or equal to the last integer of the
  previous row.

Example:

Consider the following matrix:

[

    [1,   3,  5,  7],

[10, 11, 16, 20],
   [23, 30, 34, 50]
]
Given
  target = 3, return 1 ( 1 corresponds to true )

Return 0 / 1 ( 0 if the element is not present, 1 if the element is
  present ) for this problem

My solution works on NetBeans but fails on the website. Any help will be appreciated.
https://www.interviewbit.com/problems/matrix-search/

public class Solution {

    public int searchMatrix(ArrayList<ArrayList<Integer>> a, int b) {
        int r = a.size();
        int c = a.get(0).size();

        int start = 0;
        int end = r - 1;
        // default value is last row for edge case
        int biRow = r -1; // row to search column

        //binary search 1st value of rows
        while (start <= end) {
            int mid = (start + end) / 2;
            if (b == a.get(mid).get(0)) {
                return 1;
            }

            if (a.get(mid).get(0) < b && b = end) {
                    biRow = mid;
                    break;
                }
            } if (b < a.get(mid).get(0)) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        //binary search column of biRow
        start = 0;
        end = c-1;
        while (start <= end) {
            int mid = (start + end) / 2;
            if (b == a.get(biRow).get(mid)) {
                return 1;
            }
            if (b < a.get(biRow).get(mid)) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        return 0;
    }
}

Body:
I think the shared program seems to have a logical error.

When updating the end value in the first while loop, if the end value is equal to start, biRow can not be updated.

It worked well when I updated the code like below.

public class Solution {
    public int searchMatrix(ArrayList<ArrayList<Integer>> a, int b) {
        int r = a.size();
        int c = a.get(0).size();
        int start = 0;
        int end = r - 1;
        // default value is last row for edge case
        int biRow = r -1; // row to search column

        //binary search 1st value of rows
        int mid = 0;
        while (start <= end) {
            mid = (start + end) / 2;
            if ( b >= a.get(mid).get(0) && b <= a.get(mid).get(c-1)) {
                break;
            }
            if (b < a.get(mid).get(0)) {
                end = mid-1;
            } else {
                start = mid+1;
            }
       }

        biRow = mid;

        //binary search column of biRow
        start = 0;
        end = c-1;
        while (start <= end) {
            mid = (start + end) / 2;
            if (b == a.get(biRow).get(mid)) {
                return 1;
            }
            if (b < a.get(biRow).get(mid)) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        return 0;
    }
}


问:
Elastic Search query to check for null values in 2 fields
What is the elastic search query to search for documents where "field1 is null OR field2 is null"..

I am using elasticSearch 5.3...

答:
This query did work for me:

```<code>curl -XGET "http://localhost:9200/my_null_val/_search?pretty" -d '
{
  "query": {
    "bool":{
      "must_not":{
        "bool": {
          "must": [
            {"exists" : { "field" : "field1" }},
            {"exists" : { "field" : "field2" }}
          ]
        }
      }
    }
  }
}'
</code>```

As a hint you can think of field1 is null **OR** field2 is null to be equivalent expression to NOT (field1 is not null **AND** field2 is not null).

It is also known as De_Morgan's law.

Body:
This query did work for me:

curl -XGET "http://localhost:9200/my_null_val/_search?pretty" -d '
{
  "query": {
    "bool":{
      "must_not":{
        "bool": {
          "must": [
            {"exists" : { "field" : "field1" }},
            {"exists" : { "field" : "field2" }}
          ]
        }
      }
    }
  }
}'

As a hint you can think of field1 is null **OR** field2 is null to be equivalent expression to NOT (field1 is not null **AND** field2 is not null).

It is also known as De_Morgan's law.


问:
Table squashing to fit (css)
If I put a table that naturally would be 800px wide in a div that is 700px wide, even with the css property overflow:scroll; set, the table is still 'squashed' into the the 700px space.

Is there any html or css I can edit/re-architect to fix this?

答:
this will be your required markup</p>

```<code><div style="width:700px; height:300px; overflow:auto; border:1px solid red;">
    <table width="800" border="1">
        <tr><td> Col 1 </td> <td> col 2 </td></tr>
    </table>
</div>
</code>```

Title: Table squashing to fit (css)

Body:
this will be your required markup

<div style="width:700px; height:300px; overflow:auto; border:1px solid red;">
    <table width="800" border="1">
        <tr><td> Col 1 </td> <td> col 2 </td></tr>
    </table>
</div>


问:
How to check task status in Celery?
How does one check whether a task is running in celery (specifically, I'm using celery-django)?

I've read the documentation, and I've googled, but I can't see a call like:

```<code>my_example_task.state() == RUNNING
</code>```

My use-case is that I have an external (java) service for transcoding. When I send a document to be transcoded, I want to check if the task that runs that service is running, and if not, to (re)start it.

I'm using the current stable versions - 2.4, I believe.

答:
for simple tasks, we can use http://flower.readthedocs.io/en/latest/screenshots.html and http://policystat.github.io/jobtastic/ to do the monitoring.

and for complicated tasks, say a task which deals with a lot other modules. We recommend manually record the progress and message on the specific task unit.

Title: How to check task status in Celery?

Body:
How does one check whether a task is running in celery (specifically, I'm using celery-django)?

I've read the documentation, and I've googled, but I can't see a call like:

my_example_task.state() == RUNNING

My use-case is that I have an external (java) service for transcoding. When I send a document to be transcoded, I want to check if the task that runs that service is running, and if not, to (re)start it.

I'm using the current stable versions - 2.4, I believe.


问:
Dagger2 & Android - Decide which implementation of an interface to inject at run time
Hi I'm very new to Dagger, and I'm struggling to understand how to get things to work. I want to use it in a project. This project needs to use different implementations based on OS or Manufacturer or Model. But it will need to wait for Device Administrator and Runtime Permissions to be granted.

I made a quick repo with a tiny demo. The PostPermissionActivityModule is working, but the chosenWiFiImplementation is not. My main focus is how to get the WiFiImplementation set correctly in the Activity and delivered in the Processor Object. Other improvements are welcome but not really what I'm looking for.

Thanks:

https://github.com/pnogas/DaggerTest

答:
```<code>@Component(modules = {PostPermissionActivityModule.class, MyWifFiManagerInterfaceModule.class})
@Singleton
public interface PostPermissionActivityComponent {
    void inject(PostPermissionActivity postPermissionActivity);
    void inject(MyWiFiManagerInterface myWiFiManagerInterface);
}
</code>```

This won't inject MyWifiManagerInterface,In order to work wifi manager you need to create another component for MyWifiManagerInterface

Refer this Answer

And for better architecture design using dagger you can refer this Example

Body:
@Component(modules = {PostPermissionActivityModule.class, MyWifFiManagerInterfaceModule.class})
@Singleton
public interface PostPermissionActivityComponent {
    void inject(PostPermissionActivity postPermissionActivity);
    void inject(MyWiFiManagerInterface myWiFiManagerInterface);
}

This won't inject MyWifiManagerInterface,In order to work wifi manager you need to create another component for MyWifiManagerInterface

Refer this Answer

And for better architecture design using dagger you can refer this Example


问:
How to add diffrent css class to html for every foreach loop in knockout js
KnockoutJS Data

```<code>function ExampleViewModel() {
    var self = this;
    self.ExampleData = ko.observableArray([]);
    self.update = function() {
        $.ajax("test.json", {
            success: function(allData) {
                var mappeddata = $.map(allData, function(item) {
                    return new DataItem(item)
                });
                self.ExampleData(mappeddata);
            }
        });
    }
}

function DataItem(data) {
    this.Name = ko.observable(data.name);
}
var exampleViewModel = new ExampleViewModel();
ko.applyBindings(exampleViewModel);
</code>```

Html Data

```<code>    <div data-bind="foreach: ExampleData">
      <div class="has-topic-background-color">
      </div>
    </div>
</code>```

How I can change class of below div in every foreach loop
  div class="has-topic-background-color

i need if in first loop its show red color then in second loop i need blue color insted of red

答:
You can use css binding

http://knockoutjs.com/documentation/css-binding.html

function ViewModel() {
  var self = this;
  self.data = ko.observableArray([1, 2, 3, 4, 5, 6, 7, 8, 9]);
  self.className = function(index) {
    return index % 2 === 0? 'redClass' : 'blueClass';
  };
  self.textValue = function(index) {
    return 'Data  for index ' + index + ' has background ' + self.className(index);
  }
}

$(document).ready(function () {
  var myViewModel = new ViewModel();
  ko.applyBindings(myViewModel);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<div>
  You can inspect the element to see the class name
</div>
<br/>

<div data-bind="foreach: data">
  <div data-bind="text: $parent.textValue($index()), css: $parent.className($index())"></div>
</div></code>```

Body:
KnockoutJS Data

function ExampleViewModel() {
    var self = this;
    self.ExampleData = ko.observableArray([]);
    self.update = function() {
        $.ajax("test.json", {
            success: function(allData) {
                var mappeddata = $.map(allData, function(item) {
                    return new DataItem(item)
                });
                self.ExampleData(mappeddata);
            }
        });
    }
}

function DataItem(data) {
    this.Name = ko.observable(data.name);
}
var exampleViewModel = new ExampleViewModel();
ko.applyBindings(exampleViewModel);

Html Data

How I can change class of below div in every foreach loop
  div class="has-topic-background-color

i need if in first loop its show red color then in second loop i need blue color insted of red

Body:
You can use css binding

http://knockoutjs.com/documentation/css-binding.html

function ViewModel() {
  var self = this;
  self.data = ko.observableArray([1, 2, 3, 4, 5, 6, 7, 8, 9]);
  self.className = function(index) {
    return index % 2 === 0? 'redClass' : 'blueClass';
  };
  self.textValue = function(index) {
    return 'Data  for index ' + index + ' has background ' + self.className(index);
  }
}

$(document).ready(function () {
  var myViewModel = new ViewModel();
  ko.applyBindings(myViewModel);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<div>
  You can inspect the element to see the class name
</div>
<br/>

<div data-bind="foreach: data">
  <div data-bind="text: $parent.textValue($index()), css: $parent.className($index())"></div>
</div>


答:
Not according to this test http://jsfiddle.net/6J9AB/1/

Are you sure it is not something else ?

Do you define the table width to be 800px ? (how would it otherwise be 800px naturally ?)

Title: Table squashing to fit (css)

Body:
If I put a table that naturally would be 800px wide in a div that is 700px wide, even with the css property overflow:scroll; set, the table is still 'squashed' into the the 700px space.

Is there any html or css I can edit/re-architect to fix this?


问:
opencv2/tracking.hpp: No such file or directory on Ubuntu 16.04
i am working on tracking project so i needed tracking.hpp library. and every time i try to compile the project. it says fatal error: opencv2/tracking.hpp: No such file or directory
 #include

so i do some search and i found out that i have to download opencv_contrib and build it. and those are the the command line i used to build opencv_contrib.

"cd /home/pixar/Downloads/OpenCV/opencv-3.2.0/build"

"cmake -DOPENCV_EXTRA_MODULES_PATH= /home/Yasd/Downloads/OpenCV/opencv_contrib-master/modules .."

then
 "make -j5"

but the same error appears. so did i miss something?

答:
Seems like you forgot to run make install command. Go to your build directory and make install
Your path to tracking.hpp is wrong. Replace it with actual path

```<code>#include "opencv2/tracking/tracking.hpp"
</code>```

Also make sure you've added opencv to your project. With cmake it can be done like that:

```<code>find_package(OpenCV REQUIRED)
include_directories(OpenCV_INCLUDE_DIR)
</code>```

Source

Body:
Seems like you forgot to run make install command. Go to your build directory and make install
Your path to tracking.hpp is wrong. Replace it with actual path

#include "opencv2/tracking/tracking.hpp"

Also make sure you've added opencv to your project. With cmake it can be done like that:

find_package(OpenCV REQUIRED)
include_directories(OpenCV_INCLUDE_DIR)

Source


问:
SQLAlchemy: filter by relationship
I have 2 tables, User and Object, which have a one-to-many relationship (a User can have many objects ).

How can I filter for users that have at least one object, in a pep8 compliant way?

This code works, but is not pep8-compliant:

```<code>query = session.query(User.id)
query = query.filter(User.objects != None)
</code>```

The documentation mentions using isnot: http://docs.sqlalchemy.org/en/rel_1_0/orm/tutorial.html#common-filter-operators

But the following code gives rise to a not implemented error.

```<code>query = session.query(User.id)
query = query.filter(User.objects.isnot(None))
</code>```

答:
As you may know, in Django such filtering can be done in simple, declarative way:

```<code>Entry.objects.filter(blog__name='Beatles Blog')
</code>```

And I always dreamt to have something like this in SQLAlchemy.

Good news for you: few weeks ago, I created package for that: https://github.com/absent1706/sqlalchemy-mixins#django-like-queries

Also package contains very useful batteries: Active Record for SQLAlchemy as well as nested eager loading and readable __repr__.

Title: SQLAlchemy: filter by relationship

Body:
I have 2 tables, User and Object, which have a one-to-many relationship (a User can have many objects ).

How can I filter for users that have at least one object, in a pep8 compliant way?

This code works, but is not pep8-compliant:

query = session.query(User.id)
query = query.filter(User.objects != None)

The documentation mentions using isnot: http://docs.sqlalchemy.org/en/rel_1_0/orm/tutorial.html#common-filter-operators

But the following code gives rise to a not implemented error.

query = session.query(User.id)
query = query.filter(User.objects.isnot(None))

Body:
As you may know, in Django such filtering can be done in simple, declarative way:

Entry.objects.filter(blog__name='Beatles Blog')

And I always dreamt to have something like this in SQLAlchemy.

Good news for you: few weeks ago, I created package for that: https://github.com/absent1706/sqlalchemy-mixins#django-like-queries

Also package contains very useful batteries: Active Record for SQLAlchemy as well as nested eager loading and readable __repr__.


问:
Changing connection string for different Users
My application used Code first approach & Entity Framework 6.0.

My requirement is that when a User A logs in connection string AppSchema should be used for whole application & when User B logs in connection string AppSchema1 should be used. My application is very big, i want to achieve this from a central location.

Below is the code :-

Connection String :-

```<code> <add name="AppSchema" connectionString="Data Source=Server1\MSSQLSERVER2014;Initial Catalog=MSchema;Integrated Security=True;Persist Security Info=True;" providerName="System.Data.SqlClient" />
</code>```

Connection String 2 :-

```<code><add name="AppSchema1" connectionString="Data Source=Server1\MSSQLSERVER2014;Initial Catalog=MSchema;Integrated Security=True;Persist Security Info=True;" providerName="System.Data.SqlClient" />
</code>```

ApplicationDbContext :-

```<code>public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDbModelCacheKeyProvider, IDisposable
{
     public ApplicationDbContext(string schemaname)
                : base("AppSchema")
            {
                SchemaName = schemaname;
                ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 180;
            }
}
</code>```

Use :-

```<code> using (var ctx = new ApplicationDbContext(schemaName))
    {
        ....
        ctx.tblEmployee.Add(mod);
    }
</code>```

Can anyone suggest how to do this?

答:
You can create one static method which return connection string schema name. For example:

```<code>Public static String GetSchema()
{
string schemaName;
var userName=Session["UserName"];
switch (userName)
    {
    case "User A":
        schemaName="AppSchema";
        break;
        case "User B":
            schemaName="AppSchema1";
        break;
        default:
            schemaName="DefaultSchema";
}

return schemaName;
}
</code>```

Call this Method like

```<code>using (var ctx = new ApplicationDbContext(SomeClassName.GetSchema()))
{
    ....
    ctx.tblEmployee.Add(mod);
}
</code>```

Body:
My application used Code first approach & Entity Framework 6.0.

My requirement is that when a User A logs in connection string AppSchema should be used for whole application & when User B logs in connection string AppSchema1 should be used. My application is very big, i want to achieve this from a central location.

Below is the code :-

Connection String :-

 <add name="AppSchema" connectionString="Data Source=Server1\MSSQLSERVER2014;Initial Catalog=MSchema;Integrated Security=True;Persist Security Info=True;" providerName="System.Data.SqlClient" />

Connection String 2 :-

<add name="AppSchema1" connectionString="Data Source=Server1\MSSQLSERVER2014;Initial Catalog=MSchema;Integrated Security=True;Persist Security Info=True;" providerName="System.Data.SqlClient" />

ApplicationDbContext :-

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDbModelCacheKeyProvider, IDisposable
{
     public ApplicationDbContext(string schemaname)
                : base("AppSchema")
            {
                SchemaName = schemaname;
                ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 180;
            }
}

Use :-

 using (var ctx = new ApplicationDbContext(schemaName))
    {
        ....
        ctx.tblEmployee.Add(mod);
    }

Can anyone suggest how to do this?

Body:
You can create one static method which return connection string schema name. For example:

Public static String GetSchema()
{
string schemaName;
var userName=Session["UserName"];
switch (userName)
    {
    case "User A":
        schemaName="AppSchema";
        break;
        case "User B":
            schemaName="AppSchema1";
        break;
        default:
            schemaName="DefaultSchema";
}

return schemaName;
}

Call this Method like

using (var ctx = new ApplicationDbContext(SomeClassName.GetSchema()))
{
    ....
    ctx.tblEmployee.Add(mod);
}


答:
In window.fbAsyncInit I have set cookie and oauth to true and this worked!

cookie:true,

oauth : true.

Make sure that In your php you also have

cookie' => true.

That will enable the php code to integrare with the JS.

And you need to make sure the user has logged in with:

$loginUrl = $facebook->getLoginUrl(array( 'scope' => 'read_stream,etc..'));

The scope is defined by the permissions stated here

After that you should be able to do:

$user = $facebook->api("/me");

Which will get an array associated with the user, $user['id'] is probably the one you'll want to store as well as any other information like email address - be sure to request for email in the scope

Hope that solves the problem!

Title: facebook sdk getuser() always return 0 after login?


问:
Create a calendar day table
I am trying to write a code where i can plug in a date and my table below will populate the expected date table with all the date for the particular month from CD1(Calendar Day 1) all the way to CD30 or CD31 or in February case CD28.  I know i should begin my code with something like

```<code>Declare @startdate as datetime
Set @startdate = '20170401'
</code>```

But after that I get confused with the DateAdd and DatePart code to create this query to produce the results

```date rule  | expected date |
----------------------------
| CD1      | 4/1/2017      |
| CD2      | 4/2/2017      |
| CD3      | 4/3/2017      |
| CD4      | 4/4/2017      |
| CD5      | 4/5/2017      |
| CD6      | 4/6/2017      |
```

Can anyone provide any assistance?

答:
Try below query, this will give you the required output:

```<code>DECLARE @STARTDATE DATETIME
SET @STARTDATE= CAST(MONTH(CURRENT_TIMESTAMP) AS     VARCHAR(100))+'/'+'01'+'/'+CAST(YEAR(CURRENT_TIMESTAMP) AS VARCHAR(100))
;WITH MONTHDATA
AS
(SELECT @STARTDATE MONTHDATE
UNION ALL
SELECT DATEADD(D,1,MONTHDATE) FROM MONTHDATA WHERE     MONTHDATE<DATEADD(D,-1,DATEADD(M,1,@STARTDATE))
)
SELECT 'CD'+CAST( (ROW_NUMBER()OVER (ORDER BY MONTHDATE)) AS         VARCHAR(100))DATE_RULE,CONVERT(VARCHAR,MONTHDATE,101)MONTHDATE FROM MONTHDATA
</code>```

OUTPUT

```<code>----------------------
DATE_RULE   MONTHDATE
----------------------
CD1 03/01/2017
CD2 03/02/2017
CD3 03/03/2017
.
.
.
CD29    03/29/2017
CD30    03/30/2017
CD31    03/31/2017
----------------------
</code>```

Title: Create a calendar day table

Body:
I am trying to write a code where i can plug in a date and my table below will populate the expected date table with all the date for the particular month from CD1(Calendar Day 1) all the way to CD30 or CD31 or in February case CD28.  I know i should begin my code with something like

Declare @startdate as datetime
Set @startdate = '20170401'

But after that I get confused with the DateAdd and DatePart code to create this query to produce the results

date rule  | expected date |
----------------------------
| CD1      | 4/1/2017      |
| CD2      | 4/2/2017      |
| CD3      | 4/3/2017      |
| CD4      | 4/4/2017      |
| CD5      | 4/5/2017      |
| CD6      | 4/6/2017      |

Can anyone provide any assistance?

Body:
Try below query, this will give you the required output:

DECLARE @STARTDATE DATETIME
SET @STARTDATE= CAST(MONTH(CURRENT_TIMESTAMP) AS     VARCHAR(100))+'/'+'01'+'/'+CAST(YEAR(CURRENT_TIMESTAMP) AS VARCHAR(100))
;WITH MONTHDATA
AS
(SELECT @STARTDATE MONTHDATE
UNION ALL
SELECT DATEADD(D,1,MONTHDATE) FROM MONTHDATA WHERE     MONTHDATE<DATEADD(D,-1,DATEADD(M,1,@STARTDATE))
)
SELECT 'CD'+CAST( (ROW_NUMBER()OVER (ORDER BY MONTHDATE)) AS         VARCHAR(100))DATE_RULE,CONVERT(VARCHAR,MONTHDATE,101)MONTHDATE FROM MONTHDATA

OUTPUT

----------------------
DATE_RULE   MONTHDATE
----------------------
CD1 03/01/2017
CD2 03/02/2017
CD3 03/03/2017
.
.
.
CD29    03/29/2017
CD30    03/30/2017
CD31    03/31/2017
----------------------