问:
In ASP.NET MVC, How do I synchronise or combine two collections of different types
I have two collections, OrderItems and Items. The reason there are two is because in my model I have an Item which is fixed, and an OrderItem which relates to an Item and adds order specific information such as quantity and a property (OrderID) that relates back to my Order object.

In Entity Framework 4, in order to have a collection of objects in a model you need to relate back to that model in the collection type's object. This makes the OrderID property in Item necessary.

Here are the POCO's in code:

```<code>public class Order {
    public int OrderID { get; set; }
    public DateTime DatePlaced { get; set; }
    public bool Filled { get; set; }
    public string Comment { get; set; }

    public virtual ICollection<OrderItem> OrderItems { get; set; }
}

public class OrderItem {
    public int OrderItemID { get; set; }
    public int OrderID { get; set; }
    public int Quantity { get; set; }
    public int ItemID { get; set; }
}

public class Item {
    public int ItemID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public int Size { get; set; }
}
</code>```

So now I have my models, and I want to display an Order Details page. I can send over the Order to the ViewModel (MVC 3) or ViewData (MVC 2/1) from the controller which works fine, and I can send a collection of Item as well, but how do I display a list of Items that contain both the Item properties and the Quantity from the OrderItem? Since both are collections, I could OrderBy ItemID and loop over both at the same time in the view, but that seems really messy.

I fiddled with creating an anonymous class that combined both Items and Order but that didn't really work when it came to combining the collections.

I basically want to loop through each Item and OrderItem and display the following properties, without doing it in the view:

Name

Description

Size

Quantity

Ideas?

答:
I believe, forgive me if I'm wrong, but with EntityFramework (assuming code first, but I think db first you can still do it) you can set the following:

```<code>public class OrderItem {
    public int OrderItemID { get; set; }
    public int OrderID { get; set; }
    public int Quantity { get; set; }
    public virtual Item Item { get; set; }
}
</code>```

And then when you refer to Item.Name etc. it will lazily load the data in. I don't have access at the moment to test.

Hope this helps, or at least guides you in the right direction.

Edit

Thinking about it, I believe if you're doing db first then as long as you've got the relationship defined in the database then you should be able to access the associated Item from the OrderItem through the relationship property.

Body:
I have two collections, OrderItems and Items. The reason there are two is because in my model I have an Item which is fixed, and an OrderItem which relates to an Item and adds order specific information such as quantity and a property (OrderID) that relates back to my Order object.

In Entity Framework 4, in order to have a collection of objects in a model you need to relate back to that model in the collection type's object. This makes the OrderID property in Item necessary.

Here are the POCO's in code:

public class Order {
    public int OrderID { get; set; }
    public DateTime DatePlaced { get; set; }
    public bool Filled { get; set; }
    public string Comment { get; set; }

    public virtual ICollection<OrderItem> OrderItems { get; set; }
}

public class OrderItem {
    public int OrderItemID { get; set; }
    public int OrderID { get; set; }
    public int Quantity { get; set; }
    public int ItemID { get; set; }
}

public class Item {
    public int ItemID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public int Size { get; set; }
}

So now I have my models, and I want to display an Order Details page. I can send over the Order to the ViewModel (MVC 3) or ViewData (MVC 2/1) from the controller which works fine, and I can send a collection of Item as well, but how do I display a list of Items that contain both the Item properties and the Quantity from the OrderItem? Since both are collections, I could OrderBy ItemID and loop over both at the same time in the view, but that seems really messy.

I fiddled with creating an anonymous class that combined both Items and Order but that didn't really work when it came to combining the collections.

I basically want to loop through each Item and OrderItem and display the following properties, without doing it in the view:

Name

Description

Size

Quantity

Ideas?

Body:
I believe, forgive me if I'm wrong, but with EntityFramework (assuming code first, but I think db first you can still do it) you can set the following:

public class OrderItem {
    public int OrderItemID { get; set; }
    public int OrderID { get; set; }
    public int Quantity { get; set; }
    public virtual Item Item { get; set; }
}

And then when you refer to Item.Name etc. it will lazily load the data in. I don't have access at the moment to test.

Hope this helps, or at least guides you in the right direction.

Edit

Thinking about it, I believe if you're doing db first then as long as you've got the relationship defined in the database then you should be able to access the associated Item from the OrderItem through the relationship property.


来源: stackexchange

问:
ios Charts 3 - Plot X Axis Labels per Data Point
I have 30 data points on a graph, but the chart's X Axis splits up the numbers, and doesn't give a label per data point. See below.

![1]: https://i.stack.imgur.com/I1vAP.png

```<code>class TrendChartViewController: UIViewController {
@IBOutlet var combinedChart: CombinedChartView!
var viewModel: TrendChartViewModelProtocol! {
    didSet {
        updateChart()
    }
}

private func updateChart() {
    if let dataset = viewModel.dataset {
        let data = CombinedChartData()
        data.lineData = LineChartData(dataSets: [dataset.current, dataset.py])
        data.barData = getBarChartData(dataset: dataset.budget)
        combinedChart.data = data
        combinedChart.xAxis.valueFormatter = DateValueFormatter(timeframe: viewModel.timeframe)
        removeGridLines()
    }
}

private func getBarChartData(dataset: BarChartDataSet) -> BarChartData {
    var barChartData = BarChartData(dataSet: dataset)
    barChartData.barWidth = 0.45
    return barChartData
}

private func removeGridLines() {
    combinedChart.xAxis.drawGridLinesEnabled = false
    combinedChart.leftAxis.drawGridLinesEnabled = false
    combinedChart.rightAxis.drawGridLinesEnabled = false
    combinedChart.drawGridBackgroundEnabled = false
}
</code>```

Here is an example of one of our dataset...

```<code>private func getCurrentDataSet() -> LineChartDataSet {
    let values = timeframe == .days ? report?.charts[0].data.days : report?.charts[0].data.months
    let currentEntries: [ChartDataEntry] = values?
        .enumerated()
        .flatMap {
            return ChartDataEntry(x: Double($0), y: $1.current[unit.rawValue] ?? 0)
        } ?? []

    let currentDataSet = LineChartDataSet(values: currentEntries, label: NSLocalizedString("Current", comment: ""))
    let color = UIColor.Bridgestone.forest.B500
    currentDataSet.setColor(color)
    currentDataSet.circleColors = [color]
    currentDataSet.circleHoleColor = color
    currentDataSet.circleRadius = 5
    currentDataSet.lineWidth = 2.5
    return currentDataSet
}
</code>```

So how can I get it to show X Axis label values per data point? Thanks!

答:
You need to use func xAxis.setLabelCount if you want to set number of labels on xAxis, e.g.</p>

```<code>combinedChart.xAxis.setLabelCount(countOfMyDataPoints, force: true)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have 30 data points on a graph, but the chart's X Axis splits up the numbers, and doesn't give a label per data point. See below.

![1]: https://i.stack.imgur.com/I1vAP.png

class TrendChartViewController: UIViewController {
@IBOutlet var combinedChart: CombinedChartView!
var viewModel: TrendChartViewModelProtocol! {
    didSet {
        updateChart()
    }
}

private func updateChart() {
    if let dataset = viewModel.dataset {
        let data = CombinedChartData()
        data.lineData = LineChartData(dataSets: [dataset.current, dataset.py])
        data.barData = getBarChartData(dataset: dataset.budget)
        combinedChart.data = data
        combinedChart.xAxis.valueFormatter = DateValueFormatter(timeframe: viewModel.timeframe)
        removeGridLines()
    }
}

private func getBarChartData(dataset: BarChartDataSet) -> BarChartData {
    var barChartData = BarChartData(dataSet: dataset)
    barChartData.barWidth = 0.45
    return barChartData
}

private func removeGridLines() {
    combinedChart.xAxis.drawGridLinesEnabled = false
    combinedChart.leftAxis.drawGridLinesEnabled = false
    combinedChart.rightAxis.drawGridLinesEnabled = false
    combinedChart.drawGridBackgroundEnabled = false
}

Here is an example of one of our dataset...

private func getCurrentDataSet() -> LineChartDataSet {
    let values = timeframe == .days ? report?.charts[0].data.days : report?.charts[0].data.months
    let currentEntries: [ChartDataEntry] = values?
        .enumerated()
        .flatMap {
            return ChartDataEntry(x: Double($0), y: $1.current[unit.rawValue] ?? 0)
        } ?? []

    let currentDataSet = LineChartDataSet(values: currentEntries, label: NSLocalizedString("Current", comment: ""))
    let color = UIColor.Bridgestone.forest.B500
    currentDataSet.setColor(color)
    currentDataSet.circleColors = [color]
    currentDataSet.circleHoleColor = color
    currentDataSet.circleRadius = 5
    currentDataSet.lineWidth = 2.5
    return currentDataSet
}

So how can I get it to show X Axis label values per data point? Thanks!

Body:
You need to use func xAxis.setLabelCount if you want to set number of labels on xAxis, e.g.

combinedChart.xAxis.setLabelCount(countOfMyDataPoints, force: true)


问:
unable to using winapp
I am unable to run the code

```<code>capabilities.setCapability("app", "C:\\Windows\\System32\\calc.exe");
CalculatorSession = new IOSDriver(new URL("http://127.0.0.1:4723"), capabilities);
</code>```

this code opens the calculator app but it say IOSDriver is wrong

Original code

I changed just two lines of the code

Software: Java, Eclipse, WinappDriver

I am automating Windows application in Windows 10

答: I solved the above problem updating the driver manual rather than taking the auto-suggestion version in maven</p>

Title: unable to using winapp

Body:
I am unable to run the code

capabilities.setCapability("app", "C:\\Windows\\System32\\calc.exe");
CalculatorSession = new IOSDriver(new URL("http://127.0.0.1:4723"), capabilities);

this code opens the calculator app but it say IOSDriver is wrong

Original code

I changed just two lines of the code

Software: Java, Eclipse, WinappDriver

I am automating Windows application in Windows 10


问:
Generate a clock delay by fixed cycles number Verilog
I have a clock which is always active, I have another clock call it "sample" , which is generated from the first clock . I want to generate a delay of "sample" signal by fixed number of cycles of the first clock signal in verilog</p>

答: I think you need to add a count down counter, otherwise, it keeps shifting to the left without ending. </p>


问:
Easy way to get daily pageviews (different to each url)?
I need to display daily pageviews in my wordpress site. The problem is I need it to be url aware I mean not count visits for the whole site but just count how many visits the current URL had. Is there an easy way to do so?</p>

答:
you can use wp post views http://wordpress.org/extend/plugins/wp-postviews/

i've used it before. you won't get analytics but if you include the post views function in your page you can see how much.

it also has options, like whether to count bots or not.

ContentLicense: CC BY-SA 2.5


问:
Use BlockingDataflowPipelineRunner and post-processing code for Dataflow template
I'd like to run some code after my pipeline finishes all processing, so I'm using BlockingDataflowPipelineRunner and placing code after pipeline.run() in main.

This works properly when I run the job from the command line using BlockingDataflowPipelineRunner. The code under pipeline.run() runs after the pipeline has finished processing.

However, it does not work when I try to run the job as a template. I deployed the job as a template (with TemplatingDataflowPipelineRunner), and then tried to run the template in a Cloud Function like this:

```<code>dataflow.projects.templates.create({
    projectId: 'PROJECT ID HERE',
    resource: {
        parameters: {
            runner: 'BlockingDataflowPipelineRunner'
        },
        jobName: `JOB NAME HERE`,
        gcsPath: 'GCS TEMPLATE PATH HERE'
    }
}, function(err, response) {
    if (err) {
        // etc
    }
    callback();
});
</code>```

The runner does not seem to take. I can put gibberish under runner and the job still runs.

The code I had under pipeline.run() does not run when each job runs -- it runs only when I deploy the template.

Is it expected that the code under pipeline.run() in main would not run each time the job runs? Is there a solution for executing code after the pipeline is finished?

(For context, the code after pipeline.run() moves a file from one Cloud Storage bucket to another. It's archiving the file that was just processed by the job.)

答:
Yes, this expected behavior. A template represents the pipeline itself, and allows (re-)executing the pipeline by launching the template. Since the template doesn't include any of the code from the main() method, it doesn't allow doing anything after the pipeline execution.

Similarly, the dataflow.projects.templates.create API is just the API to launch the template.

The way the blocking runner accomplished this was to get the job ID from the created pipeline and periodically poll to observe when it has completed. For your use case, you'll need to do the same:

Execute dataflow.projects.templates.create(...) to create the Dataflow job. This should return the job ID.

Periodically (every 5-10s, for instance) poll dataflow.projects.jobs.get(...) to retrieve the job with the given ID, and check what state it is in.

Body:
I'd like to run some code after my pipeline finishes all processing, so I'm using BlockingDataflowPipelineRunner and placing code after pipeline.run() in main.

This works properly when I run the job from the command line using BlockingDataflowPipelineRunner. The code under pipeline.run() runs after the pipeline has finished processing.

However, it does not work when I try to run the job as a template. I deployed the job as a template (with TemplatingDataflowPipelineRunner), and then tried to run the template in a Cloud Function like this:

dataflow.projects.templates.create({
    projectId: 'PROJECT ID HERE',
    resource: {
        parameters: {
            runner: 'BlockingDataflowPipelineRunner'
        },
        jobName: `JOB NAME HERE`,
        gcsPath: 'GCS TEMPLATE PATH HERE'
    }
}, function(err, response) {
    if (err) {
        // etc
    }
    callback();
});

The runner does not seem to take. I can put gibberish under runner and the job still runs.

The code I had under pipeline.run() does not run when each job runs -- it runs only when I deploy the template.

Is it expected that the code under pipeline.run() in main would not run each time the job runs? Is there a solution for executing code after the pipeline is finished?

(For context, the code after pipeline.run() moves a file from one Cloud Storage bucket to another. It's archiving the file that was just processed by the job.)


问:
Programmatically added buttons not matching theme
Using Theme.AppCompat in Gingerbread (API 10), programmatically added buttons do not match buttons added through XML. It works fine in all newer APIs, its only an issue with Gingerbread.  This image shows the issue.

Here is the code that adds the buttons:

```<code>for (int i = 0; i < btnFiles.length; i++) {
        btnFiles[i] = new Button(this);
        btnFiles[i].setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        btnFiles[i].setGravity(Gravity.CENTER);
        btnFiles[i].setId(100 + i);
        btnFiles[i].setText(fileList.get(i).replace(".xml", ""));
        btnFiles[i].setTag(fileList.get(i));
        registerForContextMenu(btnFiles[i]);
        btnFiles[i].setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                Continue(v);        //Start next activity when button is pressed
            }

        });

        l.addView(btnFiles[i]);
        setTitle(getString(R.string.title_activity_load_menu));
    }
</code>```

答:
Just to clarify for anyone passing by, the issue is probably that <Button> tags from XML get replaced by instances of AppCompatButton and <item name="buttonStyle">...</item> (assuming that's what had been used) applies to that. Same thing happens for many other Views.

So, an alternative possibility would be either to put both <item name="buttonStyle">...</item> and <item name="android:buttonStyle">...</item> into the style, so that Button and AppCompatButton can be combined, which would be quite a mess.

Somewhat better option would be to instantiate AppCompatButton for the APIs using AppCompat, but using the XML layout with just a single Button seems like the safest and most portable solution, so go for that, assuming you have no reason not to do that.

Body:
Using Theme.AppCompat in Gingerbread (API 10), programmatically added buttons do not match buttons added through XML. It works fine in all newer APIs, its only an issue with Gingerbread.  This image shows the issue.

Here is the code that adds the buttons:

for (int i = 0; i < btnFiles.length; i++) {
        btnFiles[i] = new Button(this);
        btnFiles[i].setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        btnFiles[i].setGravity(Gravity.CENTER);
        btnFiles[i].setId(100 + i);
        btnFiles[i].setText(fileList.get(i).replace(".xml", ""));
        btnFiles[i].setTag(fileList.get(i));
        registerForContextMenu(btnFiles[i]);
        btnFiles[i].setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                Continue(v);        //Start next activity when button is pressed
            }

        });

        l.addView(btnFiles[i]);
        setTitle(getString(R.string.title_activity_load_menu));
    }


问:
How to bring ALL data from a query in MySQL?
I want to write a query that can show the amount of purchases made in the month of June, grouped by city. So I wrote this query:

```<code>SELECT state, city, COUNT(*)
FROM address
JOIN person
JOIN purchase
WHERE purchase.person_FK = person.id
AND address.person_FK = person.id
AND MONTH(purchase.purchase_date) = 5
GROUP BY state, city
ORDER BY state, city;
</code>```

But this query doesn't return the cities that have no purchases in that month, and I want to show them. Can you help me?

答:
You will need to have a table that provides a listing of all cities you want to show (if you don't already have that). Then you join to the city table as well. Otherwise, your query has no idea which cities to show with a zero count. In addition, you will need to change your JOIN's to LEFT JOIN's

```<code>SELECT city.state, city.city, COUNT(*)
FROM address
LEFT JOIN person ON person.id = address.person_FK
LEFT JOIN purchase ON purchase.person_FK = person.id
LEFT JOIN city ON purchase.city = city.city
WHERE MONTH(purchase.purchase_date) = 5
GROUP BY address.state, address.city
ORDER BY address.state, address.city;
</code>```

Body:
I want to write a query that can show the amount of purchases made in the month of June, grouped by city. So I wrote this query:

SELECT state, city, COUNT(*)
FROM address
JOIN person
JOIN purchase
WHERE purchase.person_FK = person.id
AND address.person_FK = person.id
AND MONTH(purchase.purchase_date) = 5
GROUP BY state, city
ORDER BY state, city;

But this query doesn't return the cities that have no purchases in that month, and I want to show them. Can you help me?

Body:
You will need to have a table that provides a listing of all cities you want to show (if you don't already have that). Then you join to the city table as well. Otherwise, your query has no idea which cities to show with a zero count. In addition, you will need to change your JOIN's to LEFT JOIN's

SELECT city.state, city.city, COUNT(*)
FROM address
LEFT JOIN person ON person.id = address.person_FK
LEFT JOIN purchase ON purchase.person_FK = person.id
LEFT JOIN city ON purchase.city = city.city
WHERE MONTH(purchase.purchase_date) = 5
GROUP BY address.state, address.city
ORDER BY address.state, address.city;


问:
pyplot scatter plot marker size
In the pyplot document for scatter plot:

```<code>matplotlib.pyplot.scatter(x, y, s=20, c='b', marker='o', cmap=None, norm=None,
                          vmin=None, vmax=None, alpha=None, linewidths=None,
                          faceted=True, verts=None, hold=None, **kwargs)
</code>```

The marker size

s:
  size in points^2. It is a scalar or an array of the same length as x and y.

What kind of unit is points^2? What does it mean? Does s=100 mean 10 pixel x 10 pixel?

Basically I'm trying to make scatter plots with different marker sizes, and I want to figure out what does the s number mean.

答:
I also attempted to use 'scatter' initially for this purpose. After quite a bit of wasted time - I settled on the following solution.

```<code>import matplotlib.pyplot as plt
input_list = [{'x':100,'y':200,'radius':50, 'color':(0.1,0.2,0.3)}]
output_list = []
for point in input_list:
    output_list.append(plt.Circle((point['x'], point['y']), point['radius'], color=point['color'], fill=False))
ax = plt.gca(aspect='equal')
ax.cla()
ax.set_xlim((0, 1000))
ax.set_ylim((0, 1000))
for circle in output_list:
   ax.add_artist(circle)
</code>```

This is based on an answer to  this question

ContentLicense: CC BY-SA 4.0

Title: pyplot scatter plot marker size

Body:
In the pyplot document for scatter plot:

matplotlib.pyplot.scatter(x, y, s=20, c='b', marker='o', cmap=None, norm=None,
                          vmin=None, vmax=None, alpha=None, linewidths=None,
                          faceted=True, verts=None, hold=None, **kwargs)

The marker size

s:
  size in points^2. It is a scalar or an array of the same length as x and y.

What kind of unit is points^2? What does it mean? Does s=100 mean 10 pixel x 10 pixel?

Basically I'm trying to make scatter plots with different marker sizes, and I want to figure out what does the s number mean.

Body:
I also attempted to use 'scatter' initially for this purpose. After quite a bit of wasted time - I settled on the following solution.

import matplotlib.pyplot as plt
input_list = [{'x':100,'y':200,'radius':50, 'color':(0.1,0.2,0.3)}]
output_list = []
for point in input_list:
    output_list.append(plt.Circle((point['x'], point['y']), point['radius'], color=point['color'], fill=False))
ax = plt.gca(aspect='equal')
ax.cla()
ax.set_xlim((0, 1000))
ax.set_ylim((0, 1000))
for circle in output_list:
   ax.add_artist(circle)

This is based on an answer to  this question


问:
Find dup records with different extensions in SQL Server
I have a subscriptions table. Sample records:

```<code>  SUBS_ID    |   SUBS Name
     1       |   SC FORM 124
     2       |   SC FORM 124-R
</code>```

I need to find both the records, as the subscription name is exactly the same but just with an extension-R.

答:
Really bad throwaway code written straight here and untested, but...</p>

```<code>with cte As (Select Name, Id
From Subs
Where Name Not Like '%-R'
)
Select cte.Id, cte.Name, M.Name
From Subs As M
Join cte
On cte.Name + '-R' = M.Name
</code>```

Body:
I have a subscriptions table. Sample records:

  SUBS_ID    |   SUBS Name
     1       |   SC FORM 124
     2       |   SC FORM 124-R

I need to find both the records, as the subscription name is exactly the same but just with an extension-R.

Body:
Really bad throwaway code written straight here and untested, but...

with cte As (Select Name, Id
From Subs
Where Name Not Like '%-R'
)
Select cte.Id, cte.Name, M.Name
From Subs As M
Join cte
On cte.Name + '-R' = M.Name


问:
How to add onclick to an element using Javascript
I have an HTML button like so:

```<code><div class="row text-center">
   <button id="button1" type="submit" class="btn btn-primary">Submit</button>
</div>
</code>```

I'd like to add an onclick behavior for it via Javascript. It should call another function. I have tried this:

```<code>$("#button1").addEventListener("click", showAlert());
</code>```

However, the browser is complaining that $(...).addEventListener is not a function. What should I do instead?

答:
You could try the following:</p>

```<code>$( "#button1" ).bind( "click", showAlert);
</code>```

Body:
I have an HTML button like so:

   <button id="button1" type="submit" class="btn btn-primary">Submit</button>

I'd like to add an onclick behavior for it via Javascript. It should call another function. I have tried this:

$("#button1").addEventListener("click", showAlert());

However, the browser is complaining that $(...).addEventListener is not a function. What should I do instead?

Body:
You could try the following:

$( "#button1" ).bind( "click", showAlert);


问:
How to match URL with href in jQuery?
Using a list for navigation, I am looking for a clean way to apply the 'selected' class to a list item if the page URL (minus anything after the path) matches the href of the list item (minus anything after the path).

Example:

```<code><li><a href="/p/clothing/dresses/N-10635?ab=leftNav:dresses">dresses</a></li>
</code>```

Apply class "selected" to the list item when the page URL includes the /p/clothing/dresses/N-10635 part of the href.

So far, I achieved partial results using:

```<code>$('.leftNav li a').each(function(){
    if(window.location.href == this.href){
        $(this).parents('li').addClass('selected');
    }
});

<ul class="leftNav">
<li><a href="/p/clothing/dresses/N-10635?ab=leftNav:dresses">dresses</a></li>
<li><a href="/p/clothing/bottoms/capris/N-10764?ab=leftNav:capris">capris</a></li>
</ul>
</code>```

This, however, only applied the 'selected' class when the URL matched the href exactly - meaning it had to include the link-tracking variable as in the href (ie: ?ab=leftNav:dresses). Thinking of ways to match the "base" URL's and href's, I tried adding a data attribute to the list items to match the path only:

```<code>$('.leftNav li').each(function(){
    if(window.location.href == (this).data('left-nav-href')){
        $(this).addClass('selected');
    }
});

<ul class="leftNav">
<li data-left-nav-href="/p/clothing/dresses/N-10635"><a href="/p/clothing/dresses/N-10635?ab=leftNav:dresses">dresses</a></li>
<li data-left-nav-href="/p/clothing/bottoms/capris/N-10764"><a href="/p/clothing/bottoms/capris/N-10764?ab=leftNav:capris">capris</a></li>
</ul>
</code>```

I attempted this with variations of window.location including: window.location.href, window.location.href.pathname, window.location.href.indexOf, window.location.href.startsWith. With this not working, I searched for a way to match the path of the URL and href regardless of additional parameters or variables, but all I can find are ways to match URL's and href's specifically with strings or parameters. All instances I could find of matching only part of a URL or href use "split" RegEx which introduces another level of complexity that I don't think my use requires. Am I missing a simpler solution?

答:
you can use indexOf()

```<code>$(document).ready(function () {
    $('.leftNav li a').each(function(){
        var ThisHref = ($(this).attr('href').split('?'))[0];
        if(window.location.href.indexOf(ThisHref) > -1) {
            $(this).closest('li').addClass('selected');
        }
   });
});
</code>```

Example

var url = "http://www.website.com/index/p/clothing/bottoms/capris/N-10764?ab=leftNav:capris";

$(document).ready(function () {
    $('.leftNav li a').each(function(){
        var ThisHref = ($(this).attr('href').split('?'))[0];
        //alert(ThisHref);
        if(url.indexOf(ThisHref) > -1) {
            $(this).closest('li').addClass('selected');
        }
   });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.selected{
  background : red;
}</code>```

dresses

capris

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

<p><strong>Explanation</strong>:</p>

```$(document).ready(function () {  // run the code after document is ready
    $('.leftNav li a').each(function(){ // loop through  on

       // $(this).attr('href') will return href as string .. in your case will return something like '/p/clothing/dresses/N-10635?ab=leftNav:dresses'
       // using .split('?') to separating this href string by '?'
       // [0] get the first string after split (in this case it will be '/p/clothing/dresses/N-10635')
       // combine all of those steps on just one line
       var ThisHref = ($(this).attr('href').split('?'))[0];
       // get the 'window.location.href' which is return your url ..something like 'http://www.website.com/index/p/clothing/bottoms/capris/N-10764?ab=leftNav:capris'
       // try to find (first string after split) into (url/window.location.href)
       if(window.location.href.indexOf(ThisHref) > -1) { // if the url contains the first string after split addClass
          $(this).closest('li').addClass('selected');
       }
    });
});
```

you can read about .split() here

Note: in Vinas answer he use this.href which will return href as
  string .. in your case will return something like
  '/p/clothing/dresses/N-10635?ab=leftNav:dresses' and he use
  location.pathname
  and the code of indexOf() he try to find the location.pathname
  into the href

Additional: in your case both my answer and Vinas answer will work . that's not depending on code its depending on your case and what you're trying to do .. something like .hide(0) , .slideUp(0) , fadeOut(0) all of those hide the element with same effect .. So the code always determine by the case you working with .. May be my code or even Vinas's code won't work on another case

Title: How to match URL with href in jQuery?

Body:
Using a list for navigation, I am looking for a clean way to apply the 'selected' class to a list item if the page URL (minus anything after the path) matches the href of the list item (minus anything after the path).

Example:

dresses

Apply class "selected" to the list item when the page URL includes the /p/clothing/dresses/N-10635 part of the href.

So far, I achieved partial results using:

$('.leftNav li a').each(function(){
    if(window.location.href == this.href){
        $(this).parents('li').addClass('selected');
    }
});

dresses

capris

This, however, only applied the 'selected' class when the URL matched the href exactly - meaning it had to include the link-tracking variable as in the href (ie: ?ab=leftNav:dresses). Thinking of ways to match the "base" URL's and href's, I tried adding a data attribute to the list items to match the path only:

$('.leftNav li').each(function(){
    if(window.location.href == (this).data('left-nav-href')){
        $(this).addClass('selected');
    }
});

dresses

capris

I attempted this with variations of window.location including: window.location.href, window.location.href.pathname, window.location.href.indexOf, window.location.href.startsWith. With this not working, I searched for a way to match the path of the URL and href regardless of additional parameters or variables, but all I can find are ways to match URL's and href's specifically with strings or parameters. All instances I could find of matching only part of a URL or href use "split" RegEx which introduces another level of complexity that I don't think my use requires. Am I missing a simpler solution?

Body:
you can use indexOf()

$(document).ready(function () {
    $('.leftNav li a').each(function(){
        var ThisHref = ($(this).attr('href').split('?'))[0];
        if(window.location.href.indexOf(ThisHref) > -1) {
            $(this).closest('li').addClass('selected');
        }
   });
});

Example

var url = "http://www.website.com/index/p/clothing/bottoms/capris/N-10764?ab=leftNav:capris";

$(document).ready(function () {
    $('.leftNav li a').each(function(){
        var ThisHref = ($(this).attr('href').split('?'))[0];
        //alert(ThisHref);
        if(url.indexOf(ThisHref) > -1) {
            $(this).closest('li').addClass('selected');
        }
   });
});

.selected{
  background : red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="leftNav">
<li><a href="/p/clothing/dresses/N-10635?ab=leftNav:dresses">dresses</a></li>
<li><a href="/p/clothing/bottoms/capris/N-10764?ab=leftNav:capris">capris</a></li>
</ul>

Explanation:

$(document).ready(function () {  // run the code after document is ready
    $('.leftNav li a').each(function(){ // loop through <a> on <li>
       // $(this).attr('href') will return href as string .. in your case will return something like '/p/clothing/dresses/N-10635?ab=leftNav:dresses'
       // using .split('?') to separating this href string by '?'
       // [0] get the first string after split (in this case it will be '/p/clothing/dresses/N-10635')
       // combine all of those steps on just one line
       var ThisHref = ($(this).attr('href').split('?'))[0];
       // get the 'window.location.href' which is return your url ..something like 'http://www.website.com/index/p/clothing/bottoms/capris/N-10764?ab=leftNav:capris'
       // try to find (first string after split) into (url/window.location.href)
       if(window.location.href.indexOf(ThisHref) > -1) { // if the url contains the first string after split addClass
          $(this).closest('li').addClass('selected');
       }
    });
});

you can read about .split() here

Note: in Vinas answer he use this.href which will return href as
  string .. in your case will return something like
  '/p/clothing/dresses/N-10635?ab=leftNav:dresses' and he use
  location.pathname
  and the code of indexOf() he try to find the location.pathname
  into the href

Additional: in your case both my answer and Vinas answer will work . that's not depending on code its depending on your case and what you're trying to do .. something like .hide(0) , .slideUp(0) , fadeOut(0) all of those hide the element with same effect .. So the code always determine by the case you working with .. May be my code or even Vinas's code won't work on another case


问:
If we cant use 2D array of 10^9*10^9 then why are we able to instantiate it?
I can declare a 2D array of size 10^9*10^9 but when for a given test case which requires this size throws an exception of Exception in thread "main" java.lang.OutOfMemoryError: Java heap space and yes if it leads to complete memory usage then why are able to instantiate such arrays?

答:
java.lang.OutOfMemoryError is a run-time error. Exceptions and errors of this kind are reserved for situations when it is not possible for the compiler to decide if an operation is possible or not.

The decision to throw out-of-memory error is made by the running JVM at the time when you attempt to instantiate the object. If you run the same program on a system with more memory, or let your running JVM use more memory by increasing heap size (how?), the program may run to completion without throwing the error.


问:
How to get value datapicker in react toobox custom?
How can I get the value of datapicker in react toobox?
I am using custom components.

I am using 2 components first one is called InputDateCustom.js with the code below:

import DatePicker from 'react-toolbox/lib/date_picker/DatePicker';
import React, { Component } from 'react';

const datetime = new Date(2015, 10, 16);
datetime.setHours(17);
datetime.setMinutes(28);

export default  class InputDateCustomizado extends Component{
    state = {date2: datetime};

    handleChange = (item, value) => {
        console.log(item+" - "+value)
        this.setState({...this.state, [item]: value});
    };

    render() {
    return (

             <DatePicker
                label={this.props.label}
                locale={localeExample}
                name={this.props.name}
                required={this.props.required}
                onChange={this.handleChange.bind(this, 'date1')}
                value={this.state.date1}
             />

        );
    }
}
```
<p>Another component is called <code>Cadastro.js</code> that contains the following logic:</p>
<pre class="lang-js prettyprint-override"><code>constructor(props) {
    super(props);
    this.state = {msg: '', fim_vigencia:'', nome:''}
    this.setNome = this.setNome.bind(this)
    this.setFimVigencia  = this.setFimVigencia.bind(this)
}

setFimVigencia(evento){
  console.log("date")
   this.setState({fim_vigencia:evento.target.value});
}

InputDateCustomizado
    id="fim_vigencia"
    label="Fim"
    name="fim_vigencia"
    value    = {this.state.fim_vigencia}
    onSubmit = {this.setFimVigencia}
/>
</code>```

答:
Get the value in an onChange event or using the value prop. Doc examples: http://react-toolbox.com/#/components/date_picker

<DatePicker label='Birthdate' onChange={this.handleChange.bind(this, 'date1')} value={this.state.date1} />

You can get access to the value in the handleChange event allowing you to update your state with the currently selected date.

EDIT: Ah okay I think I understand what you are asking now. You have wrapped DatePicker with your own component and now you want to get the DatePicker value through the Cadastro.js component.

You need to create a method in the Cadastro.js that accepts state changes from the InputDateCustomizado component and then pass that function as a prop to the InputDateCustomizado component. In the InputDateCustomizado when the state changes, call the passed in function and it should update the state in the parent component. Then you will always have the datepicker value in the parent component.

It looks like you are almost there. You need to add an updateState function to the Cadastro.js component. In the InputDateCustomizado component handleChange event, you need to call this.props.updateState and pass in the new value.

In Cadastro.js

```<code>updateState = (data) => {
    this.setState({
        date: data.data //set your state here to the date
    })
}
</code>```

In InputDateCustomizado

```<code>    handleChange = (item, value) => {
        console.log(item+" - "+value)
        this.setState({...this.state, [item]: value});
        this.props.updateState(this.state);
    };
</code>```

Body:
How can I get the value of datapicker in react toobox?
I am using custom components.

I am using 2 components first one is called InputDateCustom.js with the code below:

import DatePicker from 'react-toolbox/lib/date_picker/DatePicker';
import React, { Component } from 'react';

const datetime = new Date(2015, 10, 16);
datetime.setHours(17);
datetime.setMinutes(28);

export default  class InputDateCustomizado extends Component{
    state = {date2: datetime};

    handleChange = (item, value) => {
        console.log(item+" - "+value)
        this.setState({...this.state, [item]: value});
    };

    render() {
    return (

             <DatePicker
                label={this.props.label}
                locale={localeExample}
                name={this.props.name}
                required={this.props.required}
                onChange={this.handleChange.bind(this, 'date1')}
                value={this.state.date1}
             />

        );
    }
}

Another component is called Cadastro.js that contains the following logic:

constructor(props) {
    super(props);
    this.state = {msg: '', fim_vigencia:'', nome:''}
    this.setNome = this.setNome.bind(this)
    this.setFimVigencia  = this.setFimVigencia.bind(this)
}

setFimVigencia(evento){
  console.log("date")
   this.setState({fim_vigencia:evento.target.value});
}

InputDateCustomizado
    id="fim_vigencia"
    label="Fim"
    name="fim_vigencia"
    value    = {this.state.fim_vigencia}
    onSubmit = {this.setFimVigencia}
/>

Body:
Get the value in an onChange event or using the value prop. Doc examples: http://react-toolbox.com/#/components/date_picker

<DatePicker label='Birthdate' onChange={this.handleChange.bind(this, 'date1')} value={this.state.date1} />

You can get access to the value in the handleChange event allowing you to update your state with the currently selected date.

EDIT: Ah okay I think I understand what you are asking now. You have wrapped DatePicker with your own component and now you want to get the DatePicker value through the Cadastro.js component.

You need to create a method in the Cadastro.js that accepts state changes from the InputDateCustomizado component and then pass that function as a prop to the InputDateCustomizado component. In the InputDateCustomizado when the state changes, call the passed in function and it should update the state in the parent component. Then you will always have the datepicker value in the parent component.

It looks like you are almost there. You need to add an updateState function to the Cadastro.js component. In the InputDateCustomizado component handleChange event, you need to call this.props.updateState and pass in the new value.

In Cadastro.js

updateState = (data) => {
    this.setState({
        date: data.data //set your state here to the date
    })
}

In InputDateCustomizado

    handleChange = (item, value) => {
        console.log(item+" - "+value)
        this.setState({...this.state, [item]: value});
        this.props.updateState(this.state);
    };


问:
Android granted runtime permissions to my app without asking
I'm trying to test the Runtime Permissions specifically for Android sdk > 23. But my app is being granted permissions automatically without asking.

Note : I'm using sdk version 24. Here's a snippet of code I'm using:

```<code>public void onCalendarClick(View view) {
    if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALENDAR) == PackageManager
            .PERMISSION_DENIED) {
       if(ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.WRITE_CALENDAR)) {
            //Display Explanation to the user
            //For granting permissions to the app.
        }
        else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_CALENDAR}, CALLBACK_CALENDAR);
        }
    }
}

@Override
public void onRequestPermissionsResult(int resultCode, String permission[], int grantResults[]) {
    if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        Toast toast;
        switch (resultCode) {
            case CALLBACK_CALENDAR : toast = Toast.makeText(this,"Calendar Permission Granted!!",Toast.LENGTH_LONG);
                toast.show(); break;
            //Other Cases
        }
    }
}
</code>```

When I click on Calendar Button, the onCalendarClick() method run, but without asking for any permission, the App directly displays Calendar Permission Granted!! toast. In the App's settings, there are though No Permissions Granted/Requested being displayed.

Am I missing something or doing it the wrong way? Thanks for any help.

答:
You are missing the order of the code. Check this:

```<code>@Override
public void onRequestPermissionsResult(int requestCode,
    String permissions[], int[] grantResults) {
    switch (requestCode) {
        case CALLBACK_CALENDAR: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // calendar-related task you need to do.

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}
</code>```

There is a little difference, you are asking if the permission is granted even before you know you are talking about CALENDAR permissions. So, you should first check if the current permission response is the one you want, and then check if the permission is granted.

Source: https://developer.android.com/training/permissions/requesting.html

Body:
I'm trying to test the Runtime Permissions specifically for Android sdk > 23. But my app is being granted permissions automatically without asking.

Note : I'm using sdk version 24. Here's a snippet of code I'm using:

public void onCalendarClick(View view) {
    if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALENDAR) == PackageManager
            .PERMISSION_DENIED) {
       if(ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.WRITE_CALENDAR)) {
            //Display Explanation to the user
            //For granting permissions to the app.
        }
        else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_CALENDAR}, CALLBACK_CALENDAR);
        }
    }
}

@Override
public void onRequestPermissionsResult(int resultCode, String permission[], int grantResults[]) {
    if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        Toast toast;
        switch (resultCode) {
            case CALLBACK_CALENDAR : toast = Toast.makeText(this,"Calendar Permission Granted!!",Toast.LENGTH_LONG);
                toast.show(); break;
            //Other Cases
        }
    }
}

When I click on Calendar Button, the onCalendarClick() method run, but without asking for any permission, the App directly displays Calendar Permission Granted!! toast. In the App's settings, there are though No Permissions Granted/Requested being displayed.

Am I missing something or doing it the wrong way? Thanks for any help.

Body:
You are missing the order of the code. Check this:

@Override
public void onRequestPermissionsResult(int requestCode,
    String permissions[], int[] grantResults) {
    switch (requestCode) {
        case CALLBACK_CALENDAR: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // calendar-related task you need to do.

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}

There is a little difference, you are asking if the permission is granted even before you know you are talking about CALENDAR permissions. So, you should first check if the current permission response is the one you want, and then check if the permission is granted.

Source: https://developer.android.com/training/permissions/requesting.html


问:
Headaches with configuring themed resources from c# (Windows Phone)
I have Windows Phone App and I want to have a different themed resources based on whether the user has a dark or light theme and which accent color they have chosen.

In my app initialize code I detect the users theme and accent color then load the appropriate Resource Dictionary, Dark, Light etc.  I add the Resource Dictionary to the  App.Current.Resources.MergedDictionaries collection.

The problem comes when I want to reference a value in the (dynamically loaded) from my App.Xaml. In the below example the key is "DefaultBackgroundImageOpacity".  For some reason the values in the ResourceDictionary that I load into the MergedDictionaries collection never get found when the App.Xaml parsing happens. I've played with loading the resources before I call InitializeComponent() and after. Neither seem to resolve the issue.

Any ideas?

```<code>// Simplified version of adding some xaml...
// Note I'm loading the key "DefaultBackgroundImageOpacity"
this.Resources.MergedDictionaries.Clear();

var myTestXaml = "<ResourceDictionary xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' xmlns:System='clr-namespace:System;assembly=mscorlib'> <System:Double x:Key='DefaultBackgroundImageOpacity'>0.2</System:Double></ResourceDictionary>";

this.Resources.MergedDictionaries.Add((ResourceDictionary)XamlReader.Load(myTestXaml));

// This always fails saying that the key "DefaultBackgroundImageOpacity"
// can not be foudnd - even though it was loaded just above
InitializeComponent();

// Phone-specific initialization
InitializePhoneApplication();
</code>```

答:
I suspect your App.Xaml contains something like this:-

```<code><Application.Resources>
   <ResourceDictionary>
       <ResourceDictionary.MergedDictionaries>
          <ResourceDictionary Source="/somedictionary.xaml" />
          ...
       </ResourceDictionary.MergedDictionaries>
       ...
  </ResourceDictionary>
</Application.Resources>
</code>```

If that is so then InitializeComponent will replace the default ResourceDictionary which you have manipulated in your code hence your changes to MergeDictionaries will not be present since that instance of a ResourceDictionary is no longer referenced.

If you are not setting up any MergedDictionaries in the App.Xaml then make sure you add resources directly to Applicaiton.Resources and are not creating an new instance of ResourceDictionary in the xaml.

Body:
I have Windows Phone App and I want to have a different themed resources based on whether the user has a dark or light theme and which accent color they have chosen.

In my app initialize code I detect the users theme and accent color then load the appropriate Resource Dictionary, Dark, Light etc.  I add the Resource Dictionary to the  App.Current.Resources.MergedDictionaries collection.

The problem comes when I want to reference a value in the (dynamically loaded) from my App.Xaml. In the below example the key is "DefaultBackgroundImageOpacity".  For some reason the values in the ResourceDictionary that I load into the MergedDictionaries collection never get found when the App.Xaml parsing happens. I've played with loading the resources before I call InitializeComponent() and after. Neither seem to resolve the issue.

Any ideas?

// Simplified version of adding some xaml...
// Note I'm loading the key "DefaultBackgroundImageOpacity"
this.Resources.MergedDictionaries.Clear();

var myTestXaml = "<ResourceDictionary xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' xmlns:System='clr-namespace:System;assembly=mscorlib'> <System:Double x:Key='DefaultBackgroundImageOpacity'>0.2</System:Double></ResourceDictionary>";

this.Resources.MergedDictionaries.Add((ResourceDictionary)XamlReader.Load(myTestXaml));

// This always fails saying that the key "DefaultBackgroundImageOpacity"
// can not be foudnd - even though it was loaded just above
InitializeComponent();

// Phone-specific initialization
InitializePhoneApplication();

Body:
I suspect your App.Xaml contains something like this:-

<Application.Resources>
   <ResourceDictionary>
       <ResourceDictionary.MergedDictionaries>
          <ResourceDictionary Source="/somedictionary.xaml" />
          ...
       </ResourceDictionary.MergedDictionaries>
       ...
  </ResourceDictionary>
</Application.Resources>

If that is so then InitializeComponent will replace the default ResourceDictionary which you have manipulated in your code hence your changes to MergeDictionaries will not be present since that instance of a ResourceDictionary is no longer referenced.

If you are not setting up any MergedDictionaries in the App.Xaml then make sure you add resources directly to Applicaiton.Resources and are not creating an new instance of ResourceDictionary in the xaml.


问:
Android sqlExcetion opening db : Permission denied JDBC
I try to create and use SQLite database in Android(API 25).
I provide permission in manifest. I think maybe there is problem with database Path. But I can`t solve this problem...

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permissio8n.READ_EXTERNAL_STORAGE"/>
</code>```

There is database opening code

```<code>String db = "jdbc:sqlite:" + Environment.getDataDirectory().getAbsolutePath() + "/MyDatabase.db";
        Class.forName("org.sqlite.JDBC");
</code>```

But there is some errors regarding permissions

```<code>06-05 21:05:35.962 3698-3698/com.example.user.app W/System.err: java.sql.SQLException: opening db: '/data/MyDatabase.db': Permission denied
06-05 21:05:35.962 3698-3698/com.example.user.app W/System.err:     at org.sqlite.core.CoreConnection.open(CoreConnection.java:203)
06-05 21:05:35.962 3698-3698/com.example.user.app W/System.err:     at org.sqlite.core.CoreConnection.<init>(CoreConnection.java:76)
06-05 21:05:35.962 3698-3698/com.example.user.app W/System.err:     at org.sqlite.jdbc3.JDBC3Connection.<init>(JDBC3Connection.java:24)
06-05 21:05:35.962 3698-3698/com.example.user.app W/System.err:     at org.sqlite.jdbc4.JDBC4Connection.<init>(JDBC4Connection.java:23)
06-05 21:05:35.962 3698-3698/com.example.user.app W/System.err:     at org.sqlite.SQLiteConnection.<init>(SQLiteConnection.java:45)
06-05 21:05:35.962 3698-3698/com.example.user.app W/System.err:     at org.sqlite.JDBC.createConnection(JDBC.java:114)
06-05 21:05:35.962 3698-3698/com.example.user.app W/System.err:     at org.sqlite.JDBC.connect(JDBC.java:88)
06-05 21:05:35.962 3698-3698/com.example.user.app W/System.err:     at java.sql.DriverManager.getConnection(DriverManager.java:569)
06-05 21:05:35.962 3698-3698/com.example.user.app W/System.err:     at java.sql.DriverManager.getConnection(DriverManager.java:237)
06-05 21:05:35.962 3698-3698/com.example.user.app W/System.err:     at com.example.user.app.DB.openDbConnection(DB.java:33)
06-05 21:05:35.962 3698-3698/com.example.user.app W/System.err:     at com.example.user.app.Helpers.isTableIsEmpty(Helpers.java:24)
06-05 21:05:35.962 3698-3698/com.example.user.app W/System.err:     at com.example.user.app.activity.BachelorITFCourses1.onCreate(BachelorITFCourses1.java:42)
06-05 21:05:35.962 3698-3698/com.example.user.app W/System.err:     at android.app.Activity.performCreate(Activity.java:6679)
06-05 21:05:35.962 3698-3698/com.example.user.app W/System.err:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
06-05 21:05:35.962 3698-3698/com.example.user.app W/System.err:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
06-05 21:05:35.963 3698-3698/com.example.user.app W/System.err:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
06-05 21:05:35.963 3698-3698/com.example.user.app W/System.err:     at android.app.ActivityThread.-wrap12(ActivityThread.java)
06-05 21:05:35.963 3698-3698/com.example.user.app W/System.err:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
06-05 21:05:35.963 3698-3698/com.example.user.app W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
06-05 21:05:35.963 3698-3698/com.example.user.app W/System.err:     at android.os.Looper.loop(Looper.java:154)
06-05 21:05:35.963 3698-3698/com.example.user.app W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6119)
06-05 21:05:35.963 3698-3698/com.example.user.app W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
06-05 21:05:35.963 3698-3698/com.example.user.app W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
06-05 21:05:35.963 3698-3698/com.example.user.app W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>```

P.S. I have special class DB for dtabase actions.

答:
The 8 in permission...READ is wrong right?
And are you requesting the permissions? I think writing and reading external storage is critical and has to be requested:
https://developer.android.com/training/permissions/requesting.html</p>

Body:
I try to create and use SQLite database in Android(API 25).
I provide permission in manifest. I think maybe there is problem with database Path. But I can`t solve this problem...

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permissio8n.READ_EXTERNAL_STORAGE"/>

There is database opening code

String db = "jdbc:sqlite:" + Environment.getDataDirectory().getAbsolutePath() + "/MyDatabase.db";
        Class.forName("org.sqlite.JDBC");

But there is some errors regarding permissions

06-05 21:05:35.962 3698-3698/com.example.user.app W/System.err: java.sql.SQLException: opening db: '/data/MyDatabase.db': Permission denied
06-05 21:05:35.962 3698-3698/com.example.user.app W/System.err:     at org.sqlite.core.CoreConnection.open(CoreConnection.java:203)
06-05 21:05:35.962 3698-3698/com.example.user.app W/System.err:     at org.sqlite.core.CoreConnection.<init>(CoreConnection.java:76)
06-05 21:05:35.962 3698-3698/com.example.user.app W/System.err:     at org.sqlite.jdbc3.JDBC3Connection.<init>(JDBC3Connection.java:24)
06-05 21:05:35.962 3698-3698/com.example.user.app W/System.err:     at org.sqlite.jdbc4.JDBC4Connection.<init>(JDBC4Connection.java:23)
06-05 21:05:35.962 3698-3698/com.example.user.app W/System.err:     at org.sqlite.SQLiteConnection.<init>(SQLiteConnection.java:45)
06-05 21:05:35.962 3698-3698/com.example.user.app W/System.err:     at org.sqlite.JDBC.createConnection(JDBC.java:114)
06-05 21:05:35.962 3698-3698/com.example.user.app W/System.err:     at org.sqlite.JDBC.connect(JDBC.java:88)
06-05 21:05:35.962 3698-3698/com.example.user.app W/System.err:     at java.sql.DriverManager.getConnection(DriverManager.java:569)
06-05 21:05:35.962 3698-3698/com.example.user.app W/System.err:     at java.sql.DriverManager.getConnection(DriverManager.java:237)
06-05 21:05:35.962 3698-3698/com.example.user.app W/System.err:     at com.example.user.app.DB.openDbConnection(DB.java:33)
06-05 21:05:35.962 3698-3698/com.example.user.app W/System.err:     at com.example.user.app.Helpers.isTableIsEmpty(Helpers.java:24)
06-05 21:05:35.962 3698-3698/com.example.user.app W/System.err:     at com.example.user.app.activity.BachelorITFCourses1.onCreate(BachelorITFCourses1.java:42)
06-05 21:05:35.962 3698-3698/com.example.user.app W/System.err:     at android.app.Activity.performCreate(Activity.java:6679)
06-05 21:05:35.962 3698-3698/com.example.user.app W/System.err:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
06-05 21:05:35.962 3698-3698/com.example.user.app W/System.err:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
06-05 21:05:35.963 3698-3698/com.example.user.app W/System.err:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
06-05 21:05:35.963 3698-3698/com.example.user.app W/System.err:     at android.app.ActivityThread.-wrap12(ActivityThread.java)
06-05 21:05:35.963 3698-3698/com.example.user.app W/System.err:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
06-05 21:05:35.963 3698-3698/com.example.user.app W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
06-05 21:05:35.963 3698-3698/com.example.user.app W/System.err:     at android.os.Looper.loop(Looper.java:154)
06-05 21:05:35.963 3698-3698/com.example.user.app W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6119)
06-05 21:05:35.963 3698-3698/com.example.user.app W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
06-05 21:05:35.963 3698-3698/com.example.user.app W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
06-05 21:05:35.963 3698-3698/com.example.user.app W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

P.S. I have special class DB for dtabase actions.


答:
With jQuery you can use .on():

```<code>$("#button1").on("click", showAlert);
</code>```

or

```<code>$("#button1").click(showAlert);
</code>```

addEventListener is a plain JavaScript method and you're trying to use it on a jQuery object. You could dereference the jQuery object using .get(0) and use it like:

```<code>$("#button1").get(0).addEventListener("click", showAlert);
</code>```

or

```<code>$("#button1")[0].addEventListener("click", showAlert);
</code>```

but there's really no reason.

Title: How to add onclick to an element using Javascript

Body:
With jQuery you can use .on():

$("#button1").on("click", showAlert);

or

$("#button1").click(showAlert);

addEventListener is a plain JavaScript method and you're trying to use it on a jQuery object. You could dereference the jQuery object using .get(0) and use it like:

$("#button1").get(0).addEventListener("click", showAlert);

or

$("#button1")[0].addEventListener("click", showAlert);

but there's really no reason.


问:
Retrieve Values From List In Entity Framework
There are two different models in my project: Movie and Actor.  Movie has a list of actors and Actor has a list of movies.  What I want to do is given a movie, get all of the actors, and then for each actor examine their movies acted in.

So, to get the information, I use:

```<code>var movie = context.Movies.Include("Cast.ActingCredits").FirstOrDefault(m => m.Key == key);
</code>```

The problem is that while the list ActingCredits is not null, there are no values in it.  Is there something that I am missing to load the values in the list?  ActingCredits is an ICollection<Movie>.

```<code> public class Actor : ModelBase
 {
     public ICollection<Movie> ActingCredits { get; set; }
 }

public class Movie : ModelBase
{
    public string Title { get; set; }
    public DateTime Year { get; set; }
    public Genre Genre { get; set; }
    public int RunTime { get; set; }
    public int Sales { get; set; }
    public ICollection<Actor> Cast { get; set; }
}
</code>```

EDIT: It has come to my attention that this may be wrong and is the cause of the issue.

```<code>protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Movie>().HasMany(p => p.Cast).WithMany();
        modelBuilder.Entity<Actor>().HasMany(m => m.ActingCredits).WithMany();
    }
</code>```

答:
I suggest adding this:

```<code>using System.Data.Entity;
</code>```

And then you can do the Include with strongly typed variables

```<code>var movie = context.Movies.Include(r => r.Cast)
</code>```

However what I think you really want is to use Select instead of Include?

```<code>var movie = context.Movies.Select(r => r.Cast).SelectMany(r => r.ActingCredits);
</code>```

Body:
There are two different models in my project: Movie and Actor.  Movie has a list of actors and Actor has a list of movies.  What I want to do is given a movie, get all of the actors, and then for each actor examine their movies acted in.

So, to get the information, I use:

var movie = context.Movies.Include("Cast.ActingCredits").FirstOrDefault(m => m.Key == key);

The problem is that while the list ActingCredits is not null, there are no values in it.  Is there something that I am missing to load the values in the list?  ActingCredits is an ICollection<Movie>.

 public class Actor : ModelBase
 {
     public ICollection<Movie> ActingCredits { get; set; }
 }

public class Movie : ModelBase
{
    public string Title { get; set; }
    public DateTime Year { get; set; }
    public Genre Genre { get; set; }
    public int RunTime { get; set; }
    public int Sales { get; set; }
    public ICollection<Actor> Cast { get; set; }
}

EDIT: It has come to my attention that this may be wrong and is the cause of the issue.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Movie>().HasMany(p => p.Cast).WithMany();
        modelBuilder.Entity<Actor>().HasMany(m => m.ActingCredits).WithMany();
    }

Body:
I suggest adding this:

using System.Data.Entity;

And then you can do the Include with strongly typed variables

var movie = context.Movies.Include(r => r.Cast)

However what I think you really want is to use Select instead of Include?

var movie = context.Movies.Select(r => r.Cast).SelectMany(r => r.ActingCredits);


问:
OWASP zap python api authentication
I'd like to start off by saying that I love this tool and the API is written in a very easy to follow way if you are familiar with Zap. The only troubles I've had is that I can't find much documentation on the python API, so I've gone off of the source code and verifying how it works against the app. I've been able to pull of scans and set contexts, but I can't seem to be able to correctly call anything from the authentication module. One of my problems, I believe, is that I'm not entirely sure the exact variables to use or their respective formats when calling the functions. below is some example code that I've scrapped together. Every use of the authentication functions below fail me. Even if someone were to look at this and tell me where to go or look to solve this problem myself, I would be very grateful.</p>

```<code>from zapv2 import ZAPv2

context = 'new_attack'

authmethodname = 'formBasedAuthentication'

authmethodconfigparams = "".join('loginUrl=someloginpage' 'loginRequestData=username%3D%7B%25user1%25%7D%26' 'password%3D%7B%25password%25%7D')

target = 'some target but I cant put more than 2 links in this question'

apikey = 'password'

zap = ZAPv2(apikey=apikey)

print zap.context.new_context('new_attack')

print zap.context.include_in_context(context, 'https://192.168.0.1.*')

print zap.context.context(context)

#anything below here gives me 'Missing Params' an error from zap
print zap.authentication.set_logged_in_indicator(context, loggedinindicatorregex='Logged in')

print zap.authentication.set_logged_out_indicator(context, 'Sorry, the username or password you entered is incorrect')

print zap.authentication.set_authentication_method(context, authmethodname, authmethodconfigparams)
</code>```

答:
A Dev member on the project was able to answer my question so I thought I would put it here as well. Essentially the authentication functions take the contextid and userid as parameters and I was passing the context name and user name. There are a few other mistakes that I interpreted from the source code as well. Hopefully this helps someone else who's starting out with the API as well, since there is not a lot of documentation.
from github page zaproxy; username thc202 - " </p>

```<code>from zapv2 import ZAPv2
context = 'new_attack'
authmethodname = 'formBasedAuthentication'
authmethodconfigparams = "".join('loginUrl=https://192.168.0.1/dologin.html' '&loginRequestData=username%3D%7B%25username%25%7D%26' 'password%3D%7B%25password%25%7D')
target = 'https://192.168.0.1'
apikey = 'password'
zap = ZAPv2(proxies={'http': 'http://127.0.0.1:8119', 'https': 'http://127.0.0.1:8119'}, apikey=apikey)

contextid = zap.context.new_context(context)
print contextid
print zap.context.include_in_context(context, 'https://192.168.0.1.*')

print zap.context.context(context)

print zap.authentication.set_authentication_method(contextid, authmethodname, authmethodconfigparams)
# The indicators should be set after setting the authentication method.
print zap.authentication.set_logged_in_indicator(contextid, loggedinindicatorregex='Logged in')
print zap.authentication.set_logged_out_indicator(contextid, 'Sorry, the username or password you entered is incorrect')

userid = zap.users.new_user(contextid, 'User 1')
print userid
print zap.users.set_authentication_credentials(contextid, userid, 'username=MyUserName&password=MySecretPassword')
print zap.users.set_user_enabled(contextid, userid, True)

print zap.spider.scan_as_user(contextid, userid, target)
</code>```

<p>"</p>

Title: OWASP zap python api authentication

Body:
I'd like to start off by saying that I love this tool and the API is written in a very easy to follow way if you are familiar with Zap. The only troubles I've had is that I can't find much documentation on the python API, so I've gone off of the source code and verifying how it works against the app. I've been able to pull of scans and set contexts, but I can't seem to be able to correctly call anything from the authentication module. One of my problems, I believe, is that I'm not entirely sure the exact variables to use or their respective formats when calling the functions. below is some example code that I've scrapped together. Every use of the authentication functions below fail me. Even if someone were to look at this and tell me where to go or look to solve this problem myself, I would be very grateful.

from zapv2 import ZAPv2

context = 'new_attack'

authmethodname = 'formBasedAuthentication'

authmethodconfigparams = "".join('loginUrl=someloginpage' 'loginRequestData=username%3D%7B%25user1%25%7D%26' 'password%3D%7B%25password%25%7D')

target = 'some target but I cant put more than 2 links in this question'

apikey = 'password'

zap = ZAPv2(apikey=apikey)

print zap.context.new_context('new_attack')

print zap.context.include_in_context(context, 'https://192.168.0.1.*')

print zap.context.context(context)

#anything below here gives me 'Missing Params' an error from zap
print zap.authentication.set_logged_in_indicator(context, loggedinindicatorregex='Logged in')

print zap.authentication.set_logged_out_indicator(context, 'Sorry, the username or password you entered is incorrect')

print zap.authentication.set_authentication_method(context, authmethodname, authmethodconfigparams)

Body:
A Dev member on the project was able to answer my question so I thought I would put it here as well. Essentially the authentication functions take the contextid and userid as parameters and I was passing the context name and user name. There are a few other mistakes that I interpreted from the source code as well. Hopefully this helps someone else who's starting out with the API as well, since there is not a lot of documentation.
from github page zaproxy; username thc202 - "

from zapv2 import ZAPv2
context = 'new_attack'
authmethodname = 'formBasedAuthentication'
authmethodconfigparams = "".join('loginUrl=https://192.168.0.1/dologin.html' '&loginRequestData=username%3D%7B%25username%25%7D%26' 'password%3D%7B%25password%25%7D')
target = 'https://192.168.0.1'
apikey = 'password'
zap = ZAPv2(proxies={'http': 'http://127.0.0.1:8119', 'https': 'http://127.0.0.1:8119'}, apikey=apikey)

contextid = zap.context.new_context(context)
print contextid
print zap.context.include_in_context(context, 'https://192.168.0.1.*')

print zap.context.context(context)

print zap.authentication.set_authentication_method(contextid, authmethodname, authmethodconfigparams)
# The indicators should be set after setting the authentication method.
print zap.authentication.set_logged_in_indicator(contextid, loggedinindicatorregex='Logged in')
print zap.authentication.set_logged_out_indicator(contextid, 'Sorry, the username or password you entered is incorrect')

userid = zap.users.new_user(contextid, 'User 1')
print userid
print zap.users.set_authentication_credentials(contextid, userid, 'username=MyUserName&password=MySecretPassword')
print zap.users.set_user_enabled(contextid, userid, True)

print zap.spider.scan_as_user(contextid, userid, target)

"


问:
SSIS to collect index usage
enter image description here
I am trying to collect the index usage for 1 server out of 70 of them. I declared 2 variables and did this but I m not able to move further. Please help.</p>

答:
Your connections are not dynamically set.
Please set the ServerName and DatabaseName dynamically using loop variable</p>

Title: SSIS to collect index usage


问:
Issue in Downloading File In Dropbox Version 2 Php Api
Hy Everyone,
I am using this code to download file from Dropbox Version 2 Php Api.But I don't get success yet in File downloading.Lets have a look on the script which i am using

```<code>function dbx_get_file($token, $in_filepath, $out_filepath)
{
$out_fp = fopen($out_filepath, 'w+');
if ($out_fp === FALSE)
    {
    echo "fopen error; can't open $out_filepath\n";
    return (NULL);
    }

$url = 'https://content.dropboxapi.com/2/files/download';

$header_array = array(
    'Authorization: Bearer ' . $token,
    'Content-Type:',
    'Dropbox-API-Arg: {"path":"' . $in_filepath . '"}'
);

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header_array);
curl_setopt($ch, CURLOPT_FILE, $out_fp);

$metadata = null;
curl_setopt($ch, CURLOPT_HEADERFUNCTION, function ($ch, $header) use (&$metadata)
    {
    $prefix = 'dropbox-api-result:';
    if (strtolower(substr($header, 0, strlen($prefix))) === $prefix)
        {
        $metadata = json_decode(substr($header, strlen($prefix)), true);
        }
    return strlen($header);
    }
);

$output = curl_exec($ch);

if ($output === FALSE)
    {
    echo "curl error: " . curl_error($ch);
    }

curl_close($ch);
fclose($out_fp);

return($metadata);
} // dbx_get_file()
</code>```

Calling this Function Here.

```<code>dbx_get_file("<Access-token>", '/Screenshot_1.png', 'Screenshot_1.png');
</code>```

I also replaced this "Access-token" with my Dropbox O-auth 2 Access Token.
Please suggest me the answer what i am doing wrong?Or is there any other way to download File from Dropbox using DropBox Version 2 PHP Api.
Thanks

答:
I have done it using Requests Library https://github.com/rmccue/Requests/
Here is my Code

```<code>include('Requests-master/library/Requests.php');
Requests::register_autoloader();
$token="Your Access Token is here";
$response =
Requests::post("https://content.dropboxapi.com/2/files/download", array(
'Authorization' => "Bearer ".$token,
'Dropbox-Api-Arg' => json_encode(array('path' => '/Screenshot_1.png')),
));
$fileContent = $response->body;
/*Download the file using file_put_contents method*/
file_put_contents("Screenshot_1.png",$fileContent);
$metadata = json_decode($response->headers['Dropbox-Api-Result'], true);
echo "File " . $metadata["name"] . " has the rev " . $metadata["rev"] . ".\n";
</code>```

File is downloading Successfully... :)

Body:
Hy Everyone,
I am using this code to download file from Dropbox Version 2 Php Api.But I don't get success yet in File downloading.Lets have a look on the script which i am using

function dbx_get_file($token, $in_filepath, $out_filepath)
{
$out_fp = fopen($out_filepath, 'w+');
if ($out_fp === FALSE)
    {
    echo "fopen error; can't open $out_filepath\n";
    return (NULL);
    }

$url = 'https://content.dropboxapi.com/2/files/download';

$header_array = array(
    'Authorization: Bearer ' . $token,
    'Content-Type:',
    'Dropbox-API-Arg: {"path":"' . $in_filepath . '"}'
);

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header_array);
curl_setopt($ch, CURLOPT_FILE, $out_fp);

$metadata = null;
curl_setopt($ch, CURLOPT_HEADERFUNCTION, function ($ch, $header) use (&$metadata)
    {
    $prefix = 'dropbox-api-result:';
    if (strtolower(substr($header, 0, strlen($prefix))) === $prefix)
        {
        $metadata = json_decode(substr($header, strlen($prefix)), true);
        }
    return strlen($header);
    }
);

$output = curl_exec($ch);

if ($output === FALSE)
    {
    echo "curl error: " . curl_error($ch);
    }

curl_close($ch);
fclose($out_fp);

return($metadata);
} // dbx_get_file()

Calling this Function Here.

dbx_get_file("<Access-token>", '/Screenshot_1.png', 'Screenshot_1.png');

I also replaced this "Access-token" with my Dropbox O-auth 2 Access Token.
Please suggest me the answer what i am doing wrong?Or is there any other way to download File from Dropbox using DropBox Version 2 PHP Api.
Thanks

Body:
I have done it using Requests Library https://github.com/rmccue/Requests/
Here is my Code

include('Requests-master/library/Requests.php');
Requests::register_autoloader();
$token="Your Access Token is here";
$response =
Requests::post("https://content.dropboxapi.com/2/files/download", array(
'Authorization' => "Bearer ".$token,
'Dropbox-Api-Arg' => json_encode(array('path' => '/Screenshot_1.png')),
));
$fileContent = $response->body;
/*Download the file using file_put_contents method*/
file_put_contents("Screenshot_1.png",$fileContent);
$metadata = json_decode($response->headers['Dropbox-Api-Result'], true);
echo "File " . $metadata["name"] . " has the rev " . $metadata["rev"] . ".\n";

File is downloading Successfully... :)


问:
PHP cannot create directory even though parent folder is 777
I understand the security implications of 777. This is just a troubleshooting measure.

Parent folder:

```<code>drwxrwxrwx.  3 web   www-data    22 Jun  5 11:04 library
</code>```

For good measure the immediate parent is also 777.

PHP is running as apache:

```<code>print shell_exec( 'whoami' );
</code>```

Returns apache which is a member of the www-data group:

```<code># groups apache
apache : apache www-data
</code>```

The mkdir command fails:

```<code>mkdir("/var/www/html/library/temp__9pa2spj13nkiatknv8odqrv3n0");
</code>```

Warning: mkdir(): Permission denied in /var/www/html/test.php

If I try to chdir to the directory first, I can getcwd() and it's correct. If I try to create the directory at that point if fails.

I'm out of ideas on what to test.

Here's my entire test script for good measure:

```<code><?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
print shell_exec( 'whoami' );
mkdir("/var/www/html/library/temp__9pa2spj13nkiatknv8odqrv3n0");
chdir("/var/www/html/library");
echo getcwd();
mkdir("temp__9pa2spj13nkiatknv8odqrv3n0");
</code>```

答:
By default SE Linux should be configured to block writes to any files by the web server (Apache). The httpd_sys_content_t shows that the directory is set to read only. You need to set it to read/write by using the httpd_sys_rw_content_t context. This can be done using the semanage tool. The command would look like this.

```<code>semanage fcontext -a httpd_sys_rw_content_t "/var/www/html/library(/.*)?"
</code>```

After you set that policy, you can apply it by doing...

```<code>restorecon -Rv /var/www/
</code>```

Body:
I understand the security implications of 777. This is just a troubleshooting measure.

Parent folder:

drwxrwxrwx.  3 web   www-data    22 Jun  5 11:04 library

For good measure the immediate parent is also 777.

PHP is running as apache:

print shell_exec( 'whoami' );

Returns apache which is a member of the www-data group:

# groups apache
apache : apache www-data

The mkdir command fails:

mkdir("/var/www/html/library/temp__9pa2spj13nkiatknv8odqrv3n0");

Warning: mkdir(): Permission denied in /var/www/html/test.php

If I try to chdir to the directory first, I can getcwd() and it's correct. If I try to create the directory at that point if fails.

I'm out of ideas on what to test.

Here's my entire test script for good measure:

<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
print shell_exec( 'whoami' );
mkdir("/var/www/html/library/temp__9pa2spj13nkiatknv8odqrv3n0");
chdir("/var/www/html/library");
echo getcwd();
mkdir("temp__9pa2spj13nkiatknv8odqrv3n0");

Body:
By default SE Linux should be configured to block writes to any files by the web server (Apache). The httpd_sys_content_t shows that the directory is set to read only. You need to set it to read/write by using the httpd_sys_rw_content_t context. This can be done using the semanage tool. The command would look like this.

semanage fcontext -a httpd_sys_rw_content_t "/var/www/html/library(/.*)?"

After you set that policy, you can apply it by doing...

restorecon -Rv /var/www/


问:
Is declaring an header file essential?
Is declaring an header file essential? This code:

```<code>main()
{
  int i=100;

  printf("%d\n",i);
}
</code>```

seems to work, the output that I get is 100. Even without using stdio.h header file. How is this possible?

答:
You don't have to include the header file. Its purpose is to let the compiler know all the information about stdio, but it's by no means necessary if your compiler is smart (or lazy).

You should include it because it's a good habit to get into - if you don't, then the compiler has no real way to know if you're breaking the rules, such as with:

```<code>int main (void) {
    puts (7);       // should be a string.
    return 0;
}
</code>```

which compiles without issue but rightly dumps core when running. Changing it to:

```<code>#include <stdio.h>
int main (void) {
    puts (7);
    return 0;
}
</code>```

will result in the compiler warning you with something like:

```<code>qq.c:3: warning: passing argument 1 of ‘puts’ makes pointer
                 from integer without a cast
</code>```

A decent compiler may warn you about this, such as gcc knowing about what printf is supposed to look like, even without the header:

```<code>qq.c:7: warning: incompatible implicit declaration of
                 built-in function ‘printf’
</code>```

Title: Is declaring an header file essential?

Body:
Is declaring an header file essential? This code:

main()
{
  int i=100;

  printf("%d\n",i);
}

seems to work, the output that I get is 100. Even without using stdio.h header file. How is this possible?

Body:
You don't have to include the header file. Its purpose is to let the compiler know all the information about stdio, but it's by no means necessary if your compiler is smart (or lazy).

You should include it because it's a good habit to get into - if you don't, then the compiler has no real way to know if you're breaking the rules, such as with:

int main (void) {
    puts (7);       // should be a string.
    return 0;
}

which compiles without issue but rightly dumps core when running. Changing it to:

#include <stdio.h>
int main (void) {
    puts (7);
    return 0;
}

will result in the compiler warning you with something like:

qq.c:3: warning: passing argument 1 of ‘puts’ makes pointer
                 from integer without a cast

A decent compiler may warn you about this, such as gcc knowing about what printf is supposed to look like, even without the header:

qq.c:7: warning: incompatible implicit declaration of
                 built-in function ‘printf’


问:
How to implement "Contact Us" view with a default Email destination address
I am trying to build up a Contact Us View in one iOS project,  What I am trying to do is:

Put a Text Viewin a view controller, which will capture and save users' writing.
If users press send button, the view controller will send the Email or message to customer service. How to implement this or any SDK recommended?

Thanks in advance.

答:
place the uitextview on the storyboard, create an IBoutlet for your textview, and implement the uitextview delegate methods.

You can then use "shouldChangeTextInRange" to determine if the user has pressed enter.

You are going to need to hit a backend API to then send off the data through your mail server. if you don't have a backend server where you can code up a seamless email sending program, you can open up the mail app by using something like this:

```<code>let email = "foo@bar.com"
if let url = URL(string: "mailto:\(email)") {
     UIApplication.shared.open(url)
}
</code>```

Body:
place the uitextview on the storyboard, create an IBoutlet for your textview, and implement the uitextview delegate methods.

You can then use "shouldChangeTextInRange" to determine if the user has pressed enter.

You are going to need to hit a backend API to then send off the data through your mail server. if you don't have a backend server where you can code up a seamless email sending program, you can open up the mail app by using something like this:

let email = "foo@bar.com"
if let url = URL(string: "mailto:\(email)") {
     UIApplication.shared.open(url)
}


问:
How to bring ALL data from a query in MySQL?
I want to write a query that can show the amount of purchases made in the month of June, grouped by city. So I wrote this query:

```<code>SELECT state, city, COUNT(*)
FROM address
JOIN person
JOIN purchase
WHERE purchase.person_FK = person.id
AND address.person_FK = person.id
AND MONTH(purchase.purchase_date) = 5
GROUP BY state, city
ORDER BY state, city;
</code>```

But this query doesn't return the cities that have no purchases in that month, and I want to show them. Can you help me?

答:
You need a city table with all the cities, then do a LEFT JOIN.

And put the JOIN condition on the ON section not the WHERE

```<code>SELECT Cities.state, Cities.city, COUNT(*)
FROM  Cities
LEFT JOIN Purchase
  ON Cities.city = Purchase.city
 AND Cities.state = Cities.state
JOIN person
  ON purchase.person_FK = person.id
 AND MONTH(purchase.purchase_date) = 5
JOIN address
  ON address.person_FK = person.id
GROUP BY Cities.state, Cities.city
ORDER BY Citiesstate, Cities.city;
</code>```

Body:
I want to write a query that can show the amount of purchases made in the month of June, grouped by city. So I wrote this query:

SELECT state, city, COUNT(*)
FROM address
JOIN person
JOIN purchase
WHERE purchase.person_FK = person.id
AND address.person_FK = person.id
AND MONTH(purchase.purchase_date) = 5
GROUP BY state, city
ORDER BY state, city;

But this query doesn't return the cities that have no purchases in that month, and I want to show them. Can you help me?

Body:
You need a city table with all the cities, then do a LEFT JOIN.

And put the JOIN condition on the ON section not the WHERE

SELECT Cities.state, Cities.city, COUNT(*)
FROM  Cities
LEFT JOIN Purchase
  ON Cities.city = Purchase.city
 AND Cities.state = Cities.state
JOIN person
  ON purchase.person_FK = person.id
 AND MONTH(purchase.purchase_date) = 5
JOIN address
  ON address.person_FK = person.id
GROUP BY Cities.state, Cities.city
ORDER BY Citiesstate, Cities.city;


问:
How to apply generic expression-trees code that works well on integers, to enums (e.g. how to make Expression.PostIncrementAssign() work on enums?)?
I'm trying to create an extension method to do this:

```<code>enum AlphaBet { A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z }

IEnumerable<AlphaBet> rangeCtoG = AlphaBet.C.RangeToInc(AlphaBet.G);
</code>```

But this won't compile (as TEnum is generic):

```<code>public static IEnumerable<TEnum> RangeToInc<TEnum>(this TEnum from, TEnum to)
    where TEnum : struct, IComparable, IFormattable, IConvertible //
{
    for (; from <= to; from++)
        yield return from;
}
</code>```

So I turned to expressions:

```<code>public delegate void MyFunc<T>(ref T arg); // allow PostIncrementAssign to change the input parameter

public static IEnumerable<TEnum> RangeToInc<TEnum>(this TEnum from, TEnum to)
    where TEnum : struct, IComparable, IFormattable, IConvertible //
{
    var fromRefParamExpr = Expression.Parameter(typeof(TEnum).MakeByRefType(), "fromParam");
    var incrementExpr = Expression.PostIncrementAssign(fromRefParamExpr);
    var increment = Expression.Lambda<MyFunc<TEnum>>(incrementExpr, fromRefParamExpr).Compile();

    var fromParamExpr = Expression.Parameter(typeof(TEnum), "fromParam");
    var toParamExpr = Expression.Parameter(typeof(TEnum), "toParam");
    var lessThanOrEqualExpr = Expression.LessThanOrEqual(fromParamExpr, toParamExpr);
    var lessThanOrEqual = Expression.Lambda<Func<TEnum, TEnum, bool>>(
        lessThanOrEqualExpr, toParamExpr, fromParamExpr).Compile();

    for (; lessThanOrEqual(to, from); increment(ref from))
        yield return from;
}
</code>```

It works great with integers, but not with enums: the line Expression.PostIncrementAssign(fromRefParamExpr) fails with exception:

```<code>System.InvalidOperationException:
    'The unary operator PostIncrementAssign is not defined for the type
    '...+AlphaBet'.'
</code>```

Which is quite suprising - isn't an enum a numeric type? what am I supposed to do? cast back and forth enum ⇔ int?

答:
Sadly you'll have to cast back and forth... What you can do is cache the resulting expression tree and use the internal .NET runtime for this:

```<code>public static class EnumerableHelper
{
    public static IEnumerable<TEnum> RangeToInc<TEnum>(this TEnum from, TEnum to)
        where TEnum : struct, IComparable, IFormattable, IConvertible
    {
        var cmp = Comparer<TEnum>.Default;

        while (cmp.Compare(from, to) <= 0)
        {
            yield return from;
            from = EnumerableHelperImpl<TEnum>.Increment(from);
        }
    }

    private static class EnumerableHelperImpl<TEnum>
    {
        public static readonly Func<TEnum, TEnum> Increment;

        static EnumerableHelperImpl()
        {
            var par = Expression.Parameter(typeof(TEnum));

            Expression body = typeof(TEnum).IsEnum ?
                Expression.Convert(Expression.Increment(Expression.Convert(par, Enum.GetUnderlyingType(typeof(TEnum)))), typeof(TEnum)) :
                Expression.Increment(par);

            Increment = Expression.Lambda<Func<TEnum, TEnum>>(body, par).Compile();
        }
    }
}
</code>```

and then:

```<code>IEnumerable<AlphaBet> rangeCtoG = AlphaBet.C.RangeToInc(AlphaBet.G);
IEnumerable<int> range2 = 5.RangeToInc(8);
</code>```

Note that you can even create ranges betweeen int and not only between enum. The "trick" here is to use a private EnumerableHelperImpl<TEnum>, that will be different depending on the TEnum. The .NET will generate those EnumerableHelperImpl<TEnum> based on the TEnum types used and will cache them. The code will work even with non-int enums.

Body:
I'm trying to create an extension method to do this:

enum AlphaBet { A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z }

IEnumerable<AlphaBet> rangeCtoG = AlphaBet.C.RangeToInc(AlphaBet.G);

But this won't compile (as TEnum is generic):

public static IEnumerable<TEnum> RangeToInc<TEnum>(this TEnum from, TEnum to)
    where TEnum : struct, IComparable, IFormattable, IConvertible //
{
    for (; from <= to; from++)
        yield return from;
}

So I turned to expressions:

public delegate void MyFunc<T>(ref T arg); // allow PostIncrementAssign to change the input parameter

public static IEnumerable<TEnum> RangeToInc<TEnum>(this TEnum from, TEnum to)
    where TEnum : struct, IComparable, IFormattable, IConvertible //
{
    var fromRefParamExpr = Expression.Parameter(typeof(TEnum).MakeByRefType(), "fromParam");
    var incrementExpr = Expression.PostIncrementAssign(fromRefParamExpr);
    var increment = Expression.Lambda<MyFunc<TEnum>>(incrementExpr, fromRefParamExpr).Compile();

    var fromParamExpr = Expression.Parameter(typeof(TEnum), "fromParam");
    var toParamExpr = Expression.Parameter(typeof(TEnum), "toParam");
    var lessThanOrEqualExpr = Expression.LessThanOrEqual(fromParamExpr, toParamExpr);
    var lessThanOrEqual = Expression.Lambda<Func<TEnum, TEnum, bool>>(
        lessThanOrEqualExpr, toParamExpr, fromParamExpr).Compile();

    for (; lessThanOrEqual(to, from); increment(ref from))
        yield return from;
}

It works great with integers, but not with enums: the line Expression.PostIncrementAssign(fromRefParamExpr) fails with exception:

System.InvalidOperationException:
    'The unary operator PostIncrementAssign is not defined for the type
    '...+AlphaBet'.'

Which is quite suprising - isn't an enum a numeric type? what am I supposed to do? cast back and forth enum ⇔ int?

Body:
Sadly you'll have to cast back and forth... What you can do is cache the resulting expression tree and use the internal .NET runtime for this:

public static class EnumerableHelper
{
    public static IEnumerable<TEnum> RangeToInc<TEnum>(this TEnum from, TEnum to)
        where TEnum : struct, IComparable, IFormattable, IConvertible
    {
        var cmp = Comparer<TEnum>.Default;

        while (cmp.Compare(from, to) <= 0)
        {
            yield return from;
            from = EnumerableHelperImpl<TEnum>.Increment(from);
        }
    }

    private static class EnumerableHelperImpl<TEnum>
    {
        public static readonly Func<TEnum, TEnum> Increment;

        static EnumerableHelperImpl()
        {
            var par = Expression.Parameter(typeof(TEnum));

            Expression body = typeof(TEnum).IsEnum ?
                Expression.Convert(Expression.Increment(Expression.Convert(par, Enum.GetUnderlyingType(typeof(TEnum)))), typeof(TEnum)) :
                Expression.Increment(par);

            Increment = Expression.Lambda<Func<TEnum, TEnum>>(body, par).Compile();
        }
    }
}

and then:

IEnumerable<AlphaBet> rangeCtoG = AlphaBet.C.RangeToInc(AlphaBet.G);
IEnumerable<int> range2 = 5.RangeToInc(8);

Note that you can even create ranges betweeen int and not only between enum. The "trick" here is to use a private EnumerableHelperImpl<TEnum>, that will be different depending on the TEnum. The .NET will generate those EnumerableHelperImpl<TEnum> based on the TEnum types used and will cache them. The code will work even with non-int enums.


问:
Overlapping scrollviews block touch events
needs some advice on how to achieve an effect in Appcelerator Titanium.  I need to create an effect that has two scrollviews, on top of each other both that receives touch events.

Seems that under iOS and Android native programming you can tell the OS not to gobble up the touch events.

I need a kind of see-through effect with both layers receiving the touch events? Any ideas?

答:
Answered my own question after messing around...

One scroll view, composite layout of child elements, dynamically fix position of child elements you want other elements to scroll over (making sure you either add them in order or dynamically change z-order) which still retains the interactivity of the elements within the scroll view.

Check this link, This will be helpful: https://developer.android.com/training/gestures/viewgroup.html


问:
How to update LiveData of a ViewModel from background service and Update UI
Recently I am exploring Android Architecture, that has been introduced recently by google. From the Documentation I have found this:

```<code>public class MyViewModel extends ViewModel {
    private MutableLiveData<List<User>> users;
    public LiveData<List<User>> getUsers() {
        if (users == null) {
            users = new MutableLiveData<List<Users>>();
            loadUsers();
        }
        return users;
    }

    private void loadUsers() {
        // do async operation to fetch users
    }
}
</code>```

the activity can access this list as follows:

```<code>public class MyActivity extends AppCompatActivity {
    public void onCreate(Bundle savedInstanceState) {
        MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);
        model.getUsers().observe(this, users -> {
            // update UI
        });
    }
}
</code>```

My Question is, I am going to do this:

in the loadUsers() function I am fetching the data asynchronously where I will first check the database(Room) for that data

If I do not get the data there I will make an API call to fetch the data from the web server.

I will insert the fetched data into the database(Room) and update the UI according the data.

What is the recommended approach to do this?

If I start a Service to call the API from the loadUsers() method, how can I update the MutableLiveData<List<User>> users variable from that Service?

答:
Take a look at the Android architecture guide that accompanies the new architecture modules like LiveData and ViewModel. They discuss this exact issue in depth.

In their examples they don't put it in a service. Take a look at how they solve it using a "repository" module and Retrofit. The addendums at the bottom include more complete examples including communicating network state, reporting errors, etc.

Body:
Recently I am exploring Android Architecture, that has been introduced recently by google. From the Documentation I have found this:

public class MyViewModel extends ViewModel {
    private MutableLiveData<List<User>> users;
    public LiveData<List<User>> getUsers() {
        if (users == null) {
            users = new MutableLiveData<List<Users>>();
            loadUsers();
        }
        return users;
    }

    private void loadUsers() {
        // do async operation to fetch users
    }
}

the activity can access this list as follows:

public class MyActivity extends AppCompatActivity {
    public void onCreate(Bundle savedInstanceState) {
        MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);
        model.getUsers().observe(this, users -> {
            // update UI
        });
    }
}

My Question is, I am going to do this:

in the loadUsers() function I am fetching the data asynchronously where I will first check the database(Room) for that data

If I do not get the data there I will make an API call to fetch the data from the web server.

I will insert the fetched data into the database(Room) and update the UI according the data.

What is the recommended approach to do this?

If I start a Service to call the API from the loadUsers() method, how can I update the MutableLiveData<List<User>> users variable from that Service?