text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Incanter for real world statistical projects
I'm interested in statistical computing. R is a leader platform obviously but what about Incanter?
Incanter is at the top of my list since I'm a Clojure and JVM guy.
Do you have any real world projects with Incanter? Is it a proven platform or I have to fall back to R?
What are the advantages of R over Incanter? What I'm going to miss?
A:
Major advantages of R are (well, apart that it's the industry standard in a way, which is something that should never be underestimated) its large number of libraries and its large and rather active community which again contributes to the number of libraries.
Also, it has good plotting capabilities.
Incanter (note; I've not used neither R nor Incanter for prolonged periods of time) is in a way a port of R in Clojure. Some prefer coding in Clojure so to them this will be the obvious advantage, but the last time I saw it it seemed rather immature. Its community is also much smaller, and although it may grow, it's still marginal nowadays.
If you want to go mainstream along the path of least resistance, I'd stick with R. I've never seen any even mid size projects done with Incanter (although, I should repeat, I was not in the business where statistics were primary occupation).
| {
"pile_set_name": "StackExchange"
} |
Q:
Using logarithmic differentiation to find the derivative of the function $y=x^{x+1}(x+1)^x$
Using logarithmic differentiation, find the derivative of the function $y=x^{x+1}(x+1)^x$.
I knew one may begin with this step.
$$\ln(y)=\ln(x^{x+1})+\ln(x+1)^x$$
But how to differentiate this?
A:
$ln(y)=ln(x^{x+1})+ln((x+1)^x)=(x+1)ln(x)+xln(x+1)$ by logarithm rules. Then you can just use the product rule to finish it up
| {
"pile_set_name": "StackExchange"
} |
Q:
Installing rails is failing: Unable to download data
I'm trying to install rails on a new machine and am running to the following command issue:
gem install rails
ERROR: Could not find a valid gem 'rails' (>= 0), here is why:
Unable to download data from http://gems.rubyforge.org/ - Errno::ETIMEDOUT: Operation timed out - connect(2) (http://gems.rubyforge.org/latest_specs.4.8.gz)
A:
rubyforge.org was deprecated in favor of rubygems.org -- quite a while ago, this is nothing new. But you are stuck with an old source, i was too, just updated.
You probably want to do the following, first remove rubyforge.org as a source:
gem source -r http://gems.rubyforge.org
Next add rubygems.org as a source
gem source -a http://rubygems.org
Now do a gem update:
gem update --system
Check to see which version of gem you are running:
gem -v
Should be on 2.0.6 (or greater).
Good to go!
A:
RubyForge was down today. :)
See here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Swift Google Places in a tableview
what I am trying to do is create a tableView that has the name of a bunch of different restaurants taken from Google's place api. Google recommends getting the place_id, which I am able to do, and use that place_id to get the name of the restaurants, which I am able to do. The problem that I am having is that to put the name of the restaurant into a tableView I will need an array that is outside the function, so I append the place names that I got using the place_id to the array outside the function. All is good here and it compiles with no error, it is just when the app loads that the tableView is blank, and I check using a print statement and it states that the array is empty.
This is the code:
import UIKit
import Firebase
import GooglePlaces
import GoogleMaps
import Firebase
import Alamofire
import SwiftyJSON
class MainViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var placesClient: GMSPlacesClient!
var arrayedName = [String]()
var http = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=41.392788,-73.450949&radius=5000&type=restaurant&key=KEY_HERE"
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
placesClient = GMSPlacesClient.shared()
other()
}
func other() {
Alamofire.request(http).responseJSON { (responseData) -> Void in
if ((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
let results = swiftyJsonVar["results"].arrayValue
for result in results {
let id = result["place_id"].stringValue
var arrayed = [String]()
arrayed.append(id)
for i in 0..<arrayed.count {
let array = arrayed[i]
self.placesClient.lookUpPlaceID(array, callback: { (place, error) -> Void in
if let error = error {
print("Lookup place id query error: \(error.localizedDescription)")
return
}
guard let place = place else {
print("No place details for \(arrayed[i])")
return
}
let placeName = place.name
self.arrayedName.append(placeName)
})
}
}
}
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayedName.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! LocationTableViewCell
cell.nameLbl.text = "\(arrayedName[indexPath.row])"
return cell
}
}
No matter what I do I just can't get the array to be populated. I checked the info plist, and everything I need is there, but I think that the problem is in the other() function. Another thing that I have tried is to recreate the code from the other() function and add it to the cellForRowAt, but it just crashes. That looked like this:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! LocationTableViewCell
Alamofire.request(http).responseJSON { (responseData) -> Void in
if ((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
let results = swiftyJsonVar["results"].arrayValue
for result in results {
let id = result["place_id"].stringValue
var arrayed = [String]()
arrayed.append(id)
for i in 0..<arrayed.count {
let array = arrayed[i]
self.placesClient.lookUpPlaceID(array, callback: { (place, error) -> Void in
if let error = error {
print("Lookup place id query error: \(error.localizedDescription)")
return
}
guard let place = place else {
print("No place details for \(arrayed[i])")
return
}
let placeName = place.name
var arrayName = [String]()
arrayName.append(placeName)
cell.nameLbl.text = "\(arrayName[indexPath.row])"
})
}
}
}
}
return cell
}
I am out of ideas on what to do. If there is anyone who can help, I am thankful. If there is anything else that I can answer please ask.
Thank you
A:
Initially the arrayedName is empty so you will not see any item in the tableView. But once all the places name are appended to this array you need to reload the tableView to see the new data. You should keep the cellForRowAt same as you tried in the first attempt without any API call. I have updated the other method as below so now it should work
func other() {
Alamofire.request(http).responseJSON { (responseData) -> Void in
if ((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
let results = swiftyJsonVar["results"].arrayValue
let dispatchGroup = DispatchGroup()
for result in results {
let id = result["place_id"].stringValue
dispatchGroup.enter()
self.placesClient.lookUpPlaceID(id, callback: { (place, error) -> Void in
if let error = error {
print("Lookup place id query error: \(error.localizedDescription)")
dispatchGroup.leave()
return
}
guard let place = place else {
print("No place details for \(id)")
dispatchGroup.leave()
return
}
self.arrayedName.append(place.name)
dispatchGroup.leave()
})
}
dispatchGroup.notify(queue: DispatchQueue.global()) {
self.tableView.reloadData()
}
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Are difficult code tests when applying for jobs the norm?
I just did the online tech test for Lionhead and found it a bit defeating. There were questions that required you to work out the answers to recursive algorithms that accepted arrays as arguments and made multiple calls each run through, thus splitting off into exponentially more versions. This all had to be done on paper or in your head.
There were also questions that asked you to evaluate the efficiency of theoretical algorithms and say what Big O notation you think would best describe their scaling, something that I have never been taught or learned.
There were 27 such questions. Is this usual? Is this the standard of entry level games programming? I mean, I've written 3D games, but I found this really hard.
EDIT - I have actually done another tech test for another company now which was considerably easier. I had to write various different linked list algorithms and write a routine in sudo code for how I would mathematically calculate a bot's sight given a world up vector and a forward vector.
A:
It is worth noting that there are no industry standards for either the test material or the evaluation thereof, so your mileage may (read: will) vary wildly from that described by the answers here (my own included).
That said, what you describe doesn't sound like an uncommon test structure to me (the number of questions is a bit higher than any test I've ever taken or administered, but that's about it). Both the topics you specifically called out -- complex recursion and Big-O notation -- are topics that are typical of a solid computer science education and can be extremely useful in game development. Their presence on a test is a good way to measure if you are familiar with them, or probe for potential areas of discussion in an in-person interview.
Remember that, as others have noted, a test for a job isn't necessarily like a test in school. Doing poorly may not immediately disqualify you for further interviews. Code tests are just another screening and evaluation metric to help see where you stand in terms of your technical ability and if that would be an appropriate fit for the available position or positions.
Above all, don't be discouraged if you feel you didn't do well. Look at is as an opportunity to grow and perhaps try again later. If you're eventually told that you didn't do well enough on the test, it's worth asking for clarification (sometimes you won't get it, but it can't really hurt to ask) so you know where specifically to focus your continuing education.
A:
This is almost standard in even the smaller software studios now. I haven't applied to any game studios but it's easy to assume they would be at the same level of difficulty if not more in the interview.
They want to know exactly what you said. If you've ever been taught that or not. If you didn't get a degree in computer science or have significant experience in game development, you may find it very hard to get a job at a studio that big, or even smaller ones.
These questions are geared for the entry level by the way. They need something to compare you against with all of the other applicants. If you don't know algorithm efficiency, they are assuming you are less qualified than the entry levels that do, as most CS grads know this stuff well. I use "you" in the general term to mean any applicant.
A:
A lot of games companies have tests that have questions as difficult as that. Not separate ones for intermediate / advanced levels. You will probably find that they would be expecting a low percentage correct for an entry level programmer, say 40% or something.
Was there a lot easier questions? And even with the harder ones did you attempt them and show how you worked it out, etc.? It is more for them to gauge what you do actually know and your aptitude when trying to attempt to answer them.
At least with an online test you have the advantage of being able to look up things you have forgotten, etc., which is probably another reason for them to make it more difficult.
Do you have a copy of it you could message me by any chance? I would be interested in seeing it.
| {
"pile_set_name": "StackExchange"
} |
Q:
making service available in ngRoute
This code is from the angularjs TodoMVC. You can see resolve object of the routeConfig that it fetches the todos from localStorage (if localStorage is used). The localStorage code is created in an service in another file todoStorage.js. My question is, how is that service (or how is that code in general) available in this config for the fetch of the todo records? Don't I have to make available the service somehow for the code below to use it?
angular.module('todomvc', ['ngRoute'])
.config(function ($routeProvider) {
'use strict';
var routeConfig = {
controller: 'TodoCtrl',
templateUrl: 'todomvc-index.html',
resolve: {
store: function (todoStorage) {
// Get the correct module (API or localStorage).
return todoStorage.then(function (module) {
module.get(); // Fetch the todo records in the background.
return module;
});
}
}
};
A:
The resolve property is a hash/dictionary of key value pairs.
The key is the eventual name of the value that will be available for injection. The value can be an injectible function that Angular will automatically pass dependencies into.
So when you see this code:
store: function (todoStorage) { ... }
Angular will automatically infer the 'todoStorage' service from the parameter name and then inject it automatically. And of course it supports array notation as well:
store: ['todoStorage', function (todoStorage) { ... }]
In Angular pretty much anything can be dependency injected.
| {
"pile_set_name": "StackExchange"
} |
Q:
ListDefinition and ListInstance failures with custom content type
In VisualStudio 2012 I have a custom content type that I want to use in a ListInstance. When I create a ListDefinition or ListInstance using VisualStudio and add my ContentType I get feature activation errors. Yet if I create a generic ListInstance it functions correctly and if I add my ContentType through the web interface to the ANY list it works fine too.
What do I need to do to get the ListDefinition and ListInstance to function correctly.
The content type is based on an Item and has several custom SiteColumns.
My SiteColumns are in Feature1
My ContentTypes are in Feature2
My ListDefinition and ListInstances are in Feature3
Features are scoped to web.
Features are set up with the correct dependencies.
Features are shown in the correct order in the package.
Content Type
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<!-- Parent ContentType: Item (0x01) -->
<ContentType ID="0x0100BE5BB437E28E4931960FD3AB89883799" Name="My Concept" Group="My Content Types" Description="My Content Type" Inherits="TRUE" Version="0">
<FieldRefs>
<FieldRef ID="{600c95a5-c81c-4c2d-a1b7-1b90c1fa6537}" DisplayName="Concept ID" Required="FALSE" Name="ConceptID" ShowInEditForm="False" ShowInNewForm="False" />
<FieldRef ID="{0b8e6761-062c-446b-9bf2-28b0c238684d}" DisplayName="Concept Description" Required="True" Name="Project Description" />
<FieldRef ID="{99719dc5-4a0a-4b04-b2f8-353630a0d271}" DisplayName="Proposed Project Manager" Required="TRUE" Name="Project Manager" />
<FieldRef ID="{a24d0da2-8329-4da3-9245-251d167626b6}" DisplayName="Proposed Project Sponsor" Required="TRUE" Name="Project Sponsor" />
<FieldRef ID="{49e5c95d-24bb-4575-9450-d6489cc825f7}" DisplayName="Expected Output" Required="True" Name="Expected Output" />
<FieldRef ID="{2a3d45c7-b841-4d09-b504-ea896d9e4460}" DisplayName="Development Budget" Required="TRUE" Description="Enter 0 if no development budget is required" Name="Development Budget" />
<FieldRef ID="{98d0a6df-edfa-4391-a1af-fd4fc2c996cb}" DisplayName="Budget" Required="TRUE" Name="Budget" />
<FieldRef ID="{5aa99327-7751-4efb-b018-bc579e3a84ae}" DisplayName="Proposed Start Date" Required="TRUE" Name="Start Date" Format="DateOnly" />
<FieldRef ID="{8f6305fb-b742-4c92-9d86-2c1d1d30d814}" DisplayName="Proposed End Date" Required="TRUE" Name="End Date" Format="DateOnly" />
<FieldRef ID="{203929d8-049a-429c-adb8-282213061e39}" DisplayName="Consideration of Strategic Alignment" Required="True" Name="Consideration of Strategic Alignment" />
<FieldRef ID="{493918ed-312d-4f86-a9ee-1e385318c67b}" DisplayName="Consideration of Conservation Principles" Required="True" Name="Consideration of Conservation Principles" />
<FieldRef ID="{9dbf8242-57ef-4b92-b743-c4f747f10300}" DisplayName="Business Case Uploaded" Required="FALSE" Name="Business Case Uploaded" />
<FieldRef ID="{207507fb-ce58-49eb-9cea-396a70015930}" DisplayName="Supporting DocumeMy Uploaded" Required="FALSE" Name="Project Paper Uploaded" />
<FieldRef ID="{9b44e710-1396-432c-8b1c-8a212468df9b}" DisplayName="Submit For Approval" Required="FALSE" Name="Submit For Approval" ShowInEditForm="True" ShowInNewForm="False" />
<FieldRef ID="{a6ac48b4-39fa-4c23-90c6-03600e91f4b7}" DisplayName="Development Site Created" Required="FALSE" Name="DevelopmeMyiteCreated" ShowInEditForm="False" ShowInNewForm="False" />
<FieldRef ID="{287c17a9-c869-46fe-a645-15ffcb7075cd}" DisplayName="Project Site Created" Required="FALSE" Name="ProjectSiteCreated" ShowInEditForm="False" ShowInNewForm="False" />
</FieldRefs>
</ContentType>
</ElemeMy>
List Definition
<?xml version="1.0" encoding="utf-8"?>
<List xmlns:ows="Microsoft SharePoint" Title="My Concept" FolderCreation="FALSE" Direction="$Resources:Direction;" Url="Lists/My Concept" BaseType="0" xmlns="http://schemas.microsoft.com/sharepoint/" EnableContentTypes="TRUE">
<MetaData>
<ContentTypes>
<ContentType ID="0x0100BE5BB437E28E4931960FD3AB89883799" Name="My Concept" Group="My Content Types" Description="My Content Type" Inherits="TRUE" Version="0">
<FieldRefs>
<FieldRef ID="{600c95a5-c81c-4c2d-a1b7-1b90c1fa6537}" DisplayName="Concept ID" Required="FALSE" Name="ConceptID" ShowInEditForm="False" ShowInNewForm="False" />
<FieldRef ID="{0b8e6761-062c-446b-9bf2-28b0c238684d}" DisplayName="Concept Description" Required="True" Name="Project Description" />
<FieldRef ID="{99719dc5-4a0a-4b04-b2f8-353630a0d271}" DisplayName="Proposed Project Manager" Required="TRUE" Name="Project Manager" />
<FieldRef ID="{a24d0da2-8329-4da3-9245-251d167626b6}" DisplayName="Proposed Project Sponsor" Required="TRUE" Name="Project Sponsor" />
<FieldRef ID="{49e5c95d-24bb-4575-9450-d6489cc825f7}" DisplayName="Expected Output" Required="True" Name="Expected Output" />
<FieldRef ID="{2a3d45c7-b841-4d09-b504-ea896d9e4460}" DisplayName="Development Budget" Required="TRUE" Description="Enter 0 if no development budget is required" Name="Development Budget" />
<FieldRef ID="{98d0a6df-edfa-4391-a1af-fd4fc2c996cb}" DisplayName="Budget" Required="TRUE" Name="Budget" />
<FieldRef ID="{5aa99327-7751-4efb-b018-bc579e3a84ae}" DisplayName="Proposed Start Date" Required="TRUE" Name="Start Date" Format="DateOnly" />
<FieldRef ID="{8f6305fb-b742-4c92-9d86-2c1d1d30d814}" DisplayName="Proposed End Date" Required="TRUE" Name="End Date" Format="DateOnly" />
<FieldRef ID="{203929d8-049a-429c-adb8-282213061e39}" DisplayName="Consideration of Strategic Alignment" Required="True" Name="Consideration of Strategic Alignment" />
<FieldRef ID="{493918ed-312d-4f86-a9ee-1e385318c67b}" DisplayName="Consideration of Conservation Principles" Required="True" Name="Consideration of Conservation Principles" />
<FieldRef ID="{9dbf8242-57ef-4b92-b743-c4f747f10300}" DisplayName="Business Case Uploaded" Required="FALSE" Name="Business Case Uploaded" />
<FieldRef ID="{207507fb-ce58-49eb-9cea-396a70015930}" DisplayName="Supporting DocumeMy Uploaded" Required="FALSE" Name="Project Paper Uploaded" />
<FieldRef ID="{9b44e710-1396-432c-8b1c-8a212468df9b}" DisplayName="Submit For Approval" Required="FALSE" Name="Submit For Approval" ShowInEditForm="True" ShowInNewForm="False" />
<FieldRef ID="{a6ac48b4-39fa-4c23-90c6-03600e91f4b7}" DisplayName="Development Site Created" Required="FALSE" Name="DevelopmeMyiteCreated" ShowInEditForm="False" ShowInNewForm="False" />
<FieldRef ID="{287c17a9-c869-46fe-a645-15ffcb7075cd}" DisplayName="Project Site Created" Required="FALSE" Name="ProjectSiteCreated" ShowInEditForm="False" ShowInNewForm="False" />
</FieldRefs>
</ContentType>
<ContentTypeRef ID="0x01">
<Folder TargetName="Item" />
</ContentTypeRef>
<ContentTypeRef ID="0x0120" />
</ContentTypes>
<Fields>
<Field ID="{fa564e0f-0c70-4ab9-b863-0177e6ddd247}" Type="Text" Name="Title" DisplayName="$Resources:core,Title;" Required="TRUE" SourceID="http://schemas.microsoft.com/sharepoint/v3" StaticName="Title" MaxLength="255" />
<Field ID="{600c95a5-c81c-4c2d-a1b7-1b90c1fa6537}" Name="ConceptID" DisplayName="Concept ID" Type="Text" Required="FALSE" Group="My Projects Columns" ShowInEditForm="False" ShowInNewForm="False"></Field>
<Field ID="{0b8e6761-062c-446b-9bf2-28b0c238684d}" Name="Project Description" DisplayName="Concept Description" Type="Note" Required="True" Group="My Projects Columns"></Field>
<Field ID="{99719dc5-4a0a-4b04-b2f8-353630a0d271}" Name="Project Manager" DisplayName="Proposed Project Manager" Type="User" Required="TRUE" Group="My Projects Columns"></Field>
<Field ID="{a24d0da2-8329-4da3-9245-251d167626b6}" Name="Project Sponsor" DisplayName="Proposed Project Sponsor" Type="User" Required="TRUE" Group="My Projects Columns"></Field>
<Field ID="{49e5c95d-24bb-4575-9450-d6489cc825f7}" Name="Expected Output" DisplayName="Expected Output" Type="Note" Required="True" Group="My Projects Columns"></Field>
<Field ID="{2a3d45c7-b841-4d09-b504-ea896d9e4460}" Name="Development Budget" DisplayName="Development Budget" Type="Currency" Required="TRUE" Description="Enter 0 if no development budget is required" Group="My Projects Columns"></Field>
<Field ID="{98d0a6df-edfa-4391-a1af-fd4fc2c996cb}" Name="Budget" DisplayName="Budget" Type="Currency" Required="TRUE" Group="My Projects Columns"></Field>
<Field ID="{5aa99327-7751-4efb-b018-bc579e3a84ae}" Name="Start Date" DisplayName="Proposed Start Date" Type="DateTime" Required="TRUE" Format="DateOnly" Group="My Projects Columns"></Field>
<Field ID="{8f6305fb-b742-4c92-9d86-2c1d1d30d814}" Name="End Date" DisplayName="Proposed End Date" Type="DateTime" Required="TRUE" Format="DateOnly" Group="My Projects Columns"></Field>
<Field ID="{203929d8-049a-429c-adb8-282213061e39}" Name="Consideration of Strategic Alignment" DisplayName="Consideration of Strategic Alignment" Type="Note" Required="True" Group="My Projects Columns"></Field>
<Field ID="{493918ed-312d-4f86-a9ee-1e385318c67b}" Name="Consideration of Conservation Principles" DisplayName="Consideration of Conservation Principles" Type="Note" Required="True" Group="My Projects Columns"></Field>
<Field ID="{9dbf8242-57ef-4b92-b743-c4f747f10300}" Name="Business Case Uploaded" DisplayName="Business Case Uploaded" Type="Boolean" Required="FALSE" Group="My Projects Columns"></Field>
<Field ID="{207507fb-ce58-49eb-9cea-396a70015930}" Name="Project Paper Uploaded" DisplayName="Supporting DocumeMy Uploaded" Type="Boolean" Required="FALSE" Group="My Projects Columns"></Field>
<Field ID="{9b44e710-1396-432c-8b1c-8a212468df9b}" Name="Submit For Approval" DisplayName="Submit For Approval" Type="Boolean" Required="FALSE" Group="My Projects Columns" ShowInEditForm="True" ShowInNewForm="False"></Field>
<Field ID="{a6ac48b4-39fa-4c23-90c6-03600e91f4b7}" Name="DevelopmeMyiteCreated" DisplayName="Development Site Created" Type="Boolean" Required="FALSE" Group="My Projects Columns" ShowInEditForm="False" ShowInNewForm="False"></Field>
<Field ID="{287c17a9-c869-46fe-a645-15ffcb7075cd}" Name="ProjectSiteCreated" DisplayName="Project Site Created" Type="Boolean" Required="FALSE" Group="My Projects Columns" ShowInEditForm="False" ShowInNewForm="False"></Field>
</Fields>
<Views>
<View BaseViewID="0" Type="HTML" MobileView="TRUE" TabularView="FALSE">
<Toolbar Type="Standard" />
<XslLink Default="TRUE">main.xsl</XslLink>
<RowLimit Paged="TRUE">30</RowLimit>
<ViewFields>
<FieldRef Name="LinkTitleNoMenu"></FieldRef>
</ViewFields>
<Query>
<OrderBy>
<FieldRef Name="Modified" Ascending="FALSE"></FieldRef>
</OrderBy>
</Query>
<ParameterBindings>
<ParameterBinding Name="AddNewAnnouncement" Location="Resource(wss,addnewitem)" />
<ParameterBinding Name="NoAnnouncemeMy" Location="Resource(wss,noXinviewofY_LIST)" />
<ParameterBinding Name="NoAnnouncemeMyHowTo" Location="Resource(wss,noXinviewofY_ONET_HOME)" />
</ParameterBindings>
</View>
<View BaseViewID="1" Type="HTML" WebPartZoneID="Main" DisplayName="$Resources:core,objectiv_schema_mwsidcamlidC24;" DefaultView="TRUE" MobileView="TRUE" MobileDefaultView="TRUE" SetupPath="pages\viewpage.aspx" ImageUrl="/_layouts/15/images/generic.png?rev=23" Url="AllItems.aspx">
<Toolbar Type="Standard" />
<XslLink Default="TRUE">main.xsl</XslLink>
<JSLink>clienttemplates.js</JSLink>
<RowLimit Paged="TRUE">30</RowLimit>
<ViewFields>
<FieldRef Name="LinkTitle"></FieldRef>
<FieldRef Name="ConceptID" />
<FieldRef Name="Project Description" />
<FieldRef Name="Project Manager" />
<FieldRef Name="Project Sponsor" />
<FieldRef Name="Expected Output" />
<FieldRef Name="Development Budget" />
<FieldRef Name="Budget" />
<FieldRef Name="Start Date" />
<FieldRef Name="End Date" />
<FieldRef Name="Consideration of Strategic Alignment" />
<FieldRef Name="Consideration of Conservation Principles" />
<FieldRef Name="Business Case Uploaded" />
<FieldRef Name="Project Paper Uploaded" />
<FieldRef Name="Submit For Approval" />
<FieldRef Name="DevelopmeMyiteCreated" />
<FieldRef Name="ProjectSiteCreated" />
</ViewFields>
<Query>
<OrderBy>
<FieldRef Name="ID"></FieldRef>
</OrderBy>
</Query>
<ParameterBindings>
<ParameterBinding Name="NoAnnouncemeMy" Location="Resource(wss,noXinviewofY_LIST)" />
<ParameterBinding Name="NoAnnouncemeMyHowTo" Location="Resource(wss,noXinviewofY_DEFAULT)" />
</ParameterBindings>
</View>
</Views>
<Forms>
<Form Type="DisplayForm" Url="DispForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
<Form Type="EditForm" Url="EditForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
<Form Type="NewForm" Url="NewForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
</Forms>
</MetaData>
</List>
Error
[COMException (0x80004005): Cannot complete this action.
Please try again.<nativehr>0x80004005</nativehr><nativestack></nativestack>]
Microsoft.SharePoint.Library.SPRequestInternalClass.CreateListFromFormPost(String bstrUrl, String& pbstrGuid, String& pbstrNextUrl) +0
Microsoft.SharePoint.Library.SPRequest.CreateListFromFormPost(String bstrUrl, String& pbstrGuid, String& pbstrNextUrl) +204
[SPException: Cannot complete this action.
Please try again.]
Microsoft.SharePoint.SPGlobal.HandleComException(COMException comEx) +146
Microsoft.SharePoint.Library.SPRequest.CreateListFromFormPost(String bstrUrl, String& pbstrGuid, String& pbstrNextUrl) +462
Microsoft.SharePoint.SPListCollection.CreateListFromRpc(NameValueCollection queryString, Uri& nextUrl) +1796
Microsoft.SharePoint.ApplicationPages.NewListPage.BtnOk_Click(Object sender, EventArgs args) +481
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +146
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3586
A:
Try:
Step by step exclude some block definitions from list definition to find out what exactly doesn't work.
Another recomendation, do not use gaps in Name property of the Field definition, it will be changed into something like _x2000, could be error with FieldRef of content type connection.
In FieldRef try to use only necessary properties like ID, Name or ShowId*... properties like DisplayName will be copied anyway..
If you tried to create your list through the interface and it worked, try to open created list definition through Sharepoint Manager and identify differences.
| {
"pile_set_name": "StackExchange"
} |
Q:
Checking for a new day using sql.timestamp
I'm working with some legacy code and I'm iterating through some values, the legacy code is checking for the start of a new day using an sql.timestamp value:
public static final long MILLIS_PER_SECOND = 1000;
public static final long MILLIS_PER_MINUTE = 60 * MILLIS_PER_SECOND;
public static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE;
public static final long MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR;
if (entry.getPeriodEnd().getTime() % TimestampUtils.MILLIS_PER_DAY == 0 || i >= throughputEntries.size()) {
...
}
The result is never 0 so it only goes into the if when i >= throughputEntries.size()
I can't get me head around how he was getting a 0 result, possibly his data was different and always ended with a certain time period that would produce the 0
I could rewrite the code maybe to do a check on the date, but would like to know how he achieved it with his code.
I'm not sure that this could be solved with the code I have provided, but maybe I'm missing something...
Edit
So I got my head around this in the end, thanks to @t0r0X & @Leo
I've modified my code to use Joda-Time as follows:
LocalDate newDay = null;
int count = 0;
public void calcAvg(){
DateTimeZone zone = DateTimeZone.getDefault();
LocalDate throughtputDate = entry.getPeriodEnd().toDateTime(zone).toLocalDate();
if ( this.newDay(throughtputDate) || i >= throughputEntries.size()) {
...
}
}
public boolean newDay(LocalDate date){
boolean go = false;
if(count !=0){
if(date.isAfter(newDay)){
newDay = date;
go = true;
}
}
else{
newDay = date;
count++;
}
return go;
}
Probably a cleaner way of checking for the new date than the method I've written, but time waits for no man.
A:
The author of the original code may have probably used synthetic "round" data. Maybe using the (nowadays deprecated) java.sql.Timestamp constructor ...
new Timestamp(116, 1, 25, 0, 0, 0, 0)
or maybe using the (also deprecated) Date constructor ...
new Timestamp(new Date(116, 1, 25).getTime())
Or he might have parsed some test data like e.g. '2016-01-25'...
Look ma, no millis! ;-)
Anyway, to check for a "new day" depends on how you define that. Usually you need a reference date, like the previously processed entry.
Update:
Looking a 4th time at the code entry.getPeriodEnd().getTime(): the entries look like time periods... So there must be a getPeriodBegin() method... and I suppose the needed check is to verify if the period end is in another day than the period begin... Am I right?
Dirty code (deprecated methods):
Timestamp begin = entry.getPeriodBegin()
Timestamp end = entry.getPeriodEnd()
if (begin.getYear() != end.getYear() || begin.getMonth() != end.getMonth() || begin.getDay() != end.getDay() ....)
Clean code:
My recommendation: don't even start with java.util.Calendar (proposal on Stackoverflow). Either use DateUtils from Apache Commons Lang (also suggested here on Stackoverflow; comments are relevant), or, my favourite, get JodaTime and stop worring (suggestion also on Stackoverflow; comments are relevant). I personally have always got happy with JodaTime.
PS
Not to forget (thanks to @Leo for his comment on the question, I'm still living, ahem, working, in a Java 6-7 world :-/ ...): if using Java 8 or later, go for the new java.time classes.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the meaning of >> and & in this code context and what they are trying to accomplish?
I am following a tutorial on YouTube for making a 2D game. There is no clear explanation on what its actually doing.
I get bit-shifting and & operator but I don't know what they mean in this context and I understand basic Java implementation.
I've done some basic trial and error with the below code by seeing how it works, I see the effects happening but don't quite comprehend on what it is supposed to be doing in the code.
Could someone please explain how the lines marked with "//*******" work in the given context?
public class Screen {
public static final int MAP_WIDTH= 64;
public static final int MAP_WIDTH_MASK= MAP_WIDTH - 1;
public static final int PIXEL_SIZE= 8;
public static final int PIXEL_SIZE_MASK= MAP_WIDTH - 1;
public int[] tiles = new int[MAP_WIDTH*MAP_WIDTH];
public int[] colours = new int[MAP_WIDTH*MAP_WIDTH*4];
public int xOffset = 0;
public int yOffset = 0;
public int width;
public int height;
public SpriteSheet sheet;
public Screen(int width, int height, SpriteSheet sheet) {
this.width = width;
this.height = height;
this.sheet = sheet;
// ************ explain what the for loop is doing
for(int i=0; i< (tiles.length); i++) {
colours[i*4+ 0] = 0xff00ff;
colours[i*4+ 1] = 0x0000ff;
colours[i*4+ 2] = 0xffff00;
colours[i*4+ 3] = 0xffffff;
}
}
public void render(int[] pixels, int offset, int row) {
//current x and y offset is 0 meaning that the player/map isn't moving in either direction - changing them repeats the map
// >>3 - same as multiplying by 8 (size of pixel)
//(0 * 8 ) + yOffset, (height * 8) + yOffset
// ************ what is the >> doing in this context?
for(int yTile = (0 + yOffset) >> 3; yTile<=(height + yOffset) >> 3; yTile++) {
// ************ what actually is yMin?
int yMin = (yTile * PIXEL_SIZE) - yOffset;
// ************ what actually is yMax?
int yMax = yMin + PIXEL_SIZE;
//sanity check if you go off the map - otherwise would crash
if (yMin<0) yMin=0; // yMin could be below 0 because of the yOffset variable being changed is greater than (yTile * PIXEL_SIZE)
if (yMax>height) yMax = height; // yMax could be above height because of the yOffset variable being changed
// see above; applies to xTile as well
for(int xTile = (0 + xOffset) >> 3; xTile<=(width + xOffset) >> 3; xTile++) {
int xMin = (xTile * PIXEL_SIZE) - xOffset;
int xMax = xMin + PIXEL_SIZE;
if(xMin<0) xMin=0;
if (xMax>width) xMax = width;
// ************ obviously this gives current tile you're on but what does & do in this context?
int tileIndex = (xTile &(MAP_WIDTH_MASK)) + (yTile &(MAP_WIDTH_MASK))* MAP_WIDTH;
for (int y = yMin; y < yMax; y++){
// ************ what does & do in this context?
int sheetPixel = ((y + yOffset) & PIXEL_SIZE_MASK)*sheet.width + ((xMin + xOffset)& PIXEL_SIZE_MASK);
// ************ is the tilePixel individual pixels in the tile?
int tilePixel = offset + xMin + y * row;
for(int x = xMin; x< xMax; x++) {
// ************ what is tileIndex * 4 doing?
int colour = tileIndex * 4 + sheet.pixels[sheetPixel++];
pixels[tilePixel++] = colours[colour];
}
}
}
}
}
}
A:
for(int i=0; i< (tiles.length); i++) {
colours[i*4+ 0] = 0xff00ff;
colours[i*4+ 1] = 0x0000ff;
colours[i*4+ 2] = 0xffff00;
colours[i*4+ 3] = 0xffffff;
}
The For-Loop at the start is generating groups of four colour entries based on how many tiles you have.
It's a little convoluted to read at a glance and given choice I'd probably not do it that way, but it's pretty efficient nonetheless.
The rest is essentially a way to offset your coordinate system to account for the individual tiles being multiple pixels in size.
The tiles are eight pixels in each axis, so it's going through telling every pixel in each tile what colour it needs to be.
Bitshifting by 3 is essentially taking the number in binary and pushing each number up a slot. eg: 5 >> 3 is 101 becoming 101000, which is 40. This is equivalent to multiplying by 8, which is a 1 and three zeros behind it in binary. The bitshift value is the number of 0s being added.
In this case, it serves nicely to calculate how many pixels we've got between steps so we can jump to the start of the next tile with each step of the loop. the individual pixels are handled inside the loop.
Single Ampersands are used in Bitwise operations as well as logical conditions, Wikipedia has the details on this here
| {
"pile_set_name": "StackExchange"
} |
Q:
android setVisibility(LinearLayout.VISIBLE) not work in WebView @JavascriptInterface Function
activity_main.xml content
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:id="@+id/ny_web_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ny_sms"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorBlack"
android:isScrollContainer="false"
android:orientation="vertical"
android:paddingLeft="10dp"
android:paddingTop="10dp"
android:paddingRight="10dp"
android:visibility="gone"></LinearLayout>
</android.support.constraint.ConstraintLayout>
MainActivity.java content
package com......;
import android.Manifest;
import android.blablabla.and.other.imports;
...
...
public class MainActivity extends AppCompatActivity {
static WebView mWebView;
static LinearLayout ny_sms;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
ny_sms =(LinearLayout)findViewById(R.id.ny_sms);
mWebView = (WebView)findViewById(R.id.ny_web_view);
mWebView.setWebViewClient(new WebViewClient());
mWebView.loadUrl("file:///android_asset/main.html");
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.addJavascriptInterface(new WebAppInterface(this),"Android");
}
public static void showLayoutMA() {
mWebView.setVisibility(WebView.INVISIBLE);
ny_sms.setVisibility(LinearLayout.VISIBLE);
}
}
class WebAppInterface {
Context mContext;
WebAppInterface(Context c) {
mContext = c;
}
@JavascriptInterface
public void showLayout() {
MainActivity.showLayoutMA();
}
}
main.html content
<html>
<body>
<center>
<a href="#" onclick="Android.showLayout()">Visiblity Test</a>
</center>
</body>
</html>
all permissions ok. al settings ok, app version 28 (android 9 pie)
im click "Visiblity Test" link not change any screen activity,
and after scroll to bottom nofication top bar click toggle auto rotate screen button
auto refresh and show LinearLayout front of the webview control.
how to fix this problem.
not showing LinearLayout and webView not invisible with "Visiblity Test" clicked. after need a refreshing action.
Sorry my English is bad :(
A:
im found this problem,
returned error "Only the original thread that created a view hierarchy can touch its views"
So then you need me: runOnUiThread()
extend this code...
public static void showLayoutMA() {
CurrentActivitiy.runOnUiThread(new Runnable() {
@Override
public void run() {
//mWebView.setVisibility(WebView.INVISIBLE);
ny_sms.setVisibility(LinearLayout.VISIBLE);
}
});
why not use direct runOnUiThread(new Runnable() {} function, because my function is static, im add "CurrentActivitiy" declaration of MainActivity.
static Activity CurrentActivitiy;
CurrentActivitiy = (Activity)MainActivity.this;
and after few hours happy ending, problem is resolved..
| {
"pile_set_name": "StackExchange"
} |
Q:
Android Universe library showImageOnLoading issue
I have some issues with DisplayImageOptions.Builder().showImageOnLoading(R.drawable.ic_stub)
The method showImageOnLoading(int) is undefined for the type
DisplayImageOptions.Builder
Other options, like:
.showStubImage(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error)
are valid and work.
A:
showImageOnLoading(...) will be available in next lib version. This is replacement for showStubImage(...) which does exactly the same.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I activate database settings from my settings.py DATABASES array based on environment?
I'm using Django with Python 3.7. I have a settings.py file, which includes some database settings ...
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'mainpage',
'USER': 'mainpage',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '5432'
},
'production': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'mainpage',
'USER': 'mainpage',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '5432'
}
}
The file includes a bunch of other things but I have only included the database array here. Is it possible to activate a particular database configuration from my array based on my environment or an environment variable? I would prefer not to have multiple settings files because then I have to repeat a lot of other configurations in them that do not change across environment. I'm happy to move the database settings to their own files if that's what it takes but I'm not sure how they would be activated.
Edit: Per Scott Skiles' answer, this is the error I'm getting when I remove settings.py and add the other directory and files, but I get this error when loading my Python console ...
File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/__init__.py", line 19, in setup
configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 57, in __getattr__
self._setup(name)
File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 42, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
Here is my init.py file. I haven't altered it since the project was created ...
"""
Settings and configuration for Django.
Read values from the module specified by the DJANGO_SETTINGS_MODULE environment
variable, and then from django.conf.global_settings; see the global_settings.py
for a list of all possible variables.
"""
import importlib
import os
import time
import warnings
from pathlib import Path
from django.conf import global_settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.deprecation import RemovedInDjango30Warning
from django.utils.functional import LazyObject, empty
ENVIRONMENT_VARIABLE = "DJANGO_SETTINGS_MODULE"
class LazySettings(LazyObject):
"""
A lazy proxy for either global Django settings or a custom settings object.
The user can manually configure settings prior to using them. Otherwise,
Django uses the settings module pointed to by DJANGO_SETTINGS_MODULE.
"""
def _setup(self, name=None):
"""
Load the settings module pointed to by the environment variable. This
is used the first time settings are needed, if the user hasn't
configured settings manually.
"""
settings_module = os.environ.get(ENVIRONMENT_VARIABLE)
if not settings_module:
desc = ("setting %s" % name) if name else "settings"
raise ImproperlyConfigured(
"Requested %s, but settings are not configured. "
"You must either define the environment variable %s "
"or call settings.configure() before accessing settings."
% (desc, ENVIRONMENT_VARIABLE))
self._wrapped = Settings(settings_module)
def __repr__(self):
# Hardcode the class name as otherwise it yields 'Settings'.
if self._wrapped is empty:
return '<LazySettings [Unevaluated]>'
return '<LazySettings "%(settings_module)s">' % {
'settings_module': self._wrapped.SETTINGS_MODULE,
}
def __getattr__(self, name):
"""Return the value of a setting and cache it in self.__dict__."""
if self._wrapped is empty:
self._setup(name)
val = getattr(self._wrapped, name)
self.__dict__[name] = val
return val
def __setattr__(self, name, value):
"""
Set the value of setting. Clear all cached values if _wrapped changes
(@override_settings does this) or clear single values when set.
"""
if name == '_wrapped':
self.__dict__.clear()
else:
self.__dict__.pop(name, None)
super().__setattr__(name, value)
def __delattr__(self, name):
"""Delete a setting and clear it from cache if needed."""
super().__delattr__(name)
self.__dict__.pop(name, None)
def configure(self, default_settings=global_settings, **options):
"""
Called to manually configure the settings. The 'default_settings'
parameter sets where to retrieve any unspecified values from (its
argument must support attribute access (__getattr__)).
"""
if self._wrapped is not empty:
raise RuntimeError('Settings already configured.')
holder = UserSettingsHolder(default_settings)
for name, value in options.items():
setattr(holder, name, value)
self._wrapped = holder
@property
def configured(self):
"""Return True if the settings have already been configured."""
return self._wrapped is not empty
class Settings:
def __init__(self, settings_module):
# update this dict from global settings (but only for ALL_CAPS settings)
for setting in dir(global_settings):
if setting.isupper():
setattr(self, setting, getattr(global_settings, setting))
# store the settings module in case someone later cares
self.SETTINGS_MODULE = settings_module
mod = importlib.import_module(self.SETTINGS_MODULE)
tuple_settings = (
"INSTALLED_APPS",
"TEMPLATE_DIRS",
"LOCALE_PATHS",
)
self._explicit_settings = set()
for setting in dir(mod):
if setting.isupper():
setting_value = getattr(mod, setting)
if (setting in tuple_settings and
not isinstance(setting_value, (list, tuple))):
raise ImproperlyConfigured("The %s setting must be a list or a tuple. " % setting)
setattr(self, setting, setting_value)
self._explicit_settings.add(setting)
if not self.SECRET_KEY:
raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
if self.is_overridden('DEFAULT_CONTENT_TYPE'):
warnings.warn('The DEFAULT_CONTENT_TYPE setting is deprecated.', RemovedInDjango30Warning)
if hasattr(time, 'tzset') and self.TIME_ZONE:
# When we can, attempt to validate the timezone. If we can't find
# this file, no check happens and it's harmless.
zoneinfo_root = Path('/usr/share/zoneinfo')
zone_info_file = zoneinfo_root.joinpath(*self.TIME_ZONE.split('/'))
if zoneinfo_root.exists() and not zone_info_file.exists():
raise ValueError("Incorrect timezone setting: %s" % self.TIME_ZONE)
# Move the time zone info into os.environ. See ticket #2315 for why
# we don't do this unconditionally (breaks Windows).
os.environ['TZ'] = self.TIME_ZONE
time.tzset()
def is_overridden(self, setting):
return setting in self._explicit_settings
def __repr__(self):
return '<%(cls)s "%(settings_module)s">' % {
'cls': self.__class__.__name__,
'settings_module': self.SETTINGS_MODULE,
}
class UserSettingsHolder:
"""Holder for user configured settings."""
# SETTINGS_MODULE doesn't make much sense in the manually configured
# (standalone) case.
SETTINGS_MODULE = None
def __init__(self, default_settings):
"""
Requests for configuration variables not in this class are satisfied
from the module specified in default_settings (if possible).
"""
self.__dict__['_deleted'] = set()
self.default_settings = default_settings
def __getattr__(self, name):
if name in self._deleted:
raise AttributeError
return getattr(self.default_settings, name)
def __setattr__(self, name, value):
self._deleted.discard(name)
if name == 'DEFAULT_CONTENT_TYPE':
warnings.warn('The DEFAULT_CONTENT_TYPE setting is deprecated.', RemovedInDjango30Warning)
super().__setattr__(name, value)
def __delattr__(self, name):
self._deleted.add(name)
if hasattr(self, name):
super().__delattr__(name)
def __dir__(self):
return sorted(
s for s in list(self.__dict__) + dir(self.default_settings)
if s not in self._deleted
)
def is_overridden(self, setting):
deleted = (setting in self._deleted)
set_locally = (setting in self.__dict__)
set_on_default = getattr(self.default_settings, 'is_overridden', lambda s: False)(setting)
return deleted or set_locally or set_on_default
def __repr__(self):
return '<%(cls)s>' % {
'cls': self.__class__.__name__,
}
settings = LazySettings()
A:
This is following the approach where you use a separate 'settings' directory. Be careful switching to this as it might break some things initially, such as your manage.py file.
Both dev.py and prod.py would import stuff from base.py. Anything that is common to both dev and prod goes into base. Anything that is unique to development goes into dev.py and anything that is specific to production goes into prod.py.
.bashrc:
export DJANGO_DEVELOPMENT=true
manage.py
import os
if os.environ['DJANGO_DEVELOPMENT'] == 'true':
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings.dev")
else:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings.prod")
directory structure
-> app
--> settings
---> base.py
---> prod.py
---> dev.py
dev.py
from app.settings.base import *
# This will overwrite anything in base.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'mainpage',
'USER': 'mainpage',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '5432'
},
}
Modify any locations that use DJANGO_SETTINGS_MODULE to use the new env var, such as wsgi.py:
import os
from django.core.wsgi import get_wsgi_application
if os.environ["DJANGO_DEVELOPMENT"]:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mainpage.settings.dev")
else:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mainpage.settings.prod")
application = get_wsgi_application()
~
| {
"pile_set_name": "StackExchange"
} |
Q:
Typeahead in a Model return empty value to form input field
I create a table with a button. When a user switch the button it will open a Bootstrap-Modal.
Inside the Modal is a form wite a typeahed select field. The list works and all items are selectable.
My Problem:
If i select a item it shows on form on post the return value (PHP $_POST) are empty.
My js code
$(document).ready(function () {
$('.typeahead').typeahead({
source: function (query, process) {
$.ajax({
url: '/testPost',
type: 'POST',
dataType: 'JSON',
//data: 'query=' + query,
data: 'query=' + $('#contactName').val(),
success: function(data)
{
var results = data.map(function(item) {
//var someItem = { contactname: item.ContactName, telephone: item.Telephone, email: item.Email };
var someItem = { contactname: item.ContactName, id: item.id };
console.log(item);
return JSON.stringify(someItem.contactname);
});
return process(results);
}
});
},
minLength: 1,
updater: function(item) {
// This may need some tweaks as it has not been tested
var obj = JSON.parse(item);
return item;
}
});
});
php json
$return_arr[] = array("id" => "1", "ContactName" => "Dooome");
$return_arr[] = array("id" => "2", "ContactName" => "Caa");
$return_arr[] = array("id" => "3", "ContactName" => "Veee");
$return_arr[] = array("id" => "4", "ContactName" => "Moo");
$return_arr[] = array("id" => "5", "ContactName" => "Reee");
#$return_arr[] = array("value" => "Dooome");
header("Content-Type: application/json");
print_r(json_encode($return_arr));
A:
If you want select in typeahead input .val() not working, you get value with: $('#contactName').typeahead('val'), this way you get value
of input for sending in data of Post Ajax
Look at the documentation of typeahead
| {
"pile_set_name": "StackExchange"
} |
Q:
jquery mobile pagecontent beforeshow not working
I have this checkbox that when it's checked, it should add some text/content to a favourites page. I've trying to find a way to make it happen, but no luck so far.
I've been trying to go around this code:
Javascript:
$( document ).on( "pagecontainerbeforeshow", function( event, ui ) {
if(ui.toPage.is('#favs')){
if($('#event1Fav').is(":checked")){
$('#favs#favList').append('<br /><a href="#eventDesc1">Event 1</a><br />');
} else{
$('#favs-content').append("");
}
}
} );
HTML:
<input type="checkbox" id="event1Fav"/>Add to Favourites
Any help would be very much appretiated :)
A:
Sine you have checkbox in a different page, you have to specify in which page it is. That's in case you have the same checkbox in different pages with same ID.
Moreover, #favs#favList is a wrong selector, you should leave a space between them. Or find it within target page $("#favList", ui.toPage) or ui.toPage.find("#favList").
Javascript:
$( document ).on( "pagecontainerbeforeshow", function( event, ui ) {
if(ui.toPage.is('#favs')){
if($('#pageID #event1Fav').is(":checked")){
$('#favList', ui.toPage).append('<br /><a href="#eventDesc1">Event 1</a><br />');
} else {
$('#favs-content', ui.toPage).append("");
}
}
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Dot product in LookAt Matrix implementation
I was going through an implementation of lookAt matrix for creating view matrix in OpenGL. This particular implementation is from glm math library.
When calculating the lookAt matrix the position vector of the transform is calculated as the dot product of respective orientation axis with the eye position. For example the x value of the position vector is -dotProduct(RightVector, eyeVector)
I know that dot product value indicates how similar two vectors are with each other. But why is it used here to calculate position?
This function describes lookAt matrix for right handed coordinates system:
GLM_FUNC_QUALIFIER mat<4, 4, T, Q> lookAtRH(vec<3, T, Q> const& eye, vec<3, T, Q> const& center, vec<3, T, Q> const& up)
{
vec<3, T, Q> const f(normalize(center - eye));
vec<3, T, Q> const s(normalize(cross(f, up)));
vec<3, T, Q> const u(cross(s, f));
mat<4, 4, T, Q> Result(1);
Result[0][0] = s.x;
Result[1][0] = s.y;
Result[2][0] = s.z;
Result[0][1] = u.x;
Result[1][1] = u.y;
Result[2][1] = u.z;
Result[0][2] =-f.x;
Result[1][2] =-f.y;
Result[2][2] =-f.z;
Result[3][0] =-dot(s, eye);
Result[3][1] =-dot(u, eye);
Result[3][2] = dot(f, eye);
return Result;
}
A:
The parameters to "lookAt" define the position and orientation of the camera (eye) in the world. A matrix which is set by this parameters would transform form view space to world space. It can take coordinates which are relative to the camera and transform them to coordinates in the world.
But the view matrix has to transform from world space to view space. The view matrix has to take coordinates in the world and to calculate the corresponding coordinate relative to the camera.
The matrix which transforms from world space to view space is the inverse matrix of that matrix which defines the camera position and orientation in the world.
Think about this algorithm as the optimized computation of the inverse camera matrix.
The input is the position of the camera in world space. It has to be calculate the position of the camera in relation to the orientation of the camera. For that the Dot product is used. The dot product can "project" a vector to an other vector. It calculates the component (length) of vector along an other vector or axis. Note, s, u and f are Unit vectors. In this case the dot product is used to calculate the x, y and z component of eye in relation to the axis s, u and -f. s, u and -f are the axis of the world space as seen from view space.
This is exactly the same as transforming a vector by the upper left 3x3 of the view matrix.
| {
"pile_set_name": "StackExchange"
} |
Q:
Setting content-type of response in Spring 3.1 mvc webservice
I'm trying to set up a spring 3.1 mvc webservice that will return xml. I have a method which returns the xml as a string already called getxmlforparam().
Below is a snippet of the code I have so far which always returns the correct content but with the wrong content-type = text/html.
Is there a way of setting the content type other than with the RequestMapping produces and response.addHeader techniques that I have tried below?
@Service
@RequestMapping(value="endpointname")
public class XmlRetriever {
//set up variables here
@RequestMapping(method = RequestMethod.GET, produces = "application/xml")
@ResponseBody
public String getXml(
@RequestParam(value = "param1") final String param1,
/*final HttpServletResponse response*/){
String result = null;
result = getxmlforparam(param1);
/*response.addHeader("Content-Type", "application/xml");*/
return result;
}
Thanks.
EDIT:
solution by writing straight to the response object per MikeN's suggestion below:
@Service
@RequestMapping(value="endpointname")
public class XmlRetriever {
//set up variables here
@RequestMapping(method = RequestMethod.GET, produces = "application/xml")
@ResponseBody
public String getXml(
@RequestParam(value = "param1") final String param1,
final HttpServletResponse response){
String result = null;
result = getxmlforparam(param1);
response.setContentType("application/xml");
try{
PrintWriter writer = response.getWriter();
writer.write(result);
}
catch(IOException ioex){
log.error("IO Exception thrown when trying to write response", ioex.getMessage());
}
}
}
A:
You should either register your own HttpMessageConvertor (it should now be using a StringHttpMessageConverter, which outputs text/plain, see http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/http/converter/StringHttpMessageConverter.html), or you should handle the whole request yourself.
The latter is probably the easiest, but the least Spring-MVC'ish. You just return null, and use the response object to write the result.
The Spring-MVC way would be to implement the mapping from your internal objects to XML in a HttpMessageConverter, and return your internal object together with @ResponseBody from your MVC controller function.
| {
"pile_set_name": "StackExchange"
} |
Q:
Sharing object by reference or pointer
Say I have an object of type A having Initialize() method.
The method receives object B, which are kept as the object data member.
B object is shared between several objects, thus A should contain the originally received B object and not its copy.
class A
{
public:
bool Initialize(B?? b);
private:
B?? m_B;
}
Object B must present. Thus I think to pass it by reference, instead of passing by pointer and failing Initialize() in case B is NULL.
The only alrernative for m_B is to be of type of pointer B (it cann't be reference of B, since the intializating of B is not done in A c-tor). Thus Initialize should look like:
bool A::Initialize(B& b)
{
m_B = &b;
....
}
Is this aproach is ok?
UPD:
The code is not new and I'm just trying to "fix" some problems.
Actually I'm not talking about some concrete A and b classes, rather about a way the problem is approached in my code base. The code widely passes pointer to B and verifying it in Initialize() if it's NULL.
Passing B to A's c-tor is not always a good option too. There're also other parametrs passed to A, which are not exists at A creation time. Therefore I woudln't prefer to pass part of parameters to A c-tor and the rest to A::Initialize().
shared_ptr can be "NULL" too, so passing it to A::Initialize() not different from passing just pointer to B, in that aspect that signature of Initialize() dosn't declare if B is mandatory or not. In my case it is and I want to express it by passing reference to B.
Our code currently is not using boost at all. So, although shared_ptr better solution than just passing raw pointer, can solution proposed by me be considered as bad, but still solution.
A:
I'd stay with pointer.
Reference here just sends wrong message.
You don't use references to object in situations when you plan to take pointer to object
and keep or share it, etc.
Main reason for references in C++ is allowing things like operator overloading
and copy constructors to work for user defined types.
Without them it would be difficult to provide this functionality with syntax
that doesn't differ from built in types.
But in this situation you're not trying to mimic built in type.
You are operating on object which is normally used through pointer and
even shared through several different pointers.
So be explicit about that.
As for b being NULL, by all means use assert(b) (or similar construct)
to enforce contract and stop invalid program.
(I wouldn't throw exception though.
Even if you forget about problems with exceptions in C++,
are you planning to ever catch and handle such exception in your code?)
I would also add such assertions to all code that uses m_B
in case someone forgot to call A::Initialize().
Using reference to ensure pointer is not null, might misfire.
In most implementation you can make reference from NULL or dangling pointer
without raising any error.
Your application will fail only if you try to use this reference.
So if someone accidentally passes you B *pb which equals NULL,
you could call pa->Initialize(*pb) and nothing happens.
Except that pa->m_B is now NULL.
Whether to use something like boost::shared_ptr is up to you and your strategy of memory
management.
It's a completely unrelated issue.
| {
"pile_set_name": "StackExchange"
} |
Q:
Execute function multiple times without using a loop
I have a simple table with IDs:
ObjectId
----------
100
101
102
I'd would like to execute a function fn_GetStuff(Id) multiple times like this:
fn_GetStuff(100)
fn_GetStuff(101)
fn_GetStuff(102)
Is it possible to do this without using a loop?
I tried this it doesn't work:
SELECT *
FROM myTable
INNER JOIN fn_GetStuff(myTable.ObjectId)
A:
OP is using a in-line table valued function it looks like so they would need a CROSS APPLY...
Select *
From myTable mt
Cross Apply schema.fn_GetStuff(mt.ObjectID) f
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is "dir-or-file-in-usr-local" an error rather than a warning?
I'm building some rpm packages and checking for standards and style conformance using rpmlint. The packages are specific to systems at my place of work and they won't get pushed upstream. Our packages include a variety of software, including in-house software, patched versions of software from the repositories, and software not available from the official repositories. We install local packages into /usr/local for many reasons:
avoids naming conflicts with official packages
prevents yum update from clobbering local packages
allows local packages to live on separate partition or disk and/or be shared over NFS so that packages and configurations can be shared among hosts
allows us to have greater control over packages that are installed from sources outside the official repository, many of which do not conform to the standard installation paths (bin, lib, include, share, etc.)
However, rpmlint gets very complainy when run on a package that installs files to /usr/local. For instance, on a custom build of GNU Hello World, this is what rpmlint -i has to say:
hello.x86_64: E: dir-or-file-in-usr-local /usr/local/hello-2.8/bin/hello
A file in the package is located in /usr/local. It's not permitted for
packages to install files in this directory.
I'm aware of the filesystem hierarchy standard, according to which:
The original idea behind '/usr/local' was to have a separate ('local')
'/usr' directory on every machine besides '/usr', which might be just
mounted read-only from somewhere else. It copies the structure of
'/usr'. These days, '/usr/local' is widely regarded as a good place in
which to keep self-compiled or third-party programs. The /usr/local
hierarchy is for use by the system administrator when installing
software locally. It needs to be safe from being overwritten when the
system software is updated. It may be used for programs and data that
are shareable amongst a group of hosts, but not found in /usr. Locally
installed software must be placed within /usr/local rather than /usr
unless it is being installed to replace or upgrade software in /usr.
We are, in fact, following these standards and installing our local software to /usr/local for just these reasons, so I don't see why there should be anything wrong with using a package manager to install packages to /usr/local. However, I'd also like our packages to be standards-compliant, if for no other reason than consistency among our local packages. So why does rpmlint throw an error for files in /usr/local? Shouldn't this be at the packager's descretion? Can I ignore this error or at least make rpmlint print a warning instead?
A:
rpmlint is a tool to check RPMs against some sort of packaging policy. Its configuration is typically distribution dependant and it checks packages against the particular distribution policy. Checking your own packages is fine as long as this is what you want.
If your policy differs from the distribution policy, you either have to configure rpmlint accordingly, refrain from using it or ignore the specific errors.
The following should do the trick when added to /etc/rpmlint/config or ~/.config/rpmlint (not tested):
addFilter("E: dir-or-file-in-usr-local")
Sources:
http://forums.opensuse.org/showthread.php/450353-How-to-disable-RPMlint-error
| {
"pile_set_name": "StackExchange"
} |
Q:
Relation between chemical kinetics and chemical equilibrium
In my chemistry book, the law of chemical equilibrium is derived from the law of mass action:
For a reversible chemical reaction $$\ce{aA +bB\rightleftharpoons cC + dD}$$ where $a$, $b$, $c$ and $d$ are stoichiometric coefficients in the balanced equation, we have, from the law of mass action, the rate of the forward reaction $$r_\mathrm{f} = k_1 \ce{[A]^a[B]^b}\label{1}\tag{1}$$ where $[\ce{A}]$ represents the concentration of $\ce{A}$ and so on. The rate of the backward reaction is $$r_\mathrm{b} = k_2\ce{[C]^c[D]^d} \label{2}\tag{2}$$
At equilibrium, $r_\mathrm{f} = r_\mathrm{b}$, so, we have $$\frac{k_1}{k_2} = \frac{\ce{[C]^c[D]^d}}{\ce{[A]^a[B]^b}}$$ Replacing $\displaystyle \frac{k_1}{k_2}$ by $K_\mathrm{c}$, we have
$$K_\mathrm{c} = \ce{\frac{[C]^c[D]^d}{[A]^a[B]^b}}\tag{3}\label{3}$$
which is the law of chemical equlibrium. $K_\mathrm{c}$ is supposed to be constant, for any concentration of the reactants, at a particular temperature.
However, in chemical kinetics, they tell us that the rate equation, derived from the law of mass action is not always correct. That is, the exponents of the concentration terms in the rate equations may not be equal to their stoichiometric coefficients. If this is true then, the above two rate equations ($\eqref{1}$ and $\eqref{2}$) may not be correct for a particular reversible reaction.
Then, how can we apply the law of chemical equilibrium on every reaction, without experimentally verifying the rate equations? If the rate equations derived from the law of mass action are wrong, then the value of $K_\mathrm{c}$ obtained by the final equation will not be constant.
A:
The derivation that you cite only holds true if both forward and backward reactions are elementary steps. In this case, the rate of the forward reaction is indeed given by
$$r = k[\ce{A}]^a[\ce{B}]^b$$
and so on, and hence the derivation is logically sound. If they are not elementary steps, then even though the conclusion is correct, the method of arriving there is not, for the reasons you have already pointed out. See also: hBy2Py's answer and Ben Norris's answer where the assumption of an elementary step is explicitly mentioned.
In general the equilibrium constant does not need to be derived in this manner; a more conventional method of arriving at it is by using (pressure here is taken to equal an arbitrary but specified standard pressure $p^\circ$)
$$\mu_i = \mu_i^\circ + RT\ln a_i$$
where $\mu_i$ is the chemical potential of species $i$, $\mu_i^\circ$ is the standard chemical potential of species $i$, and $a_i$ is the chemical activity of species $i$. We now have, for a reaction
$$\ce{a A + b B -> c C + d D},$$
the following equation:
$$\begin{align}
\Delta_\mathrm r G^\circ &= c\mu_\ce{C}^\circ + d\mu_\ce{D}^\circ - a\mu_\ce{A}^\circ - b\mu_\ce{B}^\circ \\
&= c(\mu_\ce{C} - RT\ln a_\ce{C}) + d(\mu_\ce{D} - RT\ln a_\ce{D}) - a\mu_\ce{A} - RT\ln a_\ce{A} - b(\mu_\ce{B} - RT\ln a_\ce{B}) \\
&= c\mu_\ce{C} + d\mu_\ce{D} - a\mu_\ce{A} - b\mu_\ce{B} - RT \ln\left[\frac{(a_\ce{C})^c (a_\ce{D})^d}{(a_\ce{A})^a (a_\ce{B})^b}\right] \\
&= \Delta_\mathrm r G - RT \ln\left[\frac{(a_\ce{C})^c (a_\ce{D})^d}{(a_\ce{A})^a (a_\ce{B})^b}\right]
\end{align}$$
However, at equilibrium, $\Delta_\mathrm r G = 0$ and hence
$$\Delta_\mathrm r G^\circ = - RT \ln\left[\frac{(a_\ce{C})^c (a_\ce{D})^d}{(a_\ce{A})^a (a_\ce{B})^b}\right]$$
The term in square brackets can then be identified as the equilibrium constant, $K$. As you can see there is no need for any recourse to kinetic rate laws.
Why is $K$ a constant? Well, the standard chemical potentials $\mu_i^\circ$ are thermodynamic constants, just like standard enthalpies of formation, standard entropies, etc. So $\Delta_\mathrm r G^\circ$ - a sum of constants - is itself a constant, and it follows that $K = \exp(-\Delta_\mathrm r G^\circ/RT)$ must be a constant.
A:
The big issue here is that there is confusion between the observed rate law, which is not the same thing as the actual rate law.
For example, there are pseudo zero order reactions, but it is impossible for a reaction to be truly zero order (what is reacting then?).
Consider the following conversion of $\ce{A}$ and $\ce{B}$ to $\ce{C}$, via a two step process involving intermediate $\ce{A'}$.
$$\ce{A + B \overset{k1}{->} A' + B \overset{k2}{->} C}$$
Suppose that the first step is slow ($k1 \ll k2$). This means that the observed rate law would be $k\ce{[A]}$ because as soon as $\ce{A'}$ is formed, the reaction to the product is fast, so the rate is essentially determined by the first step. But it doesn't make any sense that the rate law would be independent of $\ce{B}$. What if $\ce{[B]} = 0$?
If you write out the full rate law without making any assumptions, every species is involved.
Let's see if I can do this properly.
The rate of the reaction is $\ce{k2[A'][B]}$. I'll apply the steady state approximation to $\ce{A'}$ here: because $\ce{A'}$ is a fleeting intermediate that is quickly consumed, we assume that $$\ce{[A']} \approx 0 \Rightarrow \frac{d\ce{[A']}}{dt} \approx 0 $$
$$\frac{d\ce{[A']}}{dt} = -k_{-1}\ce{[A']} - k_{2}\ce{[A'][B]} + k_{1}\ce{[A]} = 0$$
$k_{-1}$ is the rate of the reverse reaction to form $\ce{A'}$.
$$\ce{[A']} = \frac{k_{1}}{k_{-1}+k_{2}\ce{[B]}}\ce{[A]}$$
$$\mathrm{rate} = \frac{k_{1}k_{2}}{k_{-1}+k_{2}\ce{[B]}}\ce{[A][B]}$$
There are two cases to consider.
First, in most scenarios because the second step is fast, $k_{2}\ce{[B]} > k_{1}$. This means that $k_{-1}+k_{2}\ce{[B]} \approx k_{2}\ce{[B]}$, and this $\ce{[B]}$ will cancel the other one in the numerator. It's really important to note that this is a pseudo first order reaction with two component, but the real rate law contains both species.
The other regime is $k_{2}\ce{[B]} < k_{1}$. In other words, there is very little $\ce{B}$ present. Here, $k_{-1}+k_{2}\ce{[B]} \approx k_{-1}$, so the $\ce{[B]}$ in the rate law cannot be canceled out, and we see that the reaction is regained its true second order form, which was concealed by the specifics of the reaction before.
| {
"pile_set_name": "StackExchange"
} |
Q:
Draw to an Image
I'm new to GDI+ and I don't know how to draw to an Image.
I've a matrix ( game map ) and tiles, Can I create an Image or a Bitmap, then I draw everything on it, so I can work with it likes an Image I load from resources.
Thanks so much :)
A:
It sounds like the bit you're missing is that you create the Graphics object on a bitmap you've already created or loaded. e.g.
Gdiplus::Bitmap * pDest = new Gdiplus::Bitmap( nWidth, nHeight,
PixelFormat32bppRGB );
Gdiplus::Graphics graphics( pDest );
Then when you actually draw on the graphics object you're drawing on the bitmap. e.g.
graphics.DrawImage( pOtherImage, 0, 0, pOtherImage->GetWidth(),
pOtherImage->GetHeight() );
Now you can manipulate your bitmap however you want.
| {
"pile_set_name": "StackExchange"
} |
Q:
Difference between "the very first" and "first"
I have the sentence:
Who wrote the very first dictionary ever?
Is it any different from
Who wrote the first dictionary ever?
I don't get how something could be more first.
A:
Typically, the "very" will be used to add emphasis (such as in your example), but it can also clarify the scope of the question.
"When did you have your first cup of coffee?" could refer to your first cup of the day, or the first cup in your life. By contrast, "When did you have your very first cup of coffee?" will almost always be interpreted as referring to the first cup of your life.
A:
It just places greater emphasis on the first instance of whatever it is being a big deal. For that matter, ever in that sentence is used in exactly the same role; "who wrote the first dictionary?" also has the same denotative meaning.
A:
In this case, very is used as an adverb. It adds emphasis and acts as an intensifier.
Other than that, there is no difference between the two.
| {
"pile_set_name": "StackExchange"
} |
Q:
React Drag and Drop - react-dnd - make component draggable and droppable at the same time (apply both roles - drag and drop)
I created a simplified version of my app.
It is here: https://codesandbox.io/s/quirky-glade-x4h51
Current version has bookmarks (top row) and places for them.
When used drags bookmark from bookmarks row and drops it to place, everything works fine.
But what if user drag one of the places and want to move it somewhere?
I wrapped PlaceForChart component both to DropTarget() and DragSource() and exported wrapped component. But it is not working properly.
If a remove any of wrappers, it will work.
Currently when user tries to drag any of PlaceForChart components (orange), the component changes color (as expected), but doesn't move.
How to make it work?
A:
I changed key={Math.random()} in PlaceForChart.tsx and it started working. There are some other issues, but they are not related to dnd behavior. This was the main one.
Working version: https://codesandbox.io/s/billowing-wave-tjugx
| {
"pile_set_name": "StackExchange"
} |
Q:
Adding none extjs controls to extjs toolbar menu
Am trying to add a none extjs element to a toolbar menu items, let's say for example I want to add a jquery ui element to the extjs menu items.
Is this possible or doable?
Thanks
A:
You can wrap the jQuery component as a ExtJS Component and use it inside the toolbar.
This basically involves extending Ext.Component and overriding the render function.
See this components-section-creating-custom-components
| {
"pile_set_name": "StackExchange"
} |
Q:
Some questions about fiber optic cable
I'm curious:
How fast is fiber in traditional Kbps/Mbps/Gbps language? 100Gbps?
Is it possible to set up a private fiber network in an office? What hardware would be required?
Is there such a thing as a LAN router or switch that uses fiber optic cable rather than ethernet/twisted-pair cable?
What sort of networking cards are available for "fiber to the device"?
What is the driver and software support like on various operating systems for fiber?
In summary, I'm curious whether it's possible today (assuming I can afford to access cutting edge consumer technology) to network all the devices and computers in an office to each other with fiber.
When I google for "fiber router" I get a whole lot of crap about wifi routers and not much information about whether it's possible to network using fiber rather than twisted pair.
A:
How fast is fiber in traditional Kbps/Mbps/Gbps language? 100Gbps?
Theoretically it can go all the way up to Pbps (i.e. petabits per second), I believe.
What you actually get depends on what hardware you have and how much money you want to spend. (And on the type of the fiber line itself – e.g. obsolete OM1 fiber doesn't have anywhere near the same capacity as modern variants.)
So in practice, if you just want a fiber LAN at home, then either 1 Gbps or 10 Gbps will be the most common options. (1 Gbps converters/modules can go as low as $10 each, while 10 Gbps is still a bit more expensive.) And most ISPs providing FTTH will also use 1 Gbps connections.
On the other hand, many ISPs and other large network operators have already moved to 40 Gbps and even 100 Gbps links for the "backbone" connections.
Don't forget that it is possible to send multiple signals over the same fiber simultaneously, using different wavelengths (colors) – just like different radio frequencies. (This is usually called WDM.) So if one 100 Gbps connection isn't enough, you can have two, or five, or a hundred.
Is it possible to set up a private fiber network in an office? What hardware would be required?
Yes. But the hardest part is the actual fiber cabling installation (precisely attaching connectors, etc.) – I know practically nothing about this. You should probably just find an installer and have them tell you what's needed.
(Note that there are different types of the fiber cable itself. "Single-mode" is probably much more future-proof than "multi-mode" especially at long distances.)
You usually plug the fiber connector into a SFP transceiver module slotted into the switch, router, or computer. The transceiver module is what actually has the optics and performs signal conversion & decoding, while the actual switch only sees the electronic data transmission.
There are multiple different module types (SFP for 1G, SFP+ for 10G, QSFP, etc.) and the modules themselves are for different kinds of fiber types – multi-mode, single-mode, single-mode bidirectional. Even for the same kind of fiber, there might be modules for different wavelengths (this obviously must match on both ends).
Is there such a thing as a LAN router or switch that uses fiber optic cable rather than ethernet/twisted-pair cable?
Yes, many switches and routers have slots for "SFP" or "SFP+" modules alongside regular copper Ethernet ports (e.g. 24xcopper + 4xSFP), and there are models which consist entirely of SFP slots as well.
(They use modules instead of having fiber optic ports built in, because different types of fiber connections exist and might even be mixed in the same network, and because the optics sometimes go bad and it's easier to swap a module than a whole switch.)
What sort of networking cards are available for "fiber to the device"?
Again there are PCIe Ethernet cards with SFP or SFP+ slots. There are also dedicated "media converter" boxes, with one copper Ethernet port and one SFP slot (or a built-in fiber optic port).
What is the driver and software support like on various operating systems for fiber?
As far as the OS cares, Ethernet over fiber optic works like regular Ethernet. The PCIe SFP card will have its own driver just like any Ethernet card would, but you don't need any special software other than that.
(Of course, there are other network types that use fiber optics – not just Ethernet – but you usually won't run them directly to your computer. For example, GPON which is used by many ISPs for FTTH probably does need extra configuration.)
When I google for "fiber router"
Well, on a LAN you primarily want a fiber switch anyway. Routers usually don't handle traffic inside the LAN – they just sit between the LAN switch and the WAN connection.
You'll get better results if you google for something like "switch 16x sfp" – most of the time, the product information page specifically mentions the module type (SFP for 1Gbps, SFP+ for 10Gbps, then there's QSFP, etc.)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to show Lists Fields stacked (not tabular)
I was wondering how to show a public view of my list data in a stacked form rather than tabular form.
That is, the fields in the list should be displayed top to bottom and not left to right... kind of the way an index page of a blog is displayed.
When I say 'displayed top to bottom' I mean:
Title:
<content of title field>
Technical Info:
<content of Tech Info field>
etc.
And not:
Title | Technical Info | etc.
<title field> | <tech info field> | etc.
Thanks
A:
You can define the different XSLT rendering template for the XsltListViewWebpart that renders the view: Overriding the presentation of an XSLT List View Web Part. Then you will be able to redesign the table for list items.
| {
"pile_set_name": "StackExchange"
} |
Q:
Django multiple models, one form
I have a model that looks like this:
class Movie(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200)
user = models.ForeignKey(User)
created_on = models.DateTimeField(default=datetime.datetime.now())
class Meta:
ordering = ['-title']
def __unicode__(self):
return self.title
class MovieScreener(models.Model):
screener_asset = models.FileField(upload_to='movies/screeners/')
movie = models.ForeignKey(Movie)
class MovieTrailer(models.Model):
trailer_asset = models.FileField(upload_to='movies/trailers/', blank=True, null=True)
description = models.TextField()
movie = models.ForeignKey(Movie)
class MoviePoster(models.Model):
poster_asset = models.FileField(upload_to='movies/posters/', blank=True, null=True)
movie = models.ForeignKey(Movie)
And my forms look like this:
class MovieForm(forms.ModelForm):
class Meta:
model = Movie
exclude = ('user','created_on')
class MovieScreenerForm(forms.ModelForm):
class Meta:
model = MovieScreener
exclude = ('movie',)
class MovieTrailerForm(forms.ModelForm):
class Meta:
model = MovieTrailer
exclude = ('movie',)
class MoviePosterForm(forms.ModelForm):
class Meta:
model = MoviePoster
exclude = ('movie',)
And here is my views.py (this is where it looks ugly)
@login_required
def create_movie(request, template_name="explore/create_movie.html"):
if request.method == 'POST':
movie_form = MovieForm(data=request.POST)
movie_screener_form = MovieScreenerForm(data=request.POST, files=request.FILES, prefix="a")
movie_trailer_form = MovieTrailerForm(data=request.POST, files=request.FILES, prefix="b")
movie_poster_form = MoviePosterForm(data=request.POST, files=request.FILES, prefix="c")
if movie_form.is_valid() and movie_screener_form.is_valid() and movie_trailer_form.is_valid():
movie_form.instance.user = request.user
movie = movie_form.save()
movie_screener_form.save(commit=False)
movie_screener_form.instance.movie = movie
movie_screener_form.save()
movie_trailer_form.save(commit=False)
movie_trailer_form.instance.movie = movie
movie_trailer_form.save()
movie_poster_form.save(commit=False)
movie_poster_form.instance.movie = movie
movie_poster_form.save()
url = urlresolvers.reverse('explore')
return redirect(url)
else:
movie_form = MovieForm(instance=request.user, label_suffix='')
movie_screener_form = MovieScreenerForm(prefix="a", label_suffix='')
movie_trailer_form = MovieTrailerForm(prefix="b", label_suffix='')
movie_poster_form = MoviePosterForm(prefix="c", label_suffix='')
context = RequestContext(request, locals())
return render_to_response(template_name, context)
My views.py seems very repetitive, is this the right way to do this or is there a better way to do this?
Thanks
J
A:
One thing you could do is move the setting of the movie instance on model forms that require it from the view to the form itself by passing it in as an argument when initializing the form. Here's an example of one implementation, but this can probably be made into a base form class that others can inherit from, saving you from having to do the override in each one individually. None of this code has been tested, I'm just thinking out loud...
class MovieScreenerForm(forms.ModelForm):
class Meta:
model = MovieScreener
exclude = ('movie',)
def __init__(self, movie, *args, **kwargs):
super(MovieScreen, self).__init__(*args, **kwargs)
self.movie = movie
def save(self, commit=True):
instance = super(MovieScreenerForm, self).save(commit=False)
instance.move = self.movie
instance.save()
A:
Can't really think of a way in terms of defining the models or forms, but you can cut down on some lines with the following.
mfs = [movie_screener_form, movie_trailer_form, movie_poster_form]
for mf in mfs:
mf.save(commit=False)
mf.instance.movie = movie
mf.save()
| {
"pile_set_name": "StackExchange"
} |
Q:
Forbidden Tripartite Graphs
I was looking at extremal graph theory. I have understood the proofs of upper bounds for the Zarankiewicz problem which basically states: What can you say about the edges of a graph with $n$ vertices and no $K_{s,t}$ subgraph. However, I was unable to find anything about the tripartite equivalent. Is anything known about the number of edges in an $n$ vertex graph that guarantee $K_{s,t,u}$ as a subgraph? Could someone suggest a reference?
For bipartite graphs, the number of edges that guarantee $K_{s,t}$ is of order $n^{2 - \frac{1}{\min(s,t)}}$. Is there a similar bound for tripartite graphs where the growth rate is determined by the size of the graph?
A:
The Erdos-Stone theorem is the reference you are looking for.
For every tripartite graph $G$, the number of edges in an $n$-vertex graph that guarantees $G$ as a subgraph is $n^2/4 + o(n^2)$. It is easy to see that $n^2/4$ is a lower bound (for $n$ even), since the complete bipartite graph does not contain $G$ as a subgraph.
By a result of Chvatal and Szemeredi, for the complete tripartite graph $G=K_3(t)$, which has $t$ vertices in each part, the upper bound can be written as $n^2/4 + n^{2-1/500t}$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Sum of series $\frac{x}{1-x^2} + \frac{x^2}{1-x^4} + \frac{x^4}{1-x^8} +\ldots$
The problem is to find the sum of series $$\frac{x}{1-x^2} + \frac{x^2}{1-x^4} + \frac{x^4}{1-x^8} +\ldots$$
to infinite terms, if $|x|<1$
I tried taking $\frac{x}{1-x^2}$ outside but could not solve it.
How to proceed further?
A:
If $|x|<1$, for any $k\in\mathbb{N}$ we have
$$ \frac{x^{2^k}}{1-x^{2^{k+1}}} = x^{2^k}+x^{3\cdot 2^k}+x^{5\cdot 2^k}+\ldots\tag{A}$$
but given any $n\in\mathbb{N}^+$, there is a unique representation of $n$ as $2^k\cdot d$, with $k\in\mathbb{N}$ and $d\in 2\mathbb{N}+1$. It follows that:
$$ \sum_{k\geq 0}\frac{x^{2^k}}{1-x^{2^{k+1}}} = \sum_{n\geq 1} x^n = \color{red}{\frac{x}{1-x}}.\tag{B}$$
A:
Notice $$\frac{y}{1-y^2} = \frac{(1+y)-1}{1-y^2} = \frac{1}{1-y} - \frac{1}{1-y^2}$$
The sum at hand is a telescoping one. The partial sums has the form:
$$\sum_{n=1}^p
\frac{x^{2^{n-1}}}{1-x^{2^n}} =
\sum_{n=1}^p
\left[\frac{1}{1-x^{2^{n-1}}} - \frac{1}{1-x^{2^n}}\right]
= \frac{1}{1-x} - \frac{1}{1-x^{2^p}}$$
When $|x| < 1$, $x^{2^p} \to 0$. This leads to
$$\sum_{n=1}^\infty
\frac{x^{2^{n-1}}}{1-x^{2^n}}
=
\lim_{p\to\infty}
\left[\frac{1}{1-x} - \frac{1}{1-x^{2^{p}}}\right]
= \frac{1}{1-x} - \frac{1}{1-0} = \frac{x}{1-x}$$
A:
If you combine the first two terms, you should end up with $$\frac{x(1+x^2)}{1-x^4}+\frac{x^2}{1-x^4}=\frac{x+x^2+x^3}{1-x^4}$$
If you combine the first three terms, you should end up with $$\frac{(x+x^2+x^3)(1+x^4)}{1-x^8}+\frac{x^4}{1-x^8}=\frac{x+x^2+x^3+x^4+x^5+x^6+x^7}{1-x^8}$$
Following this pattern, you will find out that the sum of the first $n$ terms is $$\frac{x}{1-x^{2^n}}\sum_{i=0}^{2^n-2}x^i$$
And you should be able to evaluate this sum, because it is the finite sum of a geometric progression. Taking the limit as $n\to\infty$ should yield your final answer of $$\frac{x}{1-x}$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Editing Devise user in one view and requiring password only for some fields
I am using Devise with Ruby on Rails and I would like to set up a view for editing user in which I have to provide current password only if I want to have a new password. In other words - if I want to change my name or birthdate, I can simply leave the password fields empty but if I want to change password, I would like to have standard devise behaviour.
My edit form looks like this:
I tried to allow update without password as written here by overriding update_resource method:
protected
def update_resource(resource, params)
resource.update_without_password(params)
end
However, without removing current_password from params.require(:user).permit(...) I receive the following error:
and I can't remove it from permitted params since I want to have it in case of password change.
What would be the way to do it? I am thinking of splitting the view and creating a new form for password editing along with a controller for password edit but I would prefer to have it all in one place.
A:
unknown attribute 'current_password' for User
The error makes sense as the current_password isn't one the default attribute available in the user that comes with the Devise. I had the similar issue and I've solved it with the help of attr_accessor
In user.rb model put attr_accessor :current_password. This resolves the error however you need to tweak the params like below to satisfy both cases.
def update_resource(resource, params)
if params[:user][:password].blank? && params[:user][:password_confirmation].blank?
resource.update_without_password(some_params)
else
resource.update_with_password(some_params)
end
end
def some_params
params.require(:user).permit(--all params here with current_password also included--)
end
| {
"pile_set_name": "StackExchange"
} |
Q:
Count Specific word on ArrayList
Imagine that you have this situation:
List<String> al = new ArrayList<>();
al.add("[I] am");
al.add("you are");
al.add("I");
al.add("[I] like java");
Now I want to count the sequence [I] (in this case it will count 2 times). The Link How to count the number of occurrences of an element in a List just pust one word, but on my example I have more than one, i.e, Collections.frequency(al, "[I]") do not work.
How can I achieve this preferentially using Java 8 ?
A:
Another way is to split the stream by space and then check whether chunk is equal to [I] e.g.
System.out.println(al.stream().map((w) -> w.split(" ")).flatMap(Arrays::stream).filter((i) ->i.equals("[I]")).count());
Using equals have advantage over contains because let say your list contains words like below
List<String> al = new ArrayList<>();
al.add("[I] am [I]");
al.add("you are");
al.add("I");
al.add("[I] like java");
This solution will return 3 as expected but the solution mentioned by Bohuslav Burghardt will return 2
| {
"pile_set_name": "StackExchange"
} |
Q:
Swift compiler error: segmentation fault: 11 on Archive
When archiving my iOS app prior to submission for App Store release, I get an error that says
Command failed due to signal: Segmentation fault: 11
Then there's a huge block of paths and whatnot and at the end is a mention of a function that I have in the app. Here's the function:
func matrixOperationRequiresScalar(operation: MatrixOperation) -> Bool {
switch operation {
case .Addition, .Subtraction, .Multiplication, .Division, .Negative, .Determinant, .Inverse, .Transpose, .EigenOps: return false
case .ScalarMultiplication, .ScalarDivision, .Power: return true
}
}
You can tell that operation is an enum and all cases are covered here.
What can I do to fix this?
A:
The switch you have in your code is missing the default case which is required in swfit. You can easily correct this :
func matrixOperationRequiresScalar(operation: MatrixOperation) -> Bool {
switch operation {
case .Addition, .Subtraction, .Multiplication, .Division, .Negative, .Determinant, .Inverse, .Transpose, .EigenOps: return false
case .ScalarMultiplication, .ScalarDivision, .Power: return true
default: return true
}
}
Source
| {
"pile_set_name": "StackExchange"
} |
Q:
Are nested enumerables bad practice?
In my view I'm generating a a number of restaurant menus that are divided into menu categories and within those categories are dishes. Right now I have my template setup as so:
<% @menus.each do |menu| %>
<h2><%= menu.name %></h2>
...
<% menu.categories.each do |category| %>
<h3><%= category.name %></h3>
...
<% category.dishes.each do |dish| %>
<p><%= dish.name %></p>
...
<% end %>
<% end %>
<% end %>
I was wondering what would be best practice when it comes to nesting multiple enumerables in this fashion? Aside from inserting this code into a partial, is there a better way to accomplish this without cluttering the view. Is it fine as is? Thanks.
A:
Apparently, the way your models are setup (Menu has_many categories, Category has_many dishes etc.), if you are to show all those information in the same view, you have no other way rather than just looping through them and show the required data in your view which is fine, IMHO. I don't see any problem with that.
Just one tip, while looping through the associated model's data, you just need to be careful that you always have the data present for the associated model attributes, otherwise you may get undefined method 'method_name' for nil:NilClass error for some of them. To avoid that problem, you can also use try. e.g.
menu.try(:name)
category.try(:name)
dish.try(:name)
etc.
That way, your view will not explode if some or any one of the associated model has no data present (i.e. nil).
| {
"pile_set_name": "StackExchange"
} |
Q:
JQuery Validation message shows on page load
I have the following view:
@model GRCWebApp.ViewModels.NewClubInterestsViewModel
@{
ViewBag.Title = "Add Club Interests";
}
<div class="col-md-10 col-offset-md-1">
<h2 class ="text-success">Add Club Interests for @Html.DisplayFor(model => model.Name)</h2>
</div>
@using (Html.BeginForm("NewInterests", "Club", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
<div class="row">
<div class="col-md-8">
<div class="well bs-component">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(x => Model.ClubId)
<div class="form-group">
<div class="col-md-10 col-md-offset-1">
<h3>Tick the areas your club is interested/runs events in</h3>
</div>
</div>
<div class="col-md-offset-1">
@for (int i = 0; i < Model.ClubTypeInterests.Count(); i++)
{
<div>
@Html.HiddenFor(x => Model.ClubTypeInterests[i].InterestId)
@Html.CheckBoxFor(x => Model.ClubTypeInterests[i].selected)
@Html.LabelFor(x => Model.ClubTypeInterests[i].InterestName, Model.ClubTypeInterests[i].InterestName)
</div>
}
</div>
<div class="form-group">
<div class="row">
<div class="col-md-offset-1 col-md-12">
<input type="submit" name="Submit" value="Next" class="btn btn-success btn-lg" /> to setup Online membership
<input type="submit" name="Submit" value="Complete" class="btn btn-warning btn-sm" /> to just provide online event entries
</div>
</div>
</div>
</div>
</div>
</div>
</div>
}
@using (Html.BeginForm("AddInterest", "Club"))
{
@Html.AntiForgeryToken()
<hr />
<div class="row">
<div class="col-md-8">
<div class="well bs-component">
<div class="form-group">
<div class="col-md-12 col-md-offset-1">
<h3>Not listed? - Add extras here</h3>
</div>
</div>
@Html.HiddenFor(model => model.ClubTypeId)
@Html.HiddenFor(model => model.ClubId)
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-inline">
<div class="form-group">
<div class="row col-md-offset-1 col-md-11">
<div class="col-md-4">
@Html.LabelFor(model => model.InterestName, htmlAttributes: new { @class = "control-label" })
@Html.EditorFor(model => model.InterestName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.InterestName, "", new { @class = "text-danger" })
</div>
<div class="col-md-5">
@Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label" })
@Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
</div>
<input type="submit" value="Add" class="btn btn-info" style="margin-top: 22px" />
</div>
</div>
</div>
</div>
</div>
</div>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
Overtime the page loads the Validation message shows for InterestName in the second form AddInterest.
The Get method for the whole form is:
[HttpGet]
public ActionResult NewInterests(NewClubInterestsViewModel model, int id)
{
//Find the Club and then pass its id to the ViewModel
var club = db.Clubs.Find(id);
//model.ClubId = club.ClubId ;
//Interests List
IEnumerable<Interest> allExistingInterests;
//Generate a list of the interests that apply to that type of club
using (ApplicationDbContext context = new ApplicationDbContext())
{
allExistingInterests = context.Interests
.Where(s => s.ClubTypeId == club.ClubTypeId)
.OrderBy(s => s.InterestName)
.ToList();
}
IEnumerable<int> clubInterestIds = club.ClubInterests.Select(x => x.InterestId).ToList();
//Generate the ViewModel with the appropriate Interests
var viewModel = new NewClubInterestsViewModel
{
ClubId = club.ClubId,
Name = club.Name,
ClubTypeId = club.ClubTypeId,
ClubTypeInterests =
allExistingInterests.Select(
x => new ClubInterestsViewModel { InterestId = x.InterestId, InterestName = x.InterestName, selected = clubInterestIds.Contains(x.InterestId) }).ToArray()
};
return View(viewModel);
}
What do I need to do to stop the validation message showing on load?
A:
Remove the NewClubInterestsViewModel model parameter from your GET method. It should be just
public ActionResult NewInterests(int id)
The first step in the model binding process is that instances of your parameters are initialized and then its properties are set based on form values, route values, query string values etc. In your case there are no values to set, so the properties of your model are their defaults, but because you have validation attributes on your properties, validation fails and errors are added to ModelState which are then displayed in the view.
| {
"pile_set_name": "StackExchange"
} |
Q:
Ext.util.Format.number - how do I preserve decimal places when adding thousand separator?
I've got a bunch of numbers in different units of measure requiring different decimal precision. They all are rendered in the same component. In this component - I need to format numbers to include a thousand separator.
This is how I'm currently doing it
Ext.util.Format.number(floatValue.toFixed(this.euStore.getById(euId).get('DecimalPrecision')), '0,000.00');
Where this.euStore.getById(euId).get('DecimalPrecision') returns anywhere from 0 - 4.
I need to preserve these decimal places when Ext.util.Format.number is called to add in the thousand seperator, because it always gets 2 decimal places using the current format, '0,000.00'
Is there a way to do this with the built in number formatter or do I need to write my own function? Thanks!
A:
So I ended up figuring it out shortly after posting. I saved the decimal precision in a var
var decimalPrecision = this.euStore.getById(euId).get('DecimalPrecision')
and then built the format string using Ext.String.repeat to repeat the decimal places based on the precision value.
var format = '0,000.' + Ext.String.repeat('0', decimalPrecision);
then passed that to
Ext.util.Format.number(myNumber, format)
to get the result I needed. Thanks for your suggestions!
| {
"pile_set_name": "StackExchange"
} |
Q:
ANTLR Is takes one line of tokens as a single token
I'm new to ANTLR and I tried to write a simple parser. I used a valid rules, but when I run the TestRig (grun) with -gui argument on 'var' rule and entered this:
var myVar = 13
the debugger tolds me that: line 1:0 mismatched input 'var myVar = 13' expecting 'var'
I can't get what is wrong with it..
Here's the code:
grammar Leaf;
WS: (' '|'\t'|'\n'|'\r')+ -> skip;
NUM: ('0'..'9') ('0'..'9'|'.')*;
CHAR: ('a'..'z'|'A'..'Z');
ID: CHAR (CHAR|NUM)*;
BOOL: ('true'|'false');
STRING: ~('\r'|'\n'|'"')+;
type: 'int'|'byte'|'float'|'double'|'decimal'|'char'|'bool'|'tuple'|'string'|'type';
value: NUM|BOOL|('[' (value ',')+ ']')|('\'' CHAR '\'')|('"' STRING '"')|('(' (type ',')+ ')')|type;
var: 'var' ID('[]')? (':' type)? '=' (type|value)?;
Thanks for feedback!
A:
Lexer rules in ANTLR are greedy. Because of that, the rule STRING:
STRING: ~('\r'|'\n'|'"')+;
consumes your entire input.
What you need to do is remove the double quotes from your value parser rule and include them in your lexer rule:
grammar Leaf;
var
: 'var' ID ('[' ']')? (':' type)? '=' (type | value)?
;
value
: NUM
| BOOL
| '[' value (',' value)* ']'
| CHAR
| STRING
| '(' type (',' type)* ')'
| type
;
type
: 'int'
| 'byte'
| 'float'
| 'double'
| 'decimal'
| 'char'
| 'bool'
| 'tuple'
| 'string'
| 'type'
;
WS : (' '|'\t'|'\n'|'\r')+ -> skip;
BOOL : ('true' | 'false');
NUM : DIGIT+ ('.' DIGIT*)?;
STRING : '"' ~('\r'|'\n'|'"')* '"';
CHAR : '\'' LETTER '\'';
ID : LETTER (LETTER | DIGIT)*;
fragment LETTER : [a-zA-Z];
fragment DIGIT : [0-9];
| {
"pile_set_name": "StackExchange"
} |
Q:
Could high-rep users help with clearing comment flags?
I have to start this question with a simple assumption: there are a lot of comment flags raised by users:
We get a lot of comment flags. A lot. We see a lot of comments. We delete comments all the time.
I also realise that clearing comment flags is, probably, one of the easier mod-tasks that exist, given that:
[moderators] get two [practical] choices when a comment is flagged:
Delete
Dismiss (do nothing)
Both quotes from George Stocker's answer here: https://meta.stackoverflow.com/a/278823/82548
Now, despite that this is a relatively easy and quickly-handled task there may be no need for this feature-request; I would argue that the simple emphasis, and repetition of, 'a lot' in the above quote suggests that reducing the comment-flag queue would be of benefit, simply because:
It would reduce some of the workload on the mods (a simple task performed 'a lot' of times should be distributed further, if possible),
It would free moderators up to deal with other, more serious, flags and problems.
Point 2, of course, could be countered by the simple fact that moderators may regard the flag-queue as a break, or light-relief, from the 'more serious' flags; but I'd still like us to be able to help, if possible.
My thoughts on this, in terms of limitations, would be:
A flag should be raised by another user before that comment can be deleted by a high-rep (non-moderator) user, in order to prevent us simply deleting comments with which we disagree.
In the event that a flagged comment is part of a conversation that (we feel) should be addressed, we should flag those other comments; we should not be (at least in the short term) be able to nuke the whole thread.
Any comment-based action that we take should be available for review (by moderators only, or peers as well) and, ideally, reversible (at the very least a comment that we agree to delete should be un-delete-able).
This list could surely do with expanding, I'd imagine.
As to the level of rep required to have delete powers over comments, I'd suggest it should be high; perhaps >50k; and ideally for those users with a sufficiently high ratio (perhaps in the region of 9:1, so a 90% accuracy?) of 'helpful' to 'declined' flags; on the premise that a history of accurately raising flags should demonstrate an understanding of what should, and should not, be flagged and deleted.
With regards to BoltClock's comment (below):
Remember that it takes no more than 3 comment flags on any single comment to cause it to be deleted without moderator intervention. A lot (lol) of these flags resolve themselves fairly quickly.
I hadn't forgotten, but while this clears many problems very quickly, I know I occasionally come across offensive comments on relatively old questions/answers, which may not attract flags as quickly as a new question that gets to sit on the front page for a few minutes.
This request is to supplement the existing strategies/solutions, not to replace them.
Further, to address Sunshine's comment (again, below):
Comments are sensitive and situations decline rapidly in comments. It's better if mods handle such sensitive disruptive content, instead of high-rep users.
I disagree, the reason that 'situations decline rapidly in comments,' I suspect (I have no statistics to back this up, it's purely an assumption) is because while the initiating comments may be flagged by one or two users, the lack of a third flag leaves those comments in sight for some time because of the small number of moderators versus the giant stack of comment-flags.
I have only one data-point to refer to, and that's based on my raising a flag, at 02:00, December 10th, and the closure of the question (and deletion of comments, which I'd flagged), by bluefeet, at 11:08; giving a turn-around time of over eight hours (in this one, statistically-irrelevant, data-point).
So, for eight hours a deteriorating situation can exist without review, until such a time as the question is seen by others and third-flags are cast. With community-members participating, this seems unlikely to happen.
Similarly, while moderators have greater authority, and power, over the community we, the community, should be willing to participate in our own governance. And it's important to remember that when a comment is flagged (as whatever) we are not simply a rubber-stamp for that comment's deletion, we should be able to dismiss flags (or skip, as in the review queues).
A:
Please and thank you.
There are very few comments that actually need a diamond moderator's intervention:
Abusive (rude or offensive) comments (or a pattern of abusive comments)
Custom Comments asking that the thread be nuked
Most everything else we see:
Not constructive
Obsolete
Chatty
Can (and should) be handled by the community.
One of the issues that keeps comment moderation from being turned over to the community is that once comments are deleted, we can no longer easily find them.
We do have the ability to see deleted comments by a user, but as @BoltClock points out, it is un searchable, unwieldy, and utterly devoid of context.
I think this is a great idea -- this should not be on the moderator's plate alone, and we should only be involved when we'd need to take an action more than simply deleting the flagged comment.
To make this happen, we'd first need better tooling regarding deleted comments to have evidence towards abusive behavior. It'd also be nice if a custom flag was raised for moderator attention when a user has a high number of community flagged and deleted comments.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why won't these two UIViews fade in and out using my animation?
I have two views that I would like to fade in and out. I tried the code below, but it does not seem to work, the transition only happens once. Can anyone tell me the right way to accomplish what I am trying to do?
vView1.alpha = 0.0;
vView2.alpha = 1.0;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.55];
[UIView setAnimationRepeatCount:0];
vView1.alpha = (vView1 == 0.0) ? 1.0 : 0.0;
vView2.alpha = (vView2 == 0.0) ? 1.0 : 0.0;
[UIView commitAnimations];
I set this up in viewWillAppear, in case that matters.
From the Apple Doc:
animationRepeatCount
Specifies the number of times to repeat the animation.
@property(nonatomic) NSInteger animationRepeatCount
Discussion
The default value is 0, which specifies to repeat the animation indefinitely.
Availability
Available in iOS 2.0 and later.
Declared In
UIImageView.h
A:
The UIImageView class also has an animationRepeatCount attribute, when set to 0 means "repeat indefinitely". The UIView class's attribute when set to 0 means "repeat once."
You're using UIView animation.
If you want to repeat this animation indefinitely, you might try setting a selector to execute when the animation finishes using setAnimationDidStopSelector: that simply calls your function to do the animation. Remember to also call setAnimationDelegate: with a value of self so that your selector actually gets invoked.
| {
"pile_set_name": "StackExchange"
} |
Q:
Scan a document and convert to key text
I am trying to find a way to scan a "paper document" with my scanner and then, trying with a programming language, like C# or C++, to figure out what letters are printed on the page to convert them to normal text.
In other words, I am trying to implement a "key from scanned image" function in order to convert a paper document to an electronic document to be opened with something like Notepad. Can anyone give me some tips, please?
A:
It sounds like you're trying to do is something like OCR, or Optical Character Recognition. It's certainly not a simple field of study, but this wiki page should get you started with the concepts and what it is:
https://en.wikipedia.org/wiki/Optical_character_recognition
| {
"pile_set_name": "StackExchange"
} |
Q:
A way to determine browser width in PHP without javascript?
First off is there one? Or would I have to use javascript?
I'd like to be able to make changes to which CSS is used, so frex I could load smaller fonts for a mobile device, or whatever.
A:
Unfortunately there is no way to detect the users resolution with PHP only. If you use Javascript, you could set this value in a cookie, and all subsequent requests could check the value of that cookie. This seems to be a pretty popular method for those working with this issue.
You could also run a small javascript from the page that checks to see if a resolution-cookie is set. If it's not, it sends an asynchronous request to the server containing the screen resolution. The server determines which CSS file to use by this value, and sends its path back to the javascript. A cookie is then set to indicate resolution has been determined, and the css file is subsequently loaded (via javascript) into the page. All future requests would cease assuming they're contingent upon the resolution cookie.
A:
Pure HTML and CSS trick to get the width of the display. This will get you within 10 pixels. It highlights in red down to the display width. The first black on white number should be the display width:
<!DOCTYPE HTML>
<html>
<head>
<title>Dart Foods</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link href='http://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>
<STYLE type="text/css">
hr {background-color: red;border: 1px solid blue;}
@media (max-width: 1920px) {#d1920{background-color: red;}}
@media (max-width: 1910px) {#d1910{background-color: red;}}
@media (max-width: 1900px) {#d1900{background-color: red;}}
@media (max-width: 1890px) {#d1890{background-color: red;}}
@media (max-width: 1880px) {#d1880{background-color: red;}}
@media (max-width: 1870px) {#d1870{background-color: red;}}
@media (max-width: 1860px) {#d1860{background-color: red;}}
@media (max-width: 1850px) {#d1850{background-color: red;}}
@media (max-width: 1840px) {#d1840{background-color: red;}}
@media (max-width: 1830px) {#d1830{background-color: red;}}
@media (max-width: 1820px) {#d1820{background-color: red;}}
@media (max-width: 1810px) {#d1810{background-color: red;}}
@media (max-width: 1800px) {#d1800{background-color: red;}}
@media (max-width: 1790px) {#d1790{background-color: red;}}
@media (max-width: 1780px) {#d1780{background-color: red;}}
@media (max-width: 1770px) {#d1770{background-color: red;}}
@media (max-width: 1760px) {#d1760{background-color: red;}}
@media (max-width: 1750px) {#d1750{background-color: red;}}
@media (max-width: 1740px) {#d1740{background-color: red;}}
@media (max-width: 1730px) {#d1730{background-color: red;}}
@media (max-width: 1720px) {#d1720{background-color: red;}}
@media (max-width: 1710px) {#d1710{background-color: red;}}
@media (max-width: 1700px) {#d1700{background-color: red;}}
@media (max-width: 1690px) {#d1690{background-color: red;}}
@media (max-width: 1680px) {#d1680{background-color: red;}}
@media (max-width: 1670px) {#d1670{background-color: red;}}
@media (max-width: 1660px) {#d1660{background-color: red;}}
@media (max-width: 1650px) {#d1650{background-color: red;}}
@media (max-width: 1640px) {#d1640{background-color: red;}}
@media (max-width: 1630px) {#d1630{background-color: red;}}
@media (max-width: 1620px) {#d1620{background-color: red;}}
@media (max-width: 1610px) {#d1610{background-color: red;}}
@media (max-width: 1600px) {#d1600{background-color: red;}}
@media (max-width: 1590px) {#d1590{background-color: red;}}
@media (max-width: 1580px) {#d1580{background-color: red;}}
@media (max-width: 1570px) {#d1570{background-color: red;}}
@media (max-width: 1560px) {#d1560{background-color: red;}}
@media (max-width: 1550px) {#d1550{background-color: red;}}
@media (max-width: 1540px) {#d1540{background-color: red;}}
@media (max-width: 1530px) {#d1530{background-color: red;}}
@media (max-width: 1520px) {#d1520{background-color: red;}}
@media (max-width: 1510px) {#d1510{background-color: red;}}
@media (max-width: 1500px) {#d1500{background-color: red;}}
@media (max-width: 1490px) {#d1490{background-color: red;}}
@media (max-width: 1480px) {#d1480{background-color: red;}}
@media (max-width: 1470px) {#d1470{background-color: red;}}
@media (max-width: 1460px) {#d1460{background-color: red;}}
@media (max-width: 1450px) {#d1450{background-color: red;}}
@media (max-width: 1440px) {#d1440{background-color: red;}}
@media (max-width: 1430px) {#d1430{background-color: red;}}
@media (max-width: 1420px) {#d1420{background-color: red;}}
@media (max-width: 1410px) {#d1410{background-color: red;}}
@media (max-width: 1400px) {#d1400{background-color: red;}}
@media (max-width: 1390px) {#d1390{background-color: red;}}
@media (max-width: 1380px) {#d1380{background-color: red;}}
@media (max-width: 1370px) {#d1370{background-color: red;}}
@media (max-width: 1360px) {#d1360{background-color: red;}}
@media (max-width: 1350px) {#d1350{background-color: red;}}
@media (max-width: 1340px) {#d1340{background-color: red;}}
@media (max-width: 1330px) {#d1330{background-color: red;}}
@media (max-width: 1320px) {#d1320{background-color: red;}}
@media (max-width: 1310px) {#d1310{background-color: red;}}
@media (max-width: 1300px) {#d1300{background-color: red;}}
@media (max-width: 1290px) {#d1290{background-color: red;}}
@media (max-width: 1280px) {#d1280{background-color: red;}}
@media (max-width: 1270px) {#d1270{background-color: red;}}
@media (max-width: 1260px) {#d1260{background-color: red;}}
@media (max-width: 1250px) {#d1250{background-color: red;}}
@media (max-width: 1240px) {#d1240{background-color: red;}}
@media (max-width: 1230px) {#d1230{background-color: red;}}
@media (max-width: 1220px) {#d1220{background-color: red;}}
@media (max-width: 1210px) {#d1210{background-color: red;}}
@media (max-width: 1200px) {#d1200{background-color: red;}}
@media (max-width: 1190px) {#d1190{background-color: red;}}
@media (max-width: 1180px) {#d1180{background-color: red;}}
@media (max-width: 1170px) {#d1170{background-color: red;}}
@media (max-width: 1160px) {#d1160{background-color: red;}}
@media (max-width: 1150px) {#d1150{background-color: red;}}
@media (max-width: 1140px) {#d1140{background-color: red;}}
@media (max-width: 1130px) {#d1130{background-color: red;}}
@media (max-width: 1120px) {#d1120{background-color: red;}}
@media (max-width: 1110px) {#d1110{background-color: red;}}
@media (max-width: 1100px) {#d1100{background-color: red;}}
@media (max-width: 1090px) {#d1090{background-color: red;}}
@media (max-width: 1080px) {#d1080{background-color: red;}}
@media (max-width: 1070px) {#d1070{background-color: red;}}
@media (max-width: 1060px) {#d1060{background-color: red;}}
@media (max-width: 1050px) {#d1050{background-color: red;}}
@media (max-width: 1040px) {#d1040{background-color: red;}}
@media (max-width: 1030px) {#d1030{background-color: red;}}
@media (max-width: 1020px) {#d1020{background-color: red;}}
@media (max-width: 1010px) {#d1010{background-color: red;}}
@media (max-width: 1000px) {#d1000{background-color: red;}}
@media (max-width: 990px) {#d990{background-color: red;}}
@media (max-width: 980px) {#d980{background-color: red;}}
@media (max-width: 970px) {#d970{background-color: red;}}
@media (max-width: 960px) {#d960{background-color: red;}}
@media (max-width: 950px) {#d950{background-color: red;}}
@media (max-width: 940px) {#d940{background-color: red;}}
@media (max-width: 930px) {#d930{background-color: red;}}
@media (max-width: 920px) {#d920{background-color: red;}}
@media (max-width: 910px) {#d910{background-color: red;}}
@media (max-width: 900px) {#d900{background-color: red;}}
@media (max-width: 890px) {#d890{background-color: red;}}
@media (max-width: 880px) {#d880{background-color: red;}}
@media (max-width: 870px) {#d870{background-color: red;}}
@media (max-width: 860px) {#d860{background-color: red;}}
@media (max-width: 850px) {#d850{background-color: red;}}
@media (max-width: 840px) {#d840{background-color: red;}}
@media (max-width: 830px) {#d830{background-color: red;}}
@media (max-width: 820px) {#d820{background-color: red;}}
@media (max-width: 810px) {#d810{background-color: red;}}
@media (max-width: 800px) {#d800{background-color: red;}}
@media (max-width: 790px) {#d790{background-color: red;}}
@media (max-width: 780px) {#d780{background-color: red;}}
@media (max-width: 770px) {#d770{background-color: red;}}
@media (max-width: 760px) {#d760{background-color: red;}}
@media (max-width: 750px) {#d750{background-color: red;}}
@media (max-width: 740px) {#d740{background-color: red;}}
@media (max-width: 730px) {#d730{background-color: red;}}
@media (max-width: 720px) {#d720{background-color: red;}}
@media (max-width: 710px) {#d710{background-color: red;}}
@media (max-width: 700px) {#d700{background-color: red;}}
@media (max-width: 690px) {#d690{background-color: red;}}
@media (max-width: 680px) {#d680{background-color: red;}}
@media (max-width: 670px) {#d670{background-color: red;}}
@media (max-width: 660px) {#d660{background-color: red;}}
@media (max-width: 650px) {#d650{background-color: red;}}
@media (max-width: 640px) {#d640{background-color: red;}}
@media (max-width: 630px) {#d630{background-color: red;}}
@media (max-width: 620px) {#d620{background-color: red;}}
@media (max-width: 610px) {#d610{background-color: red;}}
@media (max-width: 600px) {#d600{background-color: red;}}
@media (max-width: 590px) {#d590{background-color: red;}}
@media (max-width: 580px) {#d580{background-color: red;}}
@media (max-width: 570px) {#d570{background-color: red;}}
@media (max-width: 560px) {#d560{background-color: red;}}
@media (max-width: 550px) {#d550{background-color: red;}}
@media (max-width: 540px) {#d540{background-color: red;}}
@media (max-width: 530px) {#d530{background-color: red;}}
@media (max-width: 520px) {#d520{background-color: red;}}
@media (max-width: 510px) {#d510{background-color: red;}}
@media (max-width: 500px) {#d500{background-color: red;}}
@media (max-width: 490px) {#d490{background-color: red;}}
@media (max-width: 480px) {#d480{background-color: red;}}
@media (max-width: 470px) {#d470{background-color: red;}}
@media (max-width: 460px) {#d460{background-color: red;}}
@media (max-width: 450px) {#d450{background-color: red;}}
@media (max-width: 440px) {#d440{background-color: red;}}
@media (max-width: 430px) {#d430{background-color: red;}}
@media (max-width: 420px) {#d420{background-color: red;}}
@media (max-width: 410px) {#d410{background-color: red;}}
@media (max-width: 400px) {#d400{background-color: red;}}
@media (max-width: 390px) {#d390{background-color: red;}}
@media (max-width: 380px) {#d380{background-color: red;}}
@media (max-width: 370px) {#d370{background-color: red;}}
@media (max-width: 360px) {#d360{background-color: red;}}
@media (max-width: 350px) {#d350{background-color: red;}}
@media (max-width: 340px) {#d340{background-color: red;}}
@media (max-width: 330px) {#d330{background-color: red;}}
@media (max-width: 320px) {#d320{background-color: red;}}
@media (max-width: 310px) {#d310{background-color: red;}}
@media (max-width: 300px) {#d300{background-color: red;}}
@media (max-width: 290px) {#d290{background-color: red;}}
@media (max-width: 280px) {#d280{background-color: red;}}
@media (max-width: 270px) {#d270{background-color: red;}}
@media (max-width: 260px) {#d260{background-color: red;}}
@media (max-width: 250px) {#d250{background-color: red;}}
@media (max-width: 240px) {#d240{background-color: red;}}
@media (max-width: 230px) {#d230{background-color: red;}}
@media (max-width: 220px) {#d220{background-color: red;}}
@media (max-width: 210px) {#d210{background-color: red;}}
@media (max-width: 200px) {#d200{background-color: red;}}
@media (max-width: 190px) {#d190{background-color: red;}}
@media (max-width: 180px) {#d180{background-color: red;}}
@media (max-width: 170px) {#d170{background-color: red;}}
@media (max-width: 160px) {#d160{background-color: red;}}
@media (max-width: 150px) {#d150{background-color: red;}}
@media (max-width: 140px) {#d140{background-color: red;}}
@media (max-width: 130px) {#d130{background-color: red;}}
@media (max-width: 120px) {#d120{background-color: red;}}
@media (max-width: 110px) {#d110{background-color: red;}}
@media (max-width: 100px) {#d100{background-color: red;}}
@media (max-width: 90px) {#d90{background-color: red;}}
@media (max-width: 80px) {#d80{background-color: red;}}
@media (max-width: 70px) {#d70{background-color: red;}}
@media (max-width: 60px) {#d60{background-color: red;}}
@media (max-width: 50px) {#d50{background-color: red;}}
@media (max-width: 40px) {#d40{background-color: red;}}
@media (max-width: 30px) {#d30{background-color: red;}}
@media (max-width: 20px) {#d20{background-color: red;}}
@media (max-width: 10px) {#d10{background-color: red;}}
</STYLE>
</head>
<body>
Your width is approximately:
<hr>
<div id="d1920" >1920</div>
<div id="d1910" >1910</div>
<div id="d1900" >1900</div>
<div id="d1890">1890</div>
<div id="d1880">1880</div>
<div id="d1870">1870</div>
<div id="d1860">1860</div>
<div id="d1850">1850</div>
<div id="d1840">1840</div>
<div id="d1830">1830</div>
<div id="d1820">1820</div>
<div id="d1810">1810</div>
<div id="d1800">1800</div>
<div id="d1790">1790</div>
<div id="d1780">1780</div>
<div id="d1770">1770</div>
<div id="d1760">1760</div>
<div id="d1750">1750</div>
<div id="d1740">1740</div>
<div id="d1730">1730</div>
<div id="d1720">1720</div>
<div id="d1710">1710</div>
<div id="d1700">1700</div>
<div id="d1690">1690</div>
<div id="d1680">1680</div>
<div id="d1670">1670</div>
<div id="d1660">1660</div>
<div id="d1650">1650</div>
<div id="d1640">1640</div>
<div id="d1630">1630</div>
<div id="d1620">1620</div>
<div id="d1610">1610</div>
<div id="d1600">1600</div>
<div id="d1590">1590</div>
<div id="d1580">1580</div>
<div id="d1570">1570</div>
<div id="d1560">1560</div>
<div id="d1550">1550</div>
<div id="d1540">1540</div>
<div id="d1530">1530</div>
<div id="d1520">1520</div>
<div id="d1510">1510</div>
<div id="d1500">1500</div>
<div id="d1490">1490</div>
<div id="d1480">1480</div>
<div id="d1470">1470</div>
<div id="d1460">1460</div>
<div id="d1450">1450</div>
<div id="d1440">1440</div>
<div id="d1430">1430</div>
<div id="d1420">1420</div>
<div id="d1410">1410</div>
<div id="d1400">1400</div>
<div id="d1390">1390</div>
<div id="d1380">1380</div>
<div id="d1370">1370</div>
<div id="d1360">1360</div>
<div id="d1350">1350</div>
<div id="d1340">1340</div>
<div id="d1330">1330</div>
<div id="d1320">1320</div>
<div id="d1310">1310</div>
<div id="d1300">1300</div>
<div id="d1290">1290</div>
<div id="d1280">1280</div>
<div id="d1270">1270</div>
<div id="d1260">1260</div>
<div id="d1250">1250</div>
<div id="d1240">1240</div>
<div id="d1230">1230</div>
<div id="d1220">1220</div>
<div id="d1210">1210</div>
<div id="d1200">1200</div>
<div id="d1190">1190</div>
<div id="d1180">1180</div>
<div id="d1170">1170</div>
<div id="d1160">1160</div>
<div id="d1150">1150</div>
<div id="d1140">1140</div>
<div id="d1130">1130</div>
<div id="d1120">1120</div>
<div id="d1110">1110</div>
<div id="d1100">1100</div>
<div id="d1090">1090</div>
<div id="d1080">1080</div>
<div id="d1070">1070</div>
<div id="d1060">1060</div>
<div id="d1050">1050</div>
<div id="d1040">1040</div>
<div id="d1030">1030</div>
<div id="d1020">1020</div>
<div id="d1010">1010</div>
<div id="d1000">1000</div>
<div id="d990">990</div>
<div id="d980">980</div>
<div id="d970">970</div>
<div id="d960">960</div>
<div id="d950">950</div>
<div id="d940">940</div>
<div id="d930">930</div>
<div id="d920">920</div>
<div id="d910">910</div>
<div id="d900">900</div>
<div id="d890">890</div>
<div id="d880">880</div>
<div id="d870">870</div>
<div id="d860">860</div>
<div id="d850">850</div>
<div id="d840">840</div>
<div id="d830">830</div>
<div id="d820">820</div>
<div id="d810">810</div>
<div id="d800">800</div>
<div id="d790">790</div>
<div id="d780">780</div>
<div id="d770">770</div>
<div id="d760">760</div>
<div id="d750">750</div>
<div id="d740">740</div>
<div id="d730">730</div>
<div id="d720">720</div>
<div id="d710">710</div>
<div id="d700">700</div>
<div id="d690">690</div>
<div id="d680">680</div>
<div id="d670">670</div>
<div id="d660">660</div>
<div id="d650">650</div>
<div id="d640">640</div>
<div id="d630">630</div>
<div id="d620">620</div>
<div id="d610">610</div>
<div id="d600">600</div>
<div id="d590">590</div>
<div id="d580">580</div>
<div id="d570">570</div>
<div id="d560">560</div>
<div id="d550">550</div>
<div id="d540">540</div>
<div id="d530">530</div>
<div id="d520">520</div>
<div id="d510">510</div>
<div id="d500">500</div>
<div id="d490">490</div>
<div id="d480">480</div>
<div id="d470">470</div>
<div id="d460">460</div>
<div id="d450">450</div>
<div id="d440">440</div>
<div id="d430">430</div>
<div id="d420">420</div>
<div id="d410">410</div>
<div id="d400">400</div>
<div id="d390">390</div>
<div id="d380">380</div>
<div id="d370">370</div>
<div id="d360">360</div>
<div id="d350">350</div>
<div id="d340">340</div>
<div id="d330">330</div>
<div id="d320">320</div>
<div id="d310">310</div>
<div id="d300">300</div>
<div id="d290">290</div>
<div id="d280">280</div>
<div id="d270">270</div>
<div id="d260">260</div>
<div id="d250">250</div>
<div id="d240">240</div>
<div id="d230">230</div>
<div id="d220">220</div>
<div id="d210">210</div>
<div id="d200">200</div>
<div id="d190">190</div>
<div id="d180">180</div>
<div id="d170">170</div>
<div id="d160">160</div>
<div id="d150">150</div>
<div id="d140">140</div>
<div id="d130">130</div>
<div id="d120">120</div>
<div id="d110">110</div>
<div id="d100">100</div>
<div id="d90">90</div>
<div id="d80">80</div>
<div id="d70">70</div>
<div id="d60">60</div>
<div id="d50">50</div>
<div id="d40">40</div>
<div id="d30">30</div>
<div id="d20">20</div>
<div id="d10">10</div>
<hr>
</body>
</html>
A:
This may be of some use if you don't want to use any JavaScript:
http://www.w3.org/TR/CSS2/media.html#media-types
| {
"pile_set_name": "StackExchange"
} |
Q:
Multiple instances of the same ResourceDictionary
I have found this post about improving performance of ResourceDictionaries on the web, but the problem is that it's pretty old (2011). I was thinking about implementing something like this, but I'm wondering if Microsoft has not fixed this in the last releases of .NET Framework. I have few questions regarding this topic, which, I hope someone here can give an answer to:
Is .NET Framework 4.6.1 still managing ResourceDictionaries by making multiple instances of them, one for every time they are assigned to a control?
Is it even an issue when I have for example style "CustomButtonStyle" in my ResourceDictionary called "ButtonStyles" in assembly called "StylesAssembly", which is then referenced in App.xaml of an application, that has 20 Buttons with CustomButtonStyle assigned to them?
Do I understand it correctly, that in the case above, there will be 20 instances of "ButtonStyles" ResourceDictionary?
A:
Thanks @mm8 for posting your answer. It's 100% correct, I just want to post my own answer, because I found out something interesting, that can be useful for someone else.
The answer is: ResourceDictionary instance will be created just once if referenced in the application (no matter many controls uses its styles), BUT it will be instantiated again for every time it is referenced in another ResourceDictionary that is also used in the application.
So to give you example of this case let's say we have the following structure:
- StylesAssembly.dll
- ButtonResourceDictionary.xaml
- CustomButtonResourceDictionary.xaml
- Application.exe
- App.xaml
- MainWindow.xaml
ButtonResourceDictionary.xaml has the following code:
<Style x:Key="DefaultButtonStyle" TargetType="{x:Type Button}">
<!-- Some setters -->
</Style>
CustomButtonResourceDictionary.xaml has the following code, which uses ButtonResourceDictionary.xaml:
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="ButtonResourceDictionary.xaml" />
</ResourceDictionary.MergedDictionaries>
<Style x:Key="CustomButtonStyle" TargetType="{x:Type Button}" BasedOn="{StaticResource DefaultButtonStyle}">
<!-- Some setters -->
</Style>
Application.exe has a reference to StylesAssembly.dll and there is a following code in the App.xaml:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/StylesAssembly;component/ButtonResourceDictionary.xaml" />
<ResourceDictionary Source="pack://application:,,,/StylesAssembly;component/CustomButtonResourceDictionary.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
Now if our MainWindow.xaml has something like this in it, the ButtonResourceDictionary.xaml will have only one instance:
<StackPanel>
<Button Style="{StaticResource DefaultButtonStyle}" />
<Button Style="{StaticResource DefaultButtonStyle}" />
<Button Style="{StaticResource DefaultButtonStyle}" />
<Button Style="{StaticResource DefaultButtonStyle}" />
<Button Style="{StaticResource DefaultButtonStyle}" />
</StackPanel>
but if our MainWindow.xaml has something like this in it, the CustomButtonResourceDictionary.xaml will have one instance, but the ButtonResourceDictionary.xaml will have two instances:
<StackPanel>
<Button Style="{StaticResource DefaultButtonStyle}" />
<Button Style="{StaticResource DefaultButtonStyle}" />
<Button Style="{StaticResource CustomButtonStyle}" />
<Button Style="{StaticResource CustomButtonStyle}" />
<Button Style="{StaticResource CustomButtonStyle}" />
</StackPanel>
It happens because first two Buttons use style DefaultButtonStyle from ButtonResourceDictionary.xaml, but another three Buttons use style CustomButtonStyle which comes from CustomButtonResourceDictionary.xaml, which merges ButtonResourceDictionary.xaml in its code.
| {
"pile_set_name": "StackExchange"
} |
Q:
Could not open ServletContext resource [/] when upgrade spring-boot-actuator 1.2.5.RELEASE
I am using spring-boot-actuator dependency with version 1.1.2 with non spring boot application, now I want to upgrade to version 1.2.5.RELEASE to use the default chipped health endpoint in my application.
When I upgrade to 1.2.5.RELEASE the application fails to start up with error
Could not open ServletContext resource [/<NONE>]
I can see the configurationlocation is being set as NONE in AbstractRefreshableConfigApplicationContext so in the XmlBeanDefinitionReader it fails with this error.
Any help is appreciated.
here is the full stack trace:
[INFO ] 2017-11-30 16:25:47.714 [RMI TCP Connection(5)-127.0.0.1] c.w.w.u.s.MyPropertiesInitializer - Registering PropertySource my-eventhub.config with Spring Environment
[ERROR] 2017-11-30 16:31:13.914 [RMI TCP Connection(5)-127.0.0.1] o.s.w.c.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/<NONE>]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/<NONE>]
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:344) ~[spring-beans-4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304) ~[spring-beans-4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181) ~[spring-beans-4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217) ~[spring-beans-4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188) ~[spring-beans-4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129) ~[spring-context-4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:614) ~[spring-context-4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:515) ~[spring-context-4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:443) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:325) [spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107) [spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5003) [catalina.jar:7.0.64]
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5517) [catalina.jar:7.0.64]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [catalina.jar:7.0.64]
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901) [catalina.jar:7.0.64]
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877) [catalina.jar:7.0.64]
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:652) [catalina.jar:7.0.64]
at org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1809) [catalina.jar:7.0.64]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_80]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[?:1.7.0_80]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.7.0_80]
at java.lang.reflect.Method.invoke(Method.java:606) ~[?:1.7.0_80]
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:301) [tomcat-coyote.jar:7.0.64]
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819) [?:1.7.0_80]
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801) [?:1.7.0_80]
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:618) [catalina.jar:7.0.64]
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:565) [catalina.jar:7.0.64]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_80]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[?:1.7.0_80]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.7.0_80]
at java.lang.reflect.Method.invoke(Method.java:606) ~[?:1.7.0_80]
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:301) [tomcat-coyote.jar:7.0.64]
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819) [?:1.7.0_80]
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801) [?:1.7.0_80]
at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1487) [?:1.7.0_80]
at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:97) [?:1.7.0_80]
at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1328) [?:1.7.0_80]
at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1420) [?:1.7.0_80]
at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:848) [?:1.7.0_80]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_80]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[?:1.7.0_80]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.7.0_80]
at java.lang.reflect.Method.invoke(Method.java:606) ~[?:1.7.0_80]
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:322) [?:1.7.0_80]
at sun.rmi.transport.Transport$2.run(Transport.java:202) [?:1.7.0_80]
at sun.rmi.transport.Transport$2.run(Transport.java:199) [?:1.7.0_80]
at java.security.AccessController.doPrivileged(Native Method) ~[?:1.7.0_80]
at sun.rmi.transport.Transport.serviceCall(Transport.java:198) [?:1.7.0_80]
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:567) [?:1.7.0_80]
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:828) [?:1.7.0_80]
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.access$400(TCPTransport.java:619) [?:1.7.0_80]
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler$1.run(TCPTransport.java:684) [?:1.7.0_80]
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler$1.run(TCPTransport.java:681) [?:1.7.0_80]
at java.security.AccessController.doPrivileged(Native Method) ~[?:1.7.0_80]
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:681) [?:1.7.0_80]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [?:1.7.0_80]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [?:1.7.0_80]
at java.lang.Thread.run(Thread.java:745) [?:1.7.0_80]
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/<NONE>]
at org.springframework.web.context.support.ServletContextResource.getInputStream(ServletContextResource.java:141) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:330) ~[spring-beans-4.3.11.RELEASE.jar:4.3.11.RELEASE]
... 59 more
A:
The problem was when upgrading to spring-boot-actuator 1.2.5.RELEASE, for some reason the "contextConfigLocation" was removed so all I neded to do is to specify the contextConfiguration in my web.xml which is by default /WEB-INF/applicationContext.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
| {
"pile_set_name": "StackExchange"
} |
Q:
Bind DataGrid Columns to Nested Objects
I have a main object that has properties, each their own object:
Package {
Name
Date
}
Document {
Name
Package1 = Package()
Package2 = Package()
Package3 = Package()
Package4 = Package()
}
Now in WPF datagrid, I'd like to bind each column to one of the Document.PackageX properties. But the Name binding inside the DataTemplate always picks up the Document.Name and not the Package.Name
<DataTemplate x:Key="MyCellTemplate">
<Border>
<TextBlock Text="{Binding Name}" /> # this is Package.Name property
</Border>
</DataTemplate>
<DataGrid ItemsSource="{Binding ListOfDocuments}">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Package 1" CellTemplate="{StaticResource MyCellTemplate}"/>
<DataGridTemplateColumn Header="Package 2" CellTemplate="{StaticResource MyCellTemplate}"/>
<DataGridTemplateColumn Header="Package 3" CellTemplate="{StaticResource MyCellTemplate}"/>
<DataGridTemplateColumn Header="Package 4" CellTemplate="{StaticResource MyCellTemplate}"/>
</DataGrid.Columns>
</DataGrid>
How should I set the context of a cell template to the nested object?
(Apologize for over-simplification but I thought it's easier to read and explains the core issue)
A:
You need to define 4 different CellTemplates that binds to Package1, Package2, Package3 and Package4 respectively:
<DataGrid ItemsSource="{Binding ListOfDocuments}">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Package 1">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Package1.Name}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Package 2">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Package2.Name}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Package 3">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Package3.Name}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Package 4">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Package4.Name}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
You cannot use the same CellTemplate for all 4 columns. If the CellTemplate is more complicated than what you have showed here, you might want to consider creating the templates programmatically. Please refer to my answer here for an example of how you can do this.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to prevent a child element from clipping if the parent's overflow is not visible?
Once assigning overflow with a value other than visible, all its child elements will be clipped. It is the purpose of the overflow property. However, I have to make one of the child elements to be 'floated' and not clipped (like a popup) -- just one of them; not all. Is it possible?
Take the following as an example. Is there any CSS setting that does not clip the yellow div, while clipping the blue element? (Currently they are both clipped)
<div style="position:absolute;width:100px;height:50px;overflow:hidden;border:1px solid black">
<div style="top:30px;width:50px;height:100px;background:yellow">
</div>
<div style="position:absolute;left:50px;top:0;width:50px;height:100px;background:blue">
</div>
</div>
The code can be also found at http://jsfiddle.net/kZBxD/
A:
Do you need something like this:
check this fiddle : http://jsfiddle.net/kZBxD/3/
<div style="position:absolute;width:100px;height:50px;overflow:hidden;border:1px solid black">
<div style=" position:fixed;width:50px;height:100px;background:yellow"></div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Google App Engine: Can't import Go packages
I'm attempting the Google App Engine "hello world" example found here. I'm using the Go language, and following exactly the steps given in the above-mentioned tutorial. Additionally, I've installed Go using the installer here. I'm running Windows 7 x64.
When I run the sample app, using the command prompt:
dev_appserver.py c:\@Code\Go\myapp
I get the following response:
INFO 2013-10-17 11:17:00,497 sdk_update_checker.py:245] Checking for updates
to the SDK.
INFO 2013-10-17 11:17:02,756 sdk_update_checker.py:273] The SDK is up to dat
e.
WARNING 2013-10-17 11:17:02,815 api_server.py:332] Could not initialize images
API; you are likely missing the Python "PIL" module.
INFO 2013-10-17 11:17:02,828 api_server.py:139] Starting API server at: http
://localhost:53563
INFO 2013-10-17 11:17:02,834 dispatcher.py:171] Starting module "default" ru
nning at: http://localhost:8080
INFO 2013-10-17 11:17:02,838 admin_server.py:117] Starting admin server at:
http://localhost:8000
ERROR 2013-10-17 11:17:02,905 go_runtime.py:165] Failed to build Go applicati
on: c:\@Code\Go\myapp\hello\hello.go:4: can't find import: "fmt"
2013/10/17 11:17:02 go-app-builder: build timing: 1×6g (16ms total), 0×gopack
(0 total), 0×6l (0 total)
2013/10/17 11:17:02 go-app-builder: failed running 6g.exe: exit status 1
(Executed command: C:\go_appengine\goroot\bin\go-app-builder.exe -app_base c:\@C
ode\Go\myapp -arch 6 -binary_name _go_app -dynamic -extra_imports appengine_inte
rnal/init -goroot C:\go_appengine\goroot -gcflags -I=C:\go_appengine\goroot\pkg\
windows_amd64_appengine -ldflags -L=C:\go_appengine\goroot\pkg\windows_amd64_app
engine -nobuild_files ^^$ -unsafe -work_dir c:\users\dennyc~1.sun\appdata\local\
temp\tmpr5dxl2appengine-go-bin hello\hello.go)
All of the paths above seem to be valid (although admittedly I don't know what any of them mean) with the exception of the last temp folder. As you can see in the sample app, fmt is the first import. If I swap the two imports, I get the same error but for net/http.
I know Go is properly installed because I can run the following test Go app:
package main
import "fmt"
func main() {
fmt.Printf("hello, world\n")
}
...directly from Go.
I've tried messing with all of the various Environment Variables at no avail. But, seeing as to how the test Go app will work, I'm thinking this has something to do with the App Engine.
A:
There was a bug in the recently released windows SDK (1.8.6). A newer version has just been released which fixes that bug (1.8.6.1). Try downloading that version instead.
https://developers.google.com/appengine/downloads#Google_App_Engine_SDK_for_Go
| {
"pile_set_name": "StackExchange"
} |
Q:
approximating a geometric sum of exponentials by an integral
Let $e(x) = e^{2 \pi i x}$. Let $I = [a,b]$ be a closed interval of real numbers.
I am interested in the sum
$$
S = \sum_{n \in I \cap \mathbb{Z}} e(\alpha n)
$$
for some real number $\alpha.$ Do there exists constants $c_1, c_2>0$ such that we can approximate
$S$ by integral,
$$
c_2 |\int_I e(\alpha x) dx| \leq |S| \leq c_1 |\int_I e(\alpha x) dx| ?
$$
The constants are independent of $I$ and $\alpha$.
Do such constants exist? Thank you.
A:
There are no such constants independent of $I$ and $\alpha$. For every $\alpha \neq 0$ we have
$$\int_I e(\alpha x)\,dx = 0$$
whenever the length of $I$ is an integer multiple of $\frac{1}{\lvert\alpha\rvert}$, and not for all such intervals does the sum vanish too: By moving the interval left or right one can pick up or drop one term of the sum [if the length of the interval is an integer, this depends on the interval not being half-open], and since $e(x)$ never vanishes, at most one of the two intervals can lead to a zero sum.
Thus for every fixed $c$ the inequality
$$\lvert S\rvert \leqslant c \biggl\lvert \int_I e(\alpha x)\,dx \biggr\rvert$$
is violated for infinitely many $I$ and $\alpha$.
Conversely, if $\alpha$ is not an integer, then $\lvert S\rvert$ can be made arbitrarily small while keeping the modulus of the integral above a fixed positive threshold: For a given run of integers $k \leqslant n \leqslant m$, you can choose $a$ freely in $(k-1,k]$ (and/or $b$ freely in $[m,m+1)$) without changing the sum, while the value of the integral varies. With
$$K := \sup_{y \in [0,1)}\; \biggl\lvert \int_0^y e(\alpha x)\,dx\biggr\rvert$$
one can always choose the interval such that
$$\biggl\lvert \int_I e(\alpha x)\,dx \biggr\rvert \geqslant \frac{K}{2}\,.$$
Hence for every fixed $c > 0$ also the inequality
$$\lvert S\rvert \geqslant c \biggl\lvert \int_I e(\alpha x)\,dx \biggr\rvert$$
is violated for infinitely many $I$ and $\alpha$.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to select all list elemnets of a specific in jquery?
//first ul
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
//second ul
<ul >
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
I want to write some text only into all the <li> elements of 2nd unordered list. I want my jquery to ignore <li>s in first <ul>
Here is what I attempted, but it did not work:
$("ul:nth-child(1) li").eq(1).each(function(){
$(this).text("Lorem Ipsum");
});
A:
I want to write some text only into all the <li> elements of 2nd unordered list.
You can use :eq(index)
Select the element at index n within the matched set.
Note: Zero-based index of the element to match
Use
$("ul:eq(1) li").text("Lorem Ipsum")
DEMO
EDIT: Be wise to chooses between :eq() and :nth-child()
See comparative example
Demo with :eq() vs Demo with :nth-child()
| {
"pile_set_name": "StackExchange"
} |
Q:
Disable IPv6 on Loopback address (Localhost, Computer name, ...)
We tried installing a 3rd party software product on a new Windows Server 2008 R2 machine and found that everything works except for accessing local services through loopback addresses such as localhost or the computer name (ex: VPS-Web which resolves to localhost). We are not using IPv6 and would like to disable it until the software is compatible.
I tried using these instructions for disabling IPv6 on Windows 2008 R2 but it did not disable the protocol for localhost. Pinging localhost or VPS-Web will still return ::1: instead of 127.0.0.1. I can use ping localhost -4 to get the correct address, but IPv6 takes precedence over IPv4 so the 3rd party software only gets the IPv6 address.
A:
I had initially checked the host file as SilverbackNet suggested, but on a Windows 2008 R2 server this is the default file:
# localhost name resolution is handled within DNS itself.
# 127.0.0.1 localhost
# ::1 localhost
# indicates a comment in the host file, so all the entries are commented out, and the first line is a bit confusing. I then noticed that there were two entries for localhost that were commented out, so I tried uncommenting the IPv4 one and it worked! I should have tried that first but I was thrown off track by the first line. Using the below host file pinging the computer name or localhost will always return an IPv4 address, which fixes the problem with the 3rd party software!
# localhost name resolution is handled within DNS itself.
# ::1 localhost
127.0.0.1 localhost
127.0.0.1 VPS-Web
A:
Setting "DisabledComponents" = 0x20 under
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters\
will set that machine to use IPv4 instead of IPv6 in prefix policies.
Create the registry key if it doesn't exist.
| {
"pile_set_name": "StackExchange"
} |
Q:
Что использовать для ежедневной отправки уведомлений?
Мне нужно, чтобы приложение каждый день (когда оно закрыто) выполняла очень простые действия, по получению данных, и после этого отправляла уведомление. Подскажите, что лучше использовать?
A:
WorkManager - это API, который позволяет легко планировать отложенные асинхронные задачи, которые, как ожидается, будут выполняться, даже если приложение закрыто или устройство перезагружается. WorkManager API - это подходящая и рекомендуемая замена для всех предыдущих API фонового планирования Android, включая FirebaseJobDispatcher, GcmNetworkManager и Job Scheduler. WorkManager объединяет функции своих предшественников в современном, согласованном API, который работает до уровня API 14, но при этом учитывает срок службы батареи.
Собственно это все что вам нужно.
| {
"pile_set_name": "StackExchange"
} |