source
sequence | text
stringlengths 99
98.5k
|
---|---|
[
"stackoverflow",
"0014759061.txt"
] | Q:
Using AutoLayout in Xcode disables my code from working (dynamically)?
In my project I have enabled AutoLayout in order to make the app scale properly in both iPhone 4 and iPhone 5. Everything worked fine with doing so, but I found a new problem which I am not sure how to handle.
In my project I have a normal method which checks if a boolean is yes or no, if yes the interface should add a button into the interface and keep my tableView in its current state. But if the method returns no, the button should disappear and make the tableView's height higher! Everything with the button works fine but for some reason after start using AutoLayout my code for increasing the tableView's height stopped working (which worked before).
Now what can I do to make my tableView's height increase in height even if I am using AutoLayout? Here is my code:
- (void)viewWillAppear:(BOOL)animated
{
NSString *bookName = [self getCurrentBookName];
if([self isBlank:bookName])
{
[self.currentBookLabel setText:NSLocalizedString(@"LabelNoBookChosen", nil)];
}
else
{
[self.currentBookLabel setText:[self getCurrentBookName]];
}
[super viewWillAppear:animated];
if([self isAppLicensed] != YES) <------------------THIS IS WHERE I CHECK THE BOOLEAN METHOD!
{
[actionAppStore setHidden:TRUE];
CGRect framez = [tableView frame]; <------------------ THIS CODE IS NOT WORKING ANY LONGER!
[tableView setFrame:CGRectMake(framez.origin.x, framez.origin.y, framez.size.width, framez.size.height+77)];
}
else
{
[actionAppStore setHidden:FALSE];
}
}
A:
You can either
Turn off autolayout and use the autosizing masks. The non-autolayout autosizing masks give you the same control over having controls increase or decrease their size for the 3.5" screen vs the 4" screen. This is probably the easiest solution. And it gives you compatibility with iOS 5 devices, too.
If you want to use autolayout, then you should create an IBOutlet for the appropriate constraint, and then programmatically change that.
On that latter example, consider a layout where I have a table view and a control at the bottom for the app store (I'm inferring this from your variable names). There are two ways to hide and show that bottom control. One is to hide it (or set its alpha to zero or to removeFromSuperview), remove the unnecessary constraints, and recreate the new appropriate constraints.
That works, but it's a hassle. I now prefer to either change the height of what I want hidden to zero, or, if it's already on the edge of the screen, I'll just slide it off the edge so you can't see it anymore.
Thus I might visually hide the app store control, not by playing around with it's hidden property, but rather by changing its height to zero (or, to show it, to 77). That way, the other constraints will automatically resize the other controls. Thus I hide it with:
self.appStoreHeightConstraint.constant = 0.0;
[self.view layoutIfNeeded];
And I show with:
self.appStoreHeightConstraint.constant = 77.0;
[self.view layoutIfNeeded];
I do that with an IBOutlet called appStoreHeightConstraint which is linked to the height constraint for that bottom control.
Alternatively (and only if the item being hidden is at the bottom), I can slide the it off the bottom of the screen (this time with a IBOutlet on the bottom constraint), with:
self.appStoreBottomConstraint.constant = 77.0;
[self.view layoutIfNeeded];
and show it with
self.appStoreBottomConstraint.constant = 0.0;
[self.view layoutIfNeeded];
In the interest of full disclosure, I should mention that you have to be very careful about designing the constraints so that they simultaneously (a) minimally describe your layout; but (b) fully describe your layout. You want to avoid the horrid conflicting or unsatisfactory constraint messages.
Focusing on the vertical dimension only, that means that have the following constraints:
table view's top constraint was to the top of the superview;
table view's bottom constraint was to the top of the app store view;
table view should have no height constraint (because that's what you want to change as other stuff changes);
the app store control at the bottom had it's top constraint linked to the tableview;
the app store's bottom constraint linked to the bottom of the superview; and
the app store's height constraint fixed at 77.0.
But I find that IB always (in a good faith effort to ensure that the constraints are unambiguous) is trying to add additional constraints (e.g. the height of the tableview). So, I personally wrestle with IB to get the constraints quite right (usually I end up lowering the priority of the table view height and when I'm all done with everything else, I can go back and get rid of the table view height).
Maybe I'm making too much of the hassles in editing the constraints, but I mention it because if you don't get them all exactly right, efforts to effect UI changes by altering one constraint will not yield the results you want. Once you get the hang of it, it's pretty easy and it's a thing of beauty to see everything adjust accordingly (esp on complicated scenes). But it can be a hassle to do those first few times.
A:
You probably need to tell the view to layout its subviews using layoutIfNeeded.
See my question I just solved and this question is also related.
|
[
"stackoverflow",
"0018856533.txt"
] | Q:
How to make menu, navbar nav-pills nav-stacked collapse Twitter-bootstrap 3.0
I have this code, I want to make this menu collapse for mobile-devices
<nav class="navigation">
<ul class="nav nav-pills nav-stacked" id="nav-menu">
<li class="active" ><a href="index.php">Domov</a></li>
<li><a href="#">Koncerty</a></li>
<li><a href="#">Shop</a></li>
<li><a href="#">Download</a></li>
<li><a href="#">Kontakty</a></li>
<li><a href="#">Troll</a></li>
</ul>
</nav>
And I want to do this:
A:
I've found a similar question, which seems to have a detailed answer that will be useful for you. It didn't work perfectly for me, but it does seem much closer than I was before.
Check it out: makes nav-pills collapsable just like nav-bar in bootstrap
|
[
"stackoverflow",
"0023256030.txt"
] | Q:
Syntax error for mysql while doing inner join
SELECT t1.Type,
FROM PERFORMS_SURGERY AS PS
INNER JOIN
(SELECT CPT, Type FROM SURGERY) as t1
ON t1.CPT = PS.CPT
WHERE PS.PUsername = "klove30"
I get a syntax error at "FROM PERFORMS_SURGERY AS PS
INNER JOIN
(SELECT CPT, Type FROM SURGERY)". What is the syntax error?
A:
SELECT t1.Type,
FROM ...
You should not have a comma after the last column in the select-list.
Change it to be like this:
SELECT t1.Type
FROM ...
|
[
"stackoverflow",
"0014211300.txt"
] | Q:
Jquery Animation through pictures
I am learning jquery to make some cool animation. Right now I have been given an assignment on pictures which expands, contract and opacity changes as well , in the end it hides.
Here is my code:
function play_pic1()
{
var div = $("#img");
div.animate({width:0},2000);
div.animate({width:1100,opacity:0},4000);
div.animate({opacity:1},4000);
div.hide(4000);
}
$(document).ready(function(){
play_pic1();
play_pic1();
});
The problem is it only works for one image, when I try to insert second image the second image become static.
I used Loops and Function but nothing helped. Kindly help me overcome this issue.
A:
You could pass the element you want to animate as a parameter of the function , e.g.
function play_pic1(element)
{
var div = $(element);
div.animate({width:0},2000)
.animate({width:1100,opacity:0},4000)
.animate({opacity:1},4000)
.hide(4000);
}
$(document).ready(function(){
play_pic1("#img1");
play_pic1("#img2");
});
After OP clarification: if you need to have sequential animation over different elements you could use Deferred objects like so
Example JSBin: http://jsbin.com/ilisug/1/edit
function animate(el)
{
var div = $(el);
return div.animate({width:0},2000)
.animate({width:300,opacity:0},2000)
.animate({opacity:1},2000)
.hide(2000);
}
$(document).ready(function(){
var dfd = $.Deferred(),
chain = dfd;
var slide = ['#el1', '#el2', '#el3'];
$.map(slide, function(el) {
chain = chain.pipe(function() {
return animate(el).promise();
});
});
chain.done(function() {
alert('done')
});
return dfd.resolve();
});
|
[
"stackoverflow",
"0017065393.txt"
] | Q:
Create shortcut in a metro style app
Problem:
I would like to have my app multiple icons on start screen, I saw such with some online camera program (I forgot the name).
Question:
Can a Windows 8 Store program create an own shortcut to the start page (like for itself, but with other parameters, or for other programs, etc.)? How?
What I tried so far: Googled, maybe with the bad keywords, but found nothing but how I can make icons manually, not by my Win8 app.
Language: C#.
A:
Feature is called Secondary Tile, app can have two or more tiles when pin to start option is used.
Here you can find more about secondary tiles : http://msdn.microsoft.com/library/windows/apps/Hh868249%28v=win.10%29.aspx
|
[
"stackoverflow",
"0056374587.txt"
] | Q:
Invoking a step function synchronously from a lambda function
I have a lambda function which is triggered by a FIFO SQS. I only want one instance of the function running. The function invokes a state machine and the state machine takes longer to finish than the lambda function. I want the lambda function to finish only after the step function has completed it's execution.
A:
AWS Step Functions are only invoked asynchronously. A state machine can run for up to 1 year so synchronous invocation is not possible. Depending on your workflow you might find Activities useful.
Activities are an AWS Step Functions feature that enables you to have
a task in your state machine where the work is performed by a worker
that can be hosted on Amazon Elastic Compute Cloud (Amazon EC2),
Amazon Elastic Container Service (Amazon ECS), mobile
devices—basically anywhere.
|
[
"stackoverflow",
"0001107507.txt"
] | Q:
ASP.net MVC custom route handler/constraint
I need to implement an MVC site with urls per below:
category1/product/1/wiki
category1/product/2/wiki
category1/sub-category2/product/3/wiki
category1/sub-category2/sub-category3/product/4/wiki
etc. etc.
where the matching criteria is that the url ends with "wiki".
Unfortunately the below catch-all works only in the last part of the url:
routes.MapRoute("page1", // Route name
"{*path}/wiki", // URL with parameters
new { controller = "Wiki", action = "page", version = "" } // Parameter defaults
I have not had the time to go through the MVC extensibility options so I was wondering what are the possible choices for implementing this? Any sample/example would be just fantastic!
A:
As you mentioned, the catch-all parameter can only appear at the end of a route - the code that you have posted will throw a run-time error and give you the yellow screen of death if you even try to run your application.
There are several extensibility points for building custom routing scenarios. These are - Route, RouteBase, and IRouteHandler.
You can create a generated list of routes to handle by extending RouteBase. Typically you would follow the pattern of having a constructor that takes in a resource (controller name), and then assigning it a list of routes it was responsible for, and then mapping it in your global.asax. Here is some example code you can build from:
public class MyRoute : RouteBase
{
private List<Route> _routes = new List<Route>();
public MyRoute(string resource)
{
// make a Resource property, not shown in this example
this.Resource = resource;
// Generate all your routes here
_routes.Add(
new Route("some/url/{param1}",
new McvRouteHandler {
Defaults = new RouteValueDictionary(new {
controller = resource,
action = actionName
}),
Constraints = new RouteValueDictionary()
);
_routes.Add(...); // another new route
}
public override RouteData GetRouteData(HttpContextBase context)
{
foreach (var route in _routes)
{
var data = route.GetRouteData(context);
if (data != null)
{
return data;
}
}
return null;
}
public override VirtualPathData GetVirtualPath(RequestContext context, RouteValueDictionary rvd)
{
foreach (var route in _routes)
{
var path = route.GetVirtualPath(context, rvd);
if (path != null)
{
return path;
}
}
return null;
}
}
To use your routing class, do a routes.Add(new MyRoute("page1")); in your Global.asax.
If you need even more control, you can implement an IRouteHandler, and instead of creating MvcRouteHandlers() for your routes as shown in the above example, use your own IRouteHandler. This would allow you to override the logic of selecting the controller from the request data.
The entire framework is extremely extensible, but you would need to learn quite a bit in order to do it properly. I would suggest simply rearranging your URL's if possible to take advantage of the catch-all parameter if you can.
|
[
"physics.stackexchange",
"0000073666.txt"
] | Q:
what is the specific cause of permanent magnetism
Why can't we answer this simple question? Where does the magnetic field of a permanent magnet come from? What is different about a magnetizable atom that allows it? Why is it perpetual? Or is it recurrent? Charged particles in motion into wave-flux, then the wave-flux back to charged particles in motion? Primal energy still not explained. To the back side of Mars and physics still cannot explain the basis of a child's toy. tecvia
A:
Permanent magnets are made of a type of material known as ferromagnets.
Ferromagnets are magnetic because the individual electrons which are tiny magnets – they have a "magnetic moment", we say – tend to orient themselves in the same direction which is why the strength of the electrons adds up. For other materials, it tends to cancel.
The North-South direction of the magnet "hiding" inside an electron is aligned with the electron spin, its intrinsic rotation around the axis. The magnitude of the magnetic moment and the magnitude of the spin are determined and constant – characteristic properties of the electron. Only the direction is variable and quantum mechanics implies that once an axis is chosen, the spin (and magnetic moment) may only be "up" or "down" (clockwise or counter-clockwise rotation but nothing in between).
Ferromagnets align the electron spins in the same way because by the Pauli exclusion principle, the same orientation of the spin of two electrons implies that their other properties such as positions have to be different. The identity of the two spins automatically implies that the the "wave function" encoding the probability distribution of the electrons' positions has to be antisymmetric. When it's antisymmetric, it's very small for nearly coincident positions of the electrons (zero for equal positions) which is why the electrons are unlikely to be close to each other. Because of the Coulomb electric repulsion, this "protection against small distance" reduces the total energy by something called "the exchange energy" – the explanation of what it means is this whole paragraph and more – and that's why the same orientation of the electron spins is preferred.
If there were no spin, there would be no ferromagnets. Permanent magnets therefore demonstrate at least two properties of Nature that would be prohibited if it were governed by classical physics: internal angular momentum of point-like particles; and their complete indistinguishability. The classical or high school intuition is enough to imagine a ferromagnet as a pile of many tiny magnets (the electrons) oriented in the same direction but it is not really enough to honestly understand why the electrons "like" that configuration. Quantum mechanics is needed for that.
(There are also permanent magnets that are not of a ferromagnetic, but a ferrimagnetic material, in which the strength of the electrons does not fully add up, but cancels in part. Examples are ferrite magnets and some minerals)
|
[
"stackoverflow",
"0038340132.txt"
] | Q:
Submitting a file to a sinatra backend
I have a form to upload a file:
<form action="/upload" method="post">
<input type="file" name="image">
<input type="submit">
</form>
and I am trying to see what is being submitted. In google chromes inspect element and when I use params.inspect in my back end the only form data that is submitted is {:image => "<submitted file name>"}. How can I get the actual image data? As per this website I should just recieve something in the format of:
{
"image" => {
:type => "image/png",
:head => "Content-Disposition: form-data;
name=\"myfile\";
filename=\"cat.png\"\r\n
Content-Type: image/png\r\n",
:name => "myfile",
:tempfile => #<File:/var/folders/3n/3asd/-Tmp-/RackMultipart201-1476-nfw2-0>,
:filename=>"cat.png"
}
}
I have no idea why that isn't happening. If someone can offer an explanation and correction that would be fantastic.
A:
In order to upload files you need to set the enctype attribute on the form element to multipart/form-data:
<form action="/upload" method="post" enctype="multipart/form-data">
|
[
"rpg.meta.stackexchange",
"0000006371.txt"
] | Q:
Where to ask about a game that straddles the line?
I have fond memories of Wizards, by Avalon Hill. To me it's basically an RPG - your characters have stats and levels, roll dice for random encounters, etc. It has some issues, though, so I want to adjust the rules to make it more appealing to my pals.
If I said it was a board game, I probably wouldn't get much argument as there is a board involved. However, the specific question I want to ask SE involves homebrewing the rules to differentiate the spellcasting classes more, which seems like a topic people here would be better suited to answer. What's my best option here?
A:
Wizards is unambiguously a board game. (A very cool looking board game!) It's not unlike more recent examples of games that contain elements that look like RPG elements, such as Descent, Mice and Mystics, and Dungeons & Dragons: Castle Ravenloft Board Game1, which are definitely board games despite passing resemblances.
The place to ask about house rules for Wizards would be:
Board and Card Games SE, where they have a tag for house rules.
It may be hard to ask an SE-appropriate question for what you're looking for though, as it may be more on the idea-generation side. In that case you might try…
The forums attached to the BoardGameGeek listing for Wizards.
1. Castle Ravenloft and its kin have specifically been discussed before on meta: Are questions about role-playing derivative board games on topic?
|
[
"ham.stackexchange",
"0000006541.txt"
] | Q:
feasibility of wireless passive crystal earphones
I just learnt about such a thing as a crystal radio receiver and the following idea came to my mind. I have no background knowledge on electronics nor anything related.
What if battery-less earbuds can be made, picking AM waves from very short range nearby stations such as an antenna plugged in the audio-out of my pc or smartphone or laptop or all 3 of them at the same time, the receiver shall mix them together in this case and differentiate left-right channels for stereo. Not sure if AM would suffice for the 20kHz bandwidth necessary to cover the full audio spectrum but FM would be more complex for little benefit i think?
The antenna would be inside the string that connects the two earbuds for maybe a max of half a meter length. If two antennas (one per earphone) are needed they can both coexist in the same string but it would be thicker.
This would be compatible with any standard audio plug and have enough range for an apartment.
A:
A crystal radio is powered by the incoming signal. If you've ever listened to one, you'll know that the audio is quite faint, although a purpose-built transmitter could probably be made strong enough to overcome that problem. Traditional crystal radios receive AM only, and not in stereo.
It could be theoretically possible to make a receiver powered by the signal, but it wouldn't be very practical. You would need a high-power transmitter, which would be against the law in the US and in most other countries. There would be a tremendous amount of interference for the neighbors, and the problem would be multiplied for people in high-density housing such as a large apartment building.
Any way you look at it, a low-powered transmitter such as a Bluetooth transmitter, paired with a battery-powered receiver, is more practical.
|
[
"drupal.stackexchange",
"0000042599.txt"
] | Q:
Profile fields export/import
I have many user profile fields created at admin/config/people/accounts/fields in my drupal 7 local (offline) site. I would like to transfer all fields configuration to my online drupal site.
Is there any way to do this like views export/import feature? I don't want to re-create all fields in my online site.
A:
The Features module can export content types, fields, views and allow you to import into another Drupal site.
The features module enables the capture and management of features in Drupal. A feature is a collection of Drupal entities which taken together satisfy a certain use-case.
Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module. A feature module is like any other Drupal module except that it declares its components (e.g. views, contexts, CCK fields, etc.) in its .info file so that it can be checked, updated, or reverted programmatically.
A:
One option could be the Bundle Copy module that lets you export and import the whole user entity.
Another option would be the Field Tools module that provides export/import functionalities specific for fields.
|
[
"hermeneutics.stackexchange",
"0000032264.txt"
] | Q:
Does "ivory tower" in Song of Songs refer to a color or a material?
(This question was inspired by a comment on a Worldbuilding question.)
In Song of Songs 7:4, we have the description "Your neck is like an ivory tower." (NIV) Does the word for "ivory" here refer to being ivory-colored, or specifically to being made out of actual ivory material? Or is there some other meaning of the word here which would be more apparent to one reading this sentence at the time but doesn't really translate well even given that the sentence is a metaphor?
A:
Gesenius' 18th ed. (the leading dictionary of Biblical Hebrew) lists for the word שֵׁן three meanings: (1) tooth, either concrete or metaphorical (e.g. Ps 124:6); (2) ivory; (3) something geographical, often in combination with סלע to yield "rook tooth", i.e. "cliff" (German: "Felszahn", lit. "rock tooth"). As for (2), several examples are given (here all KJV):
Ezek 27:15, "horns of ivory and ebony"
1 Kgs 10:18 | 2 Chr 9:17, "a great throne of ivory"
1 Kgs 22:39 / Am 3:15, "the ivory house" of Ahab in Samaria
Ps 45:9, "the ivory palaces"
Song 5:14, "his belly is as bright ivory"
Am 6:4, "beds of ivory"
All these examples, with the exception of Song 5:14, seem to refer to the material, just like meaning (1) — for (3) both the material and the colour can be meant.
However, in Song 5:14 it is very clear that the colour is meant ("bright"). This is not strange; apart from Am 6:4 these are the only instances of metaphorical language. Based on the case in 5:14 I would also argue for understanding 7:4 as referring to the colour. This also provides for a nice contrast with "fishpools" in the remainder of 7:4 if we understand it to mean "dark".
Although nowadays it is fashionable in the western world to have a tanned skin, some centuries ago it was European fashion to have a white skin. In that time, workers would work outside a lot and get tanned, whereas the aristocracy had the privilege of staying inside, leading to the beauty ideal of a white skin — conversely, nowadays, people work a lot inside, and you show your wealth by showing you can get outside. This can perhaps help to understand the metaphor, although I do not know if there was a beauty ideal of a white skin in biblical times.
As for the "tower" metaphor, perhaps having a long neck was also part of the beauty ideal as for the Kayan people in Myanmar, but again this is conjecture.
|
[
"stackoverflow",
"0022377282.txt"
] | Q:
How to ensure only once instance of an Azure web-job is running at any time
I've got a continuously running WebJob on my auto-scale Azure website.
My WebJob is a simple console application with a while(true) loop that subscribes to certain messages on the Azure service bus and processes them. I don't want to process the same message twice, so when the web site is scaled an another WebJob is started I need for it to detect that another instance is already running and just sit there doing nothing until it's either killed (by scaling down again) or the other instance is killed. In the last scenario the second WebJob should detect that's the other is no longer take over.
Any takers?
A:
You should create a queue (either using the Service Bus or storage queues) and pull the jobs off (create and manage a lease to the message) and process them from there. If that lease is managed properly, the job should only get processed once although you should make sure it's idempotent just in case as there are fringe cases where it will be processed more than once.
|
[
"stackoverflow",
"0049735996.txt"
] | Q:
Creating a stored procedure with IN and OUT Paramters
This is my first time creating a stored proc that has both IN and OUT parameters, and i am pretty lost. What i am trying to do is have an API pass in 3 parameters (ID_TX, FORM_NAME and DATA_DATE) into my stored proc and have my stored procedure do a simple insert and then pass out a single value (SUBMISSION_ID). However, when I try to compile the code, i keep getting the errors. The errors are as follows:
Error(8,1): PLS-00103: Encountered the symbol "INSERT" when expecting one of the following: begin function pragma procedure subtype type <an identifier> <a double-quoted delimited-identifier> current cursor delete exists prior The symbol "begin" was substituted for "INSERT" to continue.
Error(10,1): PLS-00103: Encountered the symbol "RETURNING" when expecting one of the following: . ( ) , * % & = - + < / > at in is mod remainder not rem => <an exponent (**)> <> or != or ~= >= <= <> and or like like2 like4 likec between || multiset member submultiset
Error(11,1): PLS-00103: Encountered the symbol "END"
Is there some syntax basics/knowledge that I am missing? Thanks in advance!
create or replace procedure API_SUBMISSION(rID_TX IN VARCHAR, rFORM_NAME IN VARCHAR, rDATA_DATE IN VARCHAR, v_submission_id OUT NUMBER)
IS BEGIN
DECLARE
v_submission_id number;
insert into submission (SUBMISSION_ID, RESPONDENT_ID, SUBMISSION_DT, SUBMISSION_TYPE_ID, SUBMISSION_NAME_TX, SUBMISSION_SEQ_NB, CREATE_DT, CREATE_USER_ID, MODIFY_DT, MODIFY_USER_ID, EFFECTIVE_DT, INACTIVE_DT)
VALUES (null, get__respondent_id(rID_TX, rFORM_NAME, trunc(sysdate), sysdate, rDATA_DATE || 'TEST ' || rFORM_NAME, 1, sysdate, 1, null, null, null, null)
returning submission_id into v_submission_id;
END API_SUBMISSION;
A:
There are several issues with your procedure:
You have declared an out parameter to hold the returned submission_id, so there is no need to re-declare it.
You don't need the declare keyword inside a procedure/function unless a) it's an anonymous block or b) you're nesting PL/SQL blocks. You're doing neither; you can simply take advantage of the implicit declaration section between the IS/AS and BEGIN keywords. Not that you need to in this case.
You're missing a closing bracket from your call to get__respondent_id - I assume that it's got two parameters?
That means you could rewrite your procedure to be:
CREATE OR REPLACE PROCEDURE api_submission(rid_tx IN VARCHAR2,
rform_name IN VARCHAR2,
rdata_date IN VARCHAR2,
v_submission_id OUT NUMBER) IS
BEGIN
INSERT INTO submission
(submission_id,
respondent_id,
submission_dt,
submission_type_id,
submission_name_tx,
submission_seq_nb,
create_dt,
create_user_id,
modify_dt,
modify_user_id,
effective_dt,
inactive_dt)
VALUES
(NULL,
get__respondent_id(reia_id_tx, rform_name),
trunc(SYSDATE),
SYSDATE,
rdata_date || 'TEST ' || rform_name,
1,
SYSDATE,
1,
NULL,
NULL,
NULL,
NULL)
RETURNING submission_id INTO v_submission_id;
END api_submission;
/
|
[
"stackoverflow",
"0001920163.txt"
] | Q:
Invoking a function Object in Javascript
I have a small question in javascript.
Here is a declaration:
function answerToLifeUniverseAndEverything()
{
return 42;
}
var myLife = answerToLifeUniverseAndEverything();
If I do console.log(myLife)
It'll print 42, as I am just invoking the same instance of function resulting in 42 as the answer. (Basic rule on javascripts that only references of objects are passed and not the object)
Now on the other hand if I do
var myLife = new answerToLifeUniverseAndEverything();
Then I can't invoke the function; instead myLife becomes just an object? I understand that this is a new copy of the same function object and not a reference; but why can't I invoke the method?
Can you please clarify the basic fundamental I am missing here?
Cheers
A:
By prefixing the call to answerToLifeUniverseAndEverything() with new you are telling JavaScript to invoke the function as a constructor function, similar (internally) to this:
var newInstance = {};
var obj = answerToLifeUniverseAndEverything.call(newInstance); // returs 42
if (typeof obj === 'object') {
return obj
} else {
return newInstance;
}
JavaScript proceeds to initialize the this variable inside the constructor function to point to a new instance of answerToLifeUniverseAndEverything. Unless you return a different Object yourself, this new instance will get returned, whether you like it or not.
A:
When you do var myLife = answerToLifeUniverseAndEverything();, myLife is simply holding the return value from the function call - in this case, 42. myLife knows nothing about your function in that case, because the function was already called, returned, and then it assigned the resulting value (42) to the new variable myLife.
A completely different thing happens when you do var myLife = new answerToLifeUniverseAndEverything(); - instead, a new object is created, passed to the function as this, and then (assuming the function doesn't return an object itself), stored in the newly created variable. Since your function returns a number, not an object, the newly generated object is stored.
|
[
"stackoverflow",
"0053150935.txt"
] | Q:
One-liner to retrieve path from netstat port
I'm looking to create a one liner that, given a port number (2550) uses the returned value from netstat would allow me to then run the resulting output against ps -ef to return the path of the process in question. I have:
ps -ef | grep $(netstat -tonp | grep 2550 | awk '{split($7,a,"/"); print a[1]}')
and whilst I know
netstat -tonp | grep 2550 | awk '{split($7,a,"/"); print a[1]}'
returns the expected resulted, the subsequent grep tells me that there is no such file or directory (but, if I do the ps -ef | grep **) it works just fine... I'm obviously missing something... well, obvious, but I can't see what?
A:
try something like (it takes the first PID/port corresponding, not all):
Port=2550;ps -f --pid $( netstat -tonp | awk -F '[ \t/]+' -v Port=$Port '$0 ~ "([0-9]+[.:]){4}" Port { PID= $7;exit}; END { print PID+0 }' ) | sed 's/^\([^ \t]*[ \t]*\)\{7\}//'
the last sed is assuming a ps reply like this (space are important):
usertest 4408 4397 0 09:43 pts/6 00:00:00 ssh -p 22 -X -l usertest 198.198.131.136
for every PID and with no ending sed:
Port=2550; ps -ef | awk -v PIDs="$( netstat -tonp | awk -F '[ \t/]+' -v Port=${Port} '$0 ~ (":" Port) { print $7}' )" 'BEGIN{ split( PIDs, aTemp, /\n/); for( PID in aTemp) aPID[ aTemp[PID] ] }; $2 in aPID { sub( /^([^ \t]*[ \t]*){7}/, ""); print}'
|
[
"stackoverflow",
"0023881014.txt"
] | Q:
MySQL Query select count where in group by
I have this data:
| bid_id | created | auction_id | user_id | bid_credits | bid_credits_free | bid_rating | balance | bidded_price | last_for_user | bid_ip | bid_type |
+--------+---------------------+------------+---------+-------------+------------------+------------+---------+--------------+---------------+--------------+----------+
| 735 | 2013-10-11 10:02:58 | 9438 | 62323 | 1 | 0 | 0.0000 | 100333 | 0.86 | Y | 72.28.166.61 | single |
| 734 | 2013-10-11 10:02:56 | 9438 | 76201 | 1 | 1 | 0.0000 | 1115 | 0.85 | Y | 72.28.166.61 | single |
| 733 | 2013-10-11 10:02:55 | 9438 | 62323 | 1 | 0 | 0.0000 | 100334 | 0.84 | N | 72.28.166.61 | single |
| 732 | 2013-10-11 10:02:54 | 9438 | 76201 | 1 | 1 | 0.0000 | 1116 | 0.83 | N | 72.28.166.61 | single |
| 731 | 2013-10-11 10:02:52 | 9438 | 62323 | 1 | 0 | 0.0000 | 100335 | 0.82 | N | 72.28.166.61 | single |
I'm trying to get the number of "bid_credits" and "bid_credits_free" as SEPARATE VALUES...
So the query should return me:
| user_id | count(bid_credits) | count(bid_credits_free) |
+---------+--------------------+-------------------------+
| 62323 | 3 | 0 |
| 76201 | 2 | 2 |
The query that I am using is:
select user_id, count(bid_credits), count(bid_credits_free) from bids_history
where auction_id = 9438 and user_id in (62323,76201) group by user_id;
but it's not counting the bids correctly... Any ideas?
Thanks
A:
use a sum instead of count when grouping.. should work
I also reformatted so its easier to read :)
SELECT
user_id,
SUM(bid_credits),
SUM(bid_credits_free)
FROM bids_history
WHERE auction_id = 9438 AND user_id IN (62323,76201)
GROUP BY user_id;
the reason why you want to use a sum instead of count is the count will just count the number of rows in a table, but not the contents / value of whats inside it. so when you group by an id like that you need to do a sum to see the actual addition of the contents. hope that helps explain things a bit :)
A:
You're looking to SUM them, COUNT is just counting rows. Try this:
select user_id, sum(bid_credits), sum(bid_credits_free) from bids_history
where auction_id = 9438 and user_id in (62323,76201) group by user_id;
|
[
"christianity.stackexchange",
"0000004534.txt"
] | Q:
What is the biblical basis for women, particularly mothers, working outside of the home?
I'm wondering about the sinfulness of women, particularly mothers, working outside the home. Perhaps 1 Timothy 5:8 could be understood to mean that only the husband is to provide for the family:
Anyone who does not provide for their relatives, and especially for their own household, has denied the faith and is worse than an unbeliever.
1 Timothy 5:8 NIV
What is the biblical basis for a woman, particularly a mother, working outside the home?
A:
Proverbs 31 is considered (by many) to be the model of what a godly woman should be. In this chapter, we see that this woman is actually quite industrious:
10An excellent wife who can find? She is far more precious than
jewels. 11The heart of her husband trusts in her, and he will have no
lack of gain. 12She does him good, and not harm, all the days of her
life.
13She seeks wool and flax, and works with willing hands.
14She is like the ships of the merchant; she brings her food from afar.
15She rises while it is yet night and provides food for her household
and portions for her maidens. 16She considers a field and buys it;
with the fruit of her hands she plants a vineyard. 17She dresses
herself with strength and makes her arms strong. 18She perceives
that her merchandise is profitable. Her lamp does not go out at
night. 19She puts her hands to the distaff, and her hands hold the
spindle.
20She opens her hand to the poor and reaches out her hands
to the needy. 21She is not afraid of snow for her household, for all
her household are clothed in scarlet. 22She makes bed coverings for
herself; her clothing is fine linen and purple. 23Her husband is
known in the gates when he sits among the elders of the land. 24She
makes linen garments and sells them; she delivers sashes to the
merchant.
25Strength and dignity are her clothing, and she laughs at
the time to come. 26She opens her mouth with wisdom, and the teaching
of kindness is on her tongue. 27She looks well to the ways of her
household and does not eat the bread of idleness.
28Her children rise up and call her blessed; her husband also, and he praises her:
29"Many women have done excellently, but you surpass them all."
30Charm is deceitful, and beauty is vain, but a woman who fears
the LORD is to be praised. 31Give her of the fruit of her hands,
and let her works praise her in the gates.
Proverbs 31:10-31 ESV
So, no, in no way does the Bible say it is sinful for a woman to work outside the home.
That being said, men and women are still different, and masculinity is different from femininity.
Most Christian families that I know of where the woman does not work outside the home have made that choice because of their own priorities. They have decided that freeing up the wife or mother to focus more effort on caring for the family and being active in the lives of their children is more important than the extra money and career success that the woman could otherwise achieve in the workplace.
It goes both ways, though. I believe that both the man who has a career and the woman should value the family more than career advancement and prestige. For the man, that may mean not getting that next promotion that requires more hours, so that he can spend more time caring for his wife and children.
|
[
"meta.superuser",
"0000011835.txt"
] | Q:
Why is my question being downvoted and marked as "off-topic"?
https://superuser.com/questions/1127730/what-is-a-list-of-all-the-interfaces-that-can-be-used-to-transfer-data-directly/1127747?noredirect=1#comment1614652_1127747
As far as I can tell, it's a perfectly valid question, the basic form of which I've seen asked and helped answers tons of times on here: someone looking for technical information on some computer hardware, with some slight caveats to make it relevant to the asker's own personal requirements.
I've checked the Help Center, and it seems to be on topic, and doesn't fit in any of the "no-go" topics, so I can't for the life of me understand why it's been voted as off-topic, or why it's getting such a bad reception. Can anyone help? Thanks.
A:
I am fairly certain that the part people are concerned about is that you're asking for a comprehensive list of things. Answers to such questions would require constant maintenance as new options appear. This type of question is sometimes called "List of X" and is not usually allowed. That explains why your question is currently closed as off-topic. ("Too broad" might also be a possible choice for close voting.)
Additionally, please know that hardware recommendations are off-topic for Super User; they also tend to go out of date quickly. For more information, please review the help center's article on what you can ask here.
|
[
"scifi.stackexchange",
"0000123003.txt"
] | Q:
TV episode where family survives explosion in cave, everything else dead
I'm trying to find out a sci-fi TV episode from the late 1950's to early 1960's. It involved a family traveling and somehow an explosion happened. This forced them to take shelter in a cave. The next morning they woke up and when they exited the cave there were no signs of life, no birds chirping, etc. The family walked to the nearest town and they were greeted with overturned cars and buses and the people were all clothed skeletons. Anyone know what series or show this was from?
A:
"Where Have All The People Gone?", starring the great Peter Graves.
From Wikipedia:
On a camping trip in the Sierra Nevada mountains in central California, a father (Peter Graves) and his two teenage children are exploring a cave when they experience an earthquake. After emerging, they hear from a ranch hand who was outside that there was a bright solar flash prior to the earthquake. He soon falls ill and dies, whereupon his body turns to a powdery substance. As the family comes down from the mountain to the nearest town, they discover that everyone has turned to the powdery substance inside their clothing - and there are only a few survivors left.
I remember the scene when the family get back to town, and all the dead bodies are just piles of white powder inside their clothes. It creeped me out.
The entire movie is available on YouTube.
|
[
"stackoverflow",
"0003263452.txt"
] | Q:
use of upload class in codeigniter - Model or Controller?
Quick question about CI.
I have a view with a form, several text input fields and a file upload.
I want to be able to take the input from the text fields, save it to the DB, and then upload the image.
I've achieved this by having the upload code in a controller, and if the upload is successful, a call to my Model is made to update the database.
Is this "best practice", or indeed an acceptable way of doing it? Or should the File Upload go in the Model. Does it matter?
Essentially my code is:
function edit_category()
{
$config['upload_path'] = 'images/category/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '1000';
$config['max_width'] = '300';
$config['max_height'] = '300';
$this->load->library('upload', $config);
if(!$this->upload->do_upload())
{
$this->session->set_flashdata('status', $this->upload->display_errors());
redirect('admin/category/edit/'.$this->input->post('catID'), 'location');
}
else /*no errors, upload is successful..*/
{
$fInfo = $this->upload->data();
//$this->_createThumbnail($fInfo['file_name']);
//process form POST data.
$data = array(
'catName' => $this->input->post('catName'),
'catDesc' => $this->input->post('catDesc'),
'catImage' => $fInfo['file_name']
);
/* update the database */
$category = $this->category_model->edit_category($data, $this->input->post('catID'));
A:
I would put this in a model because I like to keep my controllers as slim as possible. I think of the controller as the link between the views and the back-room processing, not the processing itself.
I'm not sure if this is "best practise" or not. It will certainly work the way you're doing it too. CodeIgniter allows you to be quite flexible in how you apply mvc theory.
|
[
"stackoverflow",
"0036868856.txt"
] | Q:
ASP.NET WebApi DateTimeOffset serialize to Json/JavaScript (angular2)
I do not find a nice way to get a DateTimeOffset value to JavaScript (angular2).
I am using WebApi (5.2.3) and angular2. On the wire I see the date as follow:
RecordModifiedAt : "2016-03-08T17:27:11.9975483+01:00"
JavaScript/angular2 does not recognize this as valid datetime value.
I do have options, but what direction should I go:
Server side: Newtonsoft.Json, ...
Client side: angular2, ...
Others?
Many thankx for your help!
A:
Thankx to PierreDuc feedback I have played around and I came to the following conclusion:
Since JSON does not support a Date datatype, I assume one has to make the conversion on the client side. I use the following 'pattern' (see http://codegur.com/36681078/angular-2-date-deserialization):
getTags() {
return this.http.get('/api/tag/getAll')
.map((response: Response) => this.convertData(response));
}
private convertData(response: Response) {
var data = response.json() || [];
data.forEach((d) => {
// Convert to a Date datatype
d.RecordModifiedAt = new Date(d.RecordModifiedAt);
});
return data;
}
|
[
"stackoverflow",
"0060186844.txt"
] | Q:
Trying to install tryton 5.4 on ubuntu 18.04 Error is the select field (drop-down) for database field on browser with Sao
I had finished installing trytond 5.4 and sao with out error on ubuntu 18.04 server
But when open my browser and put server-ip:8000 tryton -> open database select field and text field username
But the error is the select field (drop-down) for database not working and i cant see my database name that i had been created on postgresql
and i had made browse and grunt for sao all done
So i cant open tryton ERP
Any help please
A:
You must initialize your database after you created it on the backed in order to be shown on the list of databases of the server. Here is the section of the doumentation which explains how to do it:
https://docs.tryton.org/projects/server/en/latest/topics/setup_database.html#topics-setup-database
Once you've initialized your database you have to restart the server to refresh the list of databases. Then you can access the database using admin user and the password you entered on the init process.
|
[
"stackoverflow",
"0031763113.txt"
] | Q:
iOS App Transport Security and Instagram Media CDN
I am updating my iOS app that pulls images from Instagram for iOS v[redacted]. There is a new feature that tightens up network security. It is getting in my way just for Instagram fetches with the following NSError:
Description: {
NSErrorFailingURLKey = "https:/instagram.com/p/52A5mtpurv/media/?size=l";
NSErrorFailingURLStringKey = "https:/instagram.com/p/52A5mtpurv/media/?size=l";
NSLocalizedDescription = "An SSL error has occurred and a secure connection to the server cannot be made.";
NSLocalizedRecoverySuggestion = "Would you like to connect to the server anyway?";
NSURLErrorFailingURLPeerTrustErrorKey = "<SecTrustRef: 0x17b1ebe0>";
NSUnderlyingError = "Error Domain=kCFErrorDomainCFNetwork Code=-1200 \"An SSL error has occurred and a secure connection to the server cannot be made.\" UserInfo={NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., _kCFNetworkCFStreamSSLErrorOriginalValue=-9802, _kCFStreamPropertySSLClientCertificateState=0, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFStreamErrorCodeKey=-9802, kCFStreamPropertySSLPeerTrust=<SecTrustRef: 0x17b1ebe0>, _kCFStreamErrorDomainKey=3, NSErrorFailingURLStringKey=https://igcdn-photos-f-a.akamaihd.net/hphotos-ak-xaf1/t51.2885-15/11375272_1120995804579077_1215796842_n.jpg, NSErrorFailingURLKey=https://igcdn-photos-f-a.akamaihd.net/hphotos-ak-xaf1/t51.2885-15/11375272_1120995804579077_1215796842_n.jpg}";
"_kCFStreamErrorCodeKey" = "-9802";
"_kCFStreamErrorDomainKey" = 3;
}
The easy answer is to just disable the new security feature. Many folks are clearly taking this approach. I think that is unwise.
Reading the above error, it is clear that the Akamai CDN, at akamaihd.net, and Instagram are combining to manifest the problem.
I make the following exception declaration in the info.plist:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>instagram.com</key>
<dict>
<key>NSExceptionAllowInsecureHTTPSLoads</key>
<true/>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSExceptionMinimumTLSVersion</key>
<string>TLSv1.0</string>
<key>NSThirdPartyExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSThirdPartyExceptionMinimumTLSVersion</key>
<string>TLSv1.0</string>
</dict>
</dict>
The above exception isn't doing the job. Any thoughts on how to proceed? Again, disabling the new security feature is not a fixing the issue of dealing with public services that operate through CDNs.
A:
The problem was an aggressive slash reducer in my code. It collapsed the https:// to https:/. That caused the error.
|
[
"stackoverflow",
"0030332213.txt"
] | Q:
Algorithm to Generate number letter combinations with a twist
I have to generate a list of all possible combinations of numbers and letters of length three. The catch is on the first two characters can be letters or numbers, and the third one can only be numeric.
For example:
AA1, AA2, AA3 .... FC7 ... 001, 002 ... 365)
I hope you can all help me. I look forward to these responses. Regards, Josh.
So far i only managed a very simple way to get all number with prevailing zeros
for ($k = 0 ; $k < 999; $k++) {
$rnd[] = sprintf('%03d',$k);
}
A:
This should work for you:
Basically I have an array with all letters ([A-Z]) and an array with all numbers ([0-9]). Then you define which order of possible characters you want. E.g. here you want letterNumber, letterNumber and then the third spot only number.
After this you loop through everything as many times as characters per combinations which you want(e.g. XXX -> 3 times). In the loop you go through all combinations which you already have with all characters which you want at this spot.
So after the 1 iteration you have an array with the first character of each combination, which would be: [0-9A-Z].
Then in the second iteration you go through all combinations which you already have, here [0-9A-Z] with the characters which you want on the second spot, here [0-9A-Z]. So for ever character in the combinations array ([0-9A-Z]) you get a new combinations with each character of [0-9A-Z].
And this repeated over and over until you get your expected combination length.
So at the end you end up with:
letterNumber = 36 = 26 + 10 possible characters ([A-Z0-9])
letter = 26 possible characters ([A-Z])
number = 10 possible characters ([0-9])
36 * 36 * 10 = 12'960 combinations
The code:
<?php
$letters = range("A", "Z");
$numbers = array_merge(range(0, 9));
$order = ["letterNumber", "letterNumber", "number"]; //possibilities: "letter", "number", "letterNumber"
$length = count($order);
$combinations = [[]];
for($count = 0; $count < $length; $count++) {
$tmp = [];
if($order[$count] == "number" || $order[$count] == "letterNumber") {
foreach($combinations as $combination) {
foreach($numbers as $v)
$tmp[] = array_merge($combination, [$v]);
}
}
if($order[$count] == "letter" || $order[$count] == "letterNumber") {
foreach($combinations as $combination) {
foreach($letters as $v)
$tmp[] = array_merge($combination, [$v]);
}
}
$combinations = $tmp;
}
print_r($combinations);
?>
output:
Array
(
[0] => Array
(
[0] => 0
[1] => 0
[2] => 0
)
[1] => Array
(
[0] => 0
[1] => 0
[2] => 1
)
//...
[12959] => Array
(
[0] => Z
[1] => Z
[2] => 9
)
)
Demo
|
[
"meta.stackoverflow",
"0000336622.txt"
] | Q:
Can we talk about the reviewing culture here on Meta?
Kind of related to Can we talk about the voting culture here on Meta?, but that one is about downvoting. I want to talk about close-voting and delete-voting. For quite some time I noticed that there is a group of people on Meta who vote to close any question they don't like as off-topic, choosing varying reasons that don't actually apply. Then, after the question gets closed, the delete-votes pile up.
This results in questions asked by well-meaning but perhaps ill-informed users to be downvoted into oblivion, close-voted before someone can answer and delete-voted within the first hour of its existence. I interpret this as "We don't want your kind here, go away", which is not nice to users who genuinely want feedback or discussion. I also addressed this in my answer in 'Meta to new user: your question is a turd that cannot be polished (or: we need to Be Nice here too)'.
I'm going to have to reconstruct the history I have with this issue from my flagging history to provide some backstory.
Seven months ago there was this question: Is [discussion] allowed on meta?. I flagged it at the moment it had two "cannot reproduce" close-votes, which were ridiculously inapplicable. My flag was considered "helpful" and the close-votes were invalidated by a moderator. The question is now closed as "does not seek input and discussion", which is fine, as the OP seemed to want to post a rant instead of starting a discussion.
Then there was Is there a name for Stack Overflow users as a whole?. It was closed as "off-topic". Then it was reopened by five users. And closed as "opinion-based" again. I flagged, flag was marked "helpful", a mod opened the question again.
After that I flagged Who is a moderator ? Are they an employee of SO?, because there were "non-repro" votes again. Sure, it might be a silly question, but that doesn't warrant close-voting with random close reasons as far as I'm concerned. This time, the flag was declined: "The user appears to be voting properly. The example you gave is a terrible question that should definitely have been closed. Perhaps you should review https://stackoverflow.com/help/whats-meta"
Next question from my flagging history: Question has the answer, right after the 3rd edit. Why wasn't it noticed by future edits/mods?. The close-voters interpreted the question incorrectly, and picked the wrong duplicate. My flag was marked "helpful", but the question remains closed as an incorrect duplicate.
Then there was this "Is this on-topic for Stack Overflow?" question: Where can I ask: Lotus Notes 8.5 Not Supporting Digital Badging. Initially I close-voted because it looked like a question that should have been posted to Main, but it was edited after which I retracted my close-vote. Yet it was robo-close-voted. My flag was marked "helpful", no visible action taken. Took quite some time to go through the reopen queue.
I should be allowed to answer closed questions was again one of those cases where close-votes appeard to be abused as "I strongly disagree" votes, which is not what they are for. After two declined flags because I wasn't verbose enough, the third flag was marked "helpful" and one hour after closing it, it was reopened and remains open.
Serial voting still showing on my questions 5 days after incident, cache not cleared as expected? closed as duplicate without reading or understanding the question.
I hope the pattern is clear now.
Now the problem that I'd like to discuss: it appears to me that an small crowd of 5-10 relatively low-rep (5K-20K) people are active in the review queues on Meta, and they are down-, close- and delete-voting everything that they don't like, while they (again, this is how it appears to me) hardly ever participate posting actual answers on Main.
Do we want a group that small determine what gets discussed on Meta? Do they have the right to close-vote with whatever reason they seem fit, without even trying to (or at least in some cases failing to) understand what's actually being asked in some cases, and delete-voting it so only a small group gets to read what gets posted here on a daily basis?
Alright, an edit to more expressively clarify my concerns: it appears that there are a couple of users who grind the close and reopen queue, where the tendency of voting hangs towards "close" or "leave closed" or even "delete", while the questions and their comments don't appear to be read that attentively.
A:
I've noticed this a lot more too, and I'm working (in whatever spare time I have nowadays) to craft a few SEDE queries to see how frequently a post is voted to be deleted on Meta to see if it's really necessary.
Let me state my opinion here so that it's clear.
I believe that it's fair game to downvote a question here on Meta, especially if it's not an ideal approach to a problem, is ill-researched, or is just plain ranty, but I don't really like deletion of questions here unless it's absolutely necessary. Save for users mistaking* the site for Stack Overflow, there are very few questions which actually need to be deleted.
In that regard, it's also not a bad thing if we get a few more gold-badge holders in the three key tags we have here. Giving more people the ability to undo a bad dupe can only be a good thing, and I hope that others will soon gain that privilege.
I'll address your concerns in turn; I largely agree with them, and I do hope I'm not contributing to the issue. At least, I don't think I am...
...it appears to me that an incrowd of 5-10 relatively low-rep (5K-20K) people are brigading Meta, and they are down-, close- and delete-voting everything that they don't like, while they hardly ever participate on Main. A lot of this action seems to come from the Meta review queues.
Ah, how enviable it must be to consider 5K-20K reputation "low"...
I don't disagree that there is an in-crowd of users doing this kind of thing, but I will disagree with the other two parts.
Users here heavily participate on Main, especially considering that Stack Overflow's reputation is the exact same as Meta Stack Overflow's reputation.
The review queues here are very hard to really gain any traction in; I'm inclined to believe that these actions are taken outside of the queue, especially considering that the users who fit this profile are normally equipped enough to "handle" the issue themselves.
Do they have the right to close-vote with whatever reason they seem fit, without even trying to (or at least failing to) understand what's actually being asked in some cases, and delete-voting it so only a small group gets to read what gets posted here on a daily basis?
Close vote with just whatever reason? I'd prefer if they didn't do that but there's no mechanical thing stopping one from doing this; it's up to us as the community to overturn/challenge closures which we feel are unjustified.
If it's genuinely a bad question and it does need to be closed, then I really don't see any reason to rearrange the chairs on the Titanic.
Deletion, as I mentioned earlier, does strike a bit of a nerve with me in some regards. As I said before, there aren't that many questions which need to be outright deleted, but there are quite a few which do deserve to be closed or downvoted. Deletion is one of those things that makes it tougher for a user to either figure out what happened with the comment chain (since comments are no longer accessible through the inbox once a post is deleted), and not enough users know to look through their history to look for it. Besides that, once the question is deleted, they figure that's pretty much the end of it - they can't get any more input to their problem.
We need to take a more critical look at that and see what's going on there. I get a sneaking suspicion that more content is being buried in this fashion that shouldn't be.
*: I'd love to give the benefit of the doubt to some users, but for those who ask a coding question on Meta after they've got something like 5 questions on the main site...
A:
they are down-, close- and delete-voting everything that they don't like
Is not that they don't like it... if you see their activities pages you will see basically no activity outside /review for most of these users! gasp Basically, most of the questions you see on the /review/close queue will end up closed one way or another, only the initial close voter had some issue with the question. Other reasons not-withstanding I believe this is fairly bigger problem.
|
[
"stackoverflow",
"0041863996.txt"
] | Q:
$exceptionHandler decorator on strictdi - circular and strictdi errors
I'm having trouble with formatting my $exceptionHandler to strictdi. I'm trying to modify the exceptionhandler in order to log angular errors to our servers and let us know certain pages crash. For the code below, I am having circular dependency errors. On the next set of code, I get strictdi errors. Please note we minify our code with gulp.
error here: Circular dependency found: $rootScope <- $http <- serverlog <- $exceptionHandler <- $rootScope
var pageApp = angular.module('pageApp',['angular-oauth2','ngCookies']);
pageApp.factory("serverlog", serverlog);
serverlog.$inject = ["$http"];
function serverlog($http) {
var svc = {};
svc.add = function(exception) {
var data = angular.toJson(exception);
console.log("Sending to server errors");
// console.log(data);
// $.ajax({
// type: "POST",
// url: "/api/v1/jslog",
// contentType: "application/json",
// data: data
// });
};
return svc;
}
pageApp.config(['$provide', function($provide) {
$provide.decorator("$exceptionHandler", $exceptionHandler);
$exceptionHandler.$inject = ['$delegate','serverlog'];
function $exceptionHandler($delegate,serverlog) {
return function(exception, cause) {
$delegate(exception, cause);
serverlog.add(exception);
}
};
}]);
Then for this set of code, comes the strictdi errors :
serverlog is not using explicit annotation and cannot be invoked in strict mode
pageApp.config(['$provide', function($provide) {
$provide.decorator("$exceptionHandler", ['$delegate','serverlog', function($delegate,serverlog) {
return function(exception, cause) {
$delegate(exception, cause);
serverlog.add(exception);
}
}]);
}]);
A:
To solve the circular dependency you can inject $injector instead of serverlog and resolve the dependency at runtime instead:
pageApp.config(['$provide', function($provide) {
$provide.decorator("$exceptionHandler", $exceptionHandler);
$exceptionHandler.$inject = ['$delegate', '$injector'];
function $exceptionHandler($delegate, $injector) {
var serverlog;
return function(exception, cause) {
serverlog = serverlog || $injector.get('serverlog');
$delegate(exception, cause);
serverlog.add(exception);
};
}
}]);
Tried the second example, but couldn't replicate the strictdi error. Should give the same error as the first example as long as you are using the same code for the serverlog service.
|
[
"stackoverflow",
"0025571851.txt"
] | Q:
Polymer with one way databinding
I tried to look for answer to my questions but it seems I cannot find any information on one way data-binding with Polymer.
I have been looking into Polymer and find many of its facets very interesting. I however wonder whether it's possible to "use" polymer in a different way. Different than how I see it being used in examples and tutorials.
Is it possible to use one way binding from the model to the view only (and not from the view to the model)?. How about no binding at all?
One could obviously create extra variables in the model and update the "real parts of the model" in a more controlled manner. But maybe there are some sort of backed-in one way binding alternatives?
The other thing that makes me hesitate with jumping on the Polymer train is the way integration is done between polymer components. Are there alternatives to using the declarative integration/composition. Can one compose different polymer components in a more controlled manner (i.e. programmatically).
I'm pretty sure the above is possible. But can it be done in an elegant way? Has anyone tried such approach?
For instance, knockout offers some beforechange event to allow for more controls on updating the observables. But this ugly "work around" makes the whole process cumbersome.
Thanks in advance for any help!
A:
update
In Polymer 1.x [[]] is for one-way binding.
original
Have a look at the official Polymer documentation.
One-time bindings
Sometimes, you may not need dynamic bindings. For these cases, there are one-time bindings.
Anywhere you use ¸{{}} in expressions, you can use double brackets ([[]]) to set up a one-time binding. The binding becomes inactive after {{site.project_title}} sets its value for the first time.
Example:
<input type="text" value="this value is inserted once: [[ obj.value ]]">
One time bindings can potentially be a performance win if you don't need the overhead of setting up property observation.
See also https://code.google.com/p/dart/issues/detail?id=21022
|
[
"stackoverflow",
"0038868825.txt"
] | Q:
Why cant I get the value of the label?
im trying to get the value of the selected label, and when it changes get the value of the selected label, I have a configurable product and when someone selects either option the price changes see below:
the difference in price is +/- £2.40 depending on what option is selected, I have a dynamic price when someone changes the quantity it calculates the price taking in what option has been selected, but I'm having trouble getting the value of the selected option as it shows me a blank field.
<div class="input-box">
<select name="super_attribute[183]" id="attribute183" class="required-entry super-attribute-select" style="left: -10000px; position: absolute;">
<option value="">Choose an Option...</option>
<option value="90" price="2.4">With Screws +£2.40</option>
<option value="89" price="0">Without Screws</option>
</select>
<div class="switcher-field switcher-screws" id="attribute183_switchers">
<label class="switcher-label" id="attribute183_90" value="90" title="With Scews" style="width:60px;height:60px;line-height:60px">
<img src="image" alt="With Scews">
</label>
<label class="switcher-label selected" id="attribute183_89" value="89" title="Without Screws -£2.40" style="width:60px;height:60px;line-height:60px">
<img src="image2" alt="Without Screws -£2.40">
</label>
<div style="clear:both"></div>
</div>
</div>
Im using the current jQuery code
var selectedOption = jQuery('.switcher-screws label.selected');
selectedOption.on('change', function(){
var optionvalue = $(this).val()
})
console.log(optionvalue);
I've tried
var selectedOption = jQuery('.switcher-screws label.selected');
optionvalue = selectedOption.val()
console.log(optionvalue);
but it just gives me a blank value, any ideas on where I'm going wrong ?
EDIT: I managed to get the value of the label by using on click
jQuery('label.switcher-label').click( function(){
var sellabel = jQuery('label.switcher-label.selected').attr('value');
console.log(sellabel);
});
A:
The .val() method is primarily used to get the values of form elements
such as input, select and textarea. When called on an empty
collection, it returns undefined.
It won't return the value of the label, you can try using the attr function:
var selectedOption = jQuery('.switcher-screws label.selected');
optionvalue = selectedOption.attr('value');
|
[
"space.stackexchange",
"0000009139.txt"
] | Q:
What are reentry speeds of space vehicles?
I found here that the entry speed of meteors reach 48 km/s. I mean just before hitting atmosphere.
What are reentry speeds for space vehicles like the lunar command module?
What about soyuz spacecraft?
A:
That same Wikipedia article on Atmospheric entry that you link to in your question answers this later on:
... for entry from low Earth orbit where entry velocity is
approximately 7.8 km/s. For lunar return entry of 11 km/s ...
And also:
The Stardust sample-return capsule was the fastest man-made object
ever to reenter Earth's atmosphere (12.4 km/s or 28,000 mph at 135 km
altitude).
More specifically, for Soyuz reentry see What is the maximum velocity at which Soyuz TMA-M may transit through Earth' atmosphere at reentry without a heat-shield? And for Apollo missions see Apollo by the numbers - Entry, Splashdown, and Recovery (table of contents here). Apollo 10 had the fastest maximum entry velocity at 36,397 ft/s (11.094 km/s).
Future Earth atmospheric reentry speeds might substantially increase for return missions to Mars, with entry speeds in the 15-21 km/s range, depending on trajectory and time of launch (source: A simple atmosphere reentry guidance scheme for return from the manned Mars mission, Henry C. Lessing and Robert E. Coate, 1966, NASA Ames Research Center).
|
[
"stackoverflow",
"0030034784.txt"
] | Q:
Accessing parent scope with Object.call
I want to access img property in onload function how can i do this ? i added img property to Picture object and calling onload function with scope of Picture object, still i can not access this.img.
// picture
function Picture(x, y, w, h, imgurl){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.imgurl = imgurl;
this.draw = drawPic;
this.overcheck = overRect;
} // end picture
function drawPic(){
this.img = new Image(); // add img to this scope
this.img.src = this.imgurl;
this.img.onload = function(){
//ctx.drawImage(this.image, this.that.x, this.that.y, this.that.w, this.that.h);
ctx.drawImage(this.img, this.x, this.y, this.w, this.h); //error
} // end onload
this.img.onload.call(this);
} // end drawPic
A:
Use a reference to this
function drawPic() {
var self = this;
this.img = new Image();
this.img.src = this.imgurl;
this.img.onload = function() {
ctx.drawImage(self.img, self.x, self.y, self.w, self.h);
};
}
|
[
"stackoverflow",
"0030183093.txt"
] | Q:
Custom UITableViewController inside Container View
I am trying to insert a custom UITableViewController inside a Container View. The Container View is placed inside a cell of a static UITableView as shown in the figure below.
http://i.stack.imgur.com/A762B.png
I simply want a method to combine static with dynamic cells in the same screen.
In the Identity Inspector when the field Class is empty (i.e. a standard UITableViewController) it works showing an empty dynamic table inside the cell. But when I put my custom class name (that extends UITableViewController) in that field I get a NSInternalInconsistencyException:
[UITableViewController loadView] loaded the "Enx-aT-Rum-view-zY2-9U-Z6d" nib but didn't get a UITableView.
These are the contents of MyCustomUITableViewController:
@implementation MyCustomUITableViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 2;
}
@end
I have to admit that I still don't understand all the logic behind Container View, but I just want to show only one view inside (not doing any swapping or else).
Any help would be appreciated, thanks!
A:
Let me point out the issues here first-
Problem 1: you can not have an controller inside another controller. That means, inside your Static tableview, you can not have a dynamic tableview Controller.
Solution 1:You can have a dynamic TableView.
Problem 2: You can not have a static Tableview inside a View Controller. If you want a Static Tableview then you need to have a UITableViewController rather than the UIViewController.
Solution 2: You just need to delete the ViewController you have and replace with a UITableViewController.
Now to achieve one controller where you can have a dynamic TableView inside a static tableview, you will need to implement you dynamic table's datasource inside the Static Table's ViewController which would be a very bad practise.
The static table should not need to know anything about your dynamic Table, at least about the data that will be populated in your dynamic table. However, if you want a dynamic tableview inside your static tableView then your static tableview's controller needs to implement the UITableViewDatasource.
So, you may want to re-think about the structure.
|
[
"unix.stackexchange",
"0000187221.txt"
] | Q:
How to get information about deb package archive?
How to get information about .deb package archive?
Like: package information, version, installed-size, architecture, description and licensing information etc. from .deb package archive?
A:
You can use dpkg-deb command to manipulate Debian package archive (.deb).
From manpage:-
-I, --info archive [control-file-name...]
Provides information about a binary package archive.
If no control-file-names are specified then it will print a summary of the contents of the package as
well as its control file.
If any control-file-names are specified then dpkg-deb will print them in the order they were specified;
if any of the components weren't present it will print an error message to stderr about each one and
exit with status 2.
Example Usage:-
$ dpkg-deb -I intltool_0.50.2-2_all.deb
new debian package, version 2.0.
size 52040 bytes: control archive=1242 bytes.
831 bytes, 19 lines control
1189 bytes, 18 lines md5sums
Package: intltool
Version: 0.50.2-2
Architecture: all
Maintainer: Ubuntu Developers <[email protected]>
Original-Maintainer: Debian GNOME Maintainers <[email protected]>
Installed-Size: 239
Depends: gettext (>= 0.10.36-1), patch, automake | automaken, perl (>= 5.8.1), libxml-parser-perl, file
Provides: xml-i18n-tools
Section: devel
Priority: optional
Multi-Arch: foreign
Homepage: https://launchpad.net/intltool
Description: Utility scripts for internationalizing XML
Automatically extracts translatable strings from oaf, glade, bonobo
ui, nautilus theme and other XML files into the po files.
.
Automatically merges translations from po files back into .oaf files
(encoding to be 7-bit clean). The merging mechanism can also be
extended to support other types of XML files.
You can list the content by dpkg-deb -c:-
Example Usage:
$ dpkg-deb -c libnotify-bin_0.7.6-1ubuntu3_i386.deb
drwxr-xr-x root/root 0 2014-02-22 05:24 ./
drwxr-xr-x root/root 0 2014-02-22 05:24 ./usr/
drwxr-xr-x root/root 0 2014-02-22 05:24 ./usr/bin/
-rwxr-xr-x root/root 9764 2014-02-22 05:24 ./usr/bin/notify-send
drwxr-xr-x root/root 0 2014-02-22 05:24 ./usr/share/
drwxr-xr-x root/root 0 2014-02-22 05:24 ./usr/share/man/
drwxr-xr-x root/root 0 2014-02-22 05:24 ./usr/share/man/man1/
-rw-r--r-- root/root 773 2014-02-22 05:24 ./usr/share/man/man1/notify-send.1.gz
drwxr-xr-x root/root 0 2014-02-22 05:24 ./usr/share/doc/
drwxr-xr-x root/root 0 2014-02-22 05:25 ./usr/share/doc/libnotify-bin/
-rw-r--r-- root/root 1327 2011-07-31 03:11 ./usr/share/doc/libnotify-bin/copyright
lrwxrwxrwx root/root 0 2014-02-22 05:25 ./usr/share/doc/libnotify-bin/AUTHORS -> ../libnotify4/AUTHORS
lrwxrwxrwx root/root 0 2014-02-22 05:25 ./usr/share/doc/libnotify-bin/NEWS.gz -> ../libnotify4/NEWS.gz
lrwxrwxrwx root/root 0 2014-02-22 05:25 ./usr/share/doc/libnotify-bin/changelog.Debian.gz -> ../libnotify4/changelog.Debian.gz
Getting licensing information:-
Most of archive's copyright information is available from /usr/share/doc/<pkgname>/copyright
Example :-
$ dpkg-deb -c gparted_0.18.0-1_i386.deb | grep -i copyright
-rw-r--r-- root/root 1067 2011-12-08 00:34 ./usr/share/doc/gparted/copyright
Which you can extract by -x and look for License under which it is released.
Here:-
$ cat /usr/share/doc/gparted/copyright | grep -i ^license -A 5
License:
This package is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 dated June, 1991.
For more, run man dpkg-deb.
A:
You can use dpkg -f (archive) (field name) to do exactly this.
Example:
dpkg -f archive.deb Version
dpkg -f archive.deb Package
To get possible field names:
dpkg --info archive.deb
|
[
"stackoverflow",
"0029012517.txt"
] | Q:
active_record-acts_as - validate parent fields on child model
I'm using Rails 4.2.0 and the active_record-acts_as gem.
This gem simulates multi-table inheritance for ActiveRecord models.
I have my parent model called Attachment with child models Specification and Release.
class Attachment < ActiveRecord::Base
actable
end
class Specification < ActiveRecord::Base
acts_as :attachment
end
class Release < ActiveRecord::Base
acts_as :attachment
end
My Attachment model has fields name, actable_id, actable_type (used by acts_as gem) and the standard paperclip fields.
Specification and Release have multiple fields specific to their type (so I don't think they are good candidates for single table inheritance).
What I am trying to do is validate name on the child models instead of the parent, as different rules apply to Release and Specification.
Presence validations seem to work fine:
class Specification < ActiveRecord::Base
acts_as :attachment
validates :name, presence: true
end
But when I try something like:
class Specification < ActiveRecord::Base
acts_as :attachment
validates :name, presence: true, uniqueness: { case_sensitive: true }
end
I get the following error when calling .valid?
NoMethodError: undefined method `limit' for nil:NilClass
I wrote some custom validations which work on the child model, but I was hoping I wouldn't have to.
The main reason for validating on the child was because I use the following to get more concise error messages depending on the model (Specification, Release):
class Specification < ActiveRecord::Base
...
HUMANIZED_ATTRIBUTES = {
name: "Version"
}
def self.human_attribute_name(attr, options={})
HUMANIZED_ATTRIBUTES[attr.to_sym] || super
end
end
So it returns something like:
Version can't be blank. instead of Name can't be blank.
I also tried validating on Attachment (the parent) using something like:
with_options if: Proc.new { |x| x.actable_type == "Specification" } do |s|
s.validates :name, presence: true, uniqueness: { case_sensitive: true }
end
But then I don't get the error messages I want. Name instead of Version.
I am probably massively over complicating things. Any ideas?
A:
As Evgeny Petrov worked out, it isn't possible to validate parent attributes on the child models (probably can be done with a custom Validator).
In the end I opted for validating on the parent model using with_options if: to target certain actable_types.
And in order to sort out some custom error messages, I combined the HUMANIZED_ATTRIBUTES hash on the child class with self.human_attribute_name on the parent.
Here is an example:
class Attachment < ActiveRecord::Base
actable
before_validation :set_humanized_attributes
class << self; attr_reader :humanized_attributes end
@humanized_attributes = {}
with_options if: proc { |x| x.actable_type == 'Release' do |s|
s.validates :name, presence: true, uniqueness: { case_sensitive: false }
end
with_options if: proc { |x| x.actable_type == 'Specification' do |s|
s.validates :name, presence: true, uniqueness: { case_sensitive: true }
end
def self.human_attribute_name(attr, options = {})
humanized_attributes[attr.to_sym] || super
end
private
def set_humanized_attributes
@humanized_attributes = actable_type.constantize::HUMANIZED_ATTRIBUTES
end
end
class Specification < ActiveRecord::Base
acts_as :attachment
HUMANIZED_ATTRIBUTES = {
name: 'Version'
}
# child attribute validations here
end
class Release < ActiveRecord::Base
acts_as :attachment
HUMANIZED_ATTRIBUTES = {
name: 'Release'
}
# child attribute validations here
end
In rails console:
> s = Specification.new
=> #<Specification id ... >
> s.valid?
=> false
> s.errors.full_messages
=> ["Version can't be blank"]
> r = Release.new
=> #<Release id ... >
> r.valid?
=> false
> r.errors.full_messages
=> ["Release can't be blank"]
Need to check some edge cases and make it more robust, but for now this is achieving what I required.
|
[
"unix.stackexchange",
"0000402672.txt"
] | Q:
Xdotool action without focusing
Is there a way to automatically click at a specific place in specific window without getting the window focused?
A:
I've just been struggling with the same problem and this is the best option I could come up with:
$ (w=`xdotool getactivewindow` && xdotool click 1 && xdotool windowactivate $w)
This line saves the ID of the currently active window, then issues the click command at the location of the mouse cursor, and then forces the focus to go back to the window that was active.
Thus, the target window WILL gain focus for a split second, but then the focus will return to the original window.
This is suboptimal, but may be an acceptable solution depending on what you are doing.
|
[
"stackoverflow",
"0041444789.txt"
] | Q:
C# shortcut for a List property that should never return null
In order to make sure that a list property would never return null, I declared it this way:
private IList<Item> _myList;
[NotNull]
public IList<Item> MyList
{
get { return _myList ?? new List<Item>(); }
set { _myList = value; }
}
This works, but I hate the syntax. Considering that I should use this technique extensively throughout my project, I'm looking for a better way to write this or a better solution to the same problem. Any idea?
A:
That's the good way to do it but each time MyList is required and _myList is null, you will create a new empty List... So if _myList is empty and someone do MyList.Add(item); it will not be added to the right list.
Better do this :
private IList<Item> _myList;
[NotNull]
public IList<Item> MyList
{
get { return _myList ?? (_myList = new List<Item>()); }
set { _myList = value; }
}
That way, first time _myList is null, you create a new list. Then, _myList will not be null.
|
[
"stats.stackexchange",
"0000037659.txt"
] | Q:
Scaling mixed models for PCA using dudi.mix
I am trying to do a kselect model from the adehabitatHS which uses commands from ade4 package. I am trying to determine if I need to scale my variables. My surface understanding is that the k-select is basically a fancy PCA. In their example they scaled their variables, but their variables were only continuous measures. I have mixed categorical and continuous variables. In their example, they scale their variables before they use the command dudi.pca which from my understanding this is needed to set up the k-select. I know from reading the dudi help in the ade4 vinette that I should use dudi.mix here instead of .pca, but what to do about scaling? Do I need to scale my variables? Do I need to scale all variables? Do I need to scale all the variables EXCEPT the categorical variable? I can't find reading material that explains what is happening in the dudi/pca mixed process in sufficient detail.
Below is the example code from the k-select help if you would like to see what I am referring to.
data(puechabonsp)
locs <- puechabonsp$relocs
map <- puechabonsp$map
pc <- mcp(locs[,"Name"])
hr <- hr.rast(pc, map)
cp <- count.points(locs[,"Name"], map)
## prepares the data for the kselect analysis
x <- prepksel(map, hr, cp)
tab <- x$tab
## Example of analysis with two variables: the slope and the elevation.
tab <- tab[,((names(tab) == "Slope")|(names(tab) == "Elevation"))]
tab <- scale(tab)
## A K-select analysis
acp <- dudi.pca(tab, scannf = FALSE, nf = 2)
kn <- kselect(acp, x$factor, x$weight, scannf = FALSE, nf = 2)
Again, their example only used continuous variables. Does the dudi.mix scale the variables appropriately in the code that we don't see?
A:
I found this as a partial explanation in http://cran.r-project.org/web/packages/adehabitatHS/vignettes/adehabitatHS.pdf.
The function dudi.pca is to be used when all the variables present in
the data.frame are numeric. The function dudi.acm is to be used when
all the vari- ables present in the data.frame are factors. The
function dudi.hillsmith (or, equivalently, dudi.mix) is to be used
when the data.frame contains both types of variables. These functions,
used as a preliminary to the GNESFA, are needed to scale the table
suitably (so that all the variables have the same mean and the same
variance), and to compute the weights of the variables in the
analysis. For example, the use of dudi.hillsmith on a table containing
a numeric variable and a factor with four levels ensures that the
factor will have the same weight in the analysis as the numeric
variable
I can only assume the dudi.hillsmith is scaling the data correctly and I do not need to scale my data before using the k-select.
|
[
"stackoverflow",
"0019017620.txt"
] | Q:
How to make the status bar translucent in iOS 7?
In my app, I have some webviews. A transparent status bar doesn't look good for full screen webview. I want to make the status bar TRANSLUCENT, just like the game center.
I notice that the status bar would be drawn translucent if there is a navigation bar under it. But I want a translucent status bar BY ITSELF.
Is there any way to do this?
A:
As the status bar is totally transparent and any content can go on top of it, I just create an empty UIToolbar that is 20px height which just looks like a perfect translucent background for the status bar.
This is not an ultimate solution, but it really helps and it is very easy to implement when you don't need a real tool bar.
Thanks to Apple that they do not provide an option to set the status bar from transparent to translucent.
|
[
"stackoverflow",
"0021767061.txt"
] | Q:
Linux Kernel Module Character Device Permissions
Is it possible to create a character device in a linux kernel module that starts off mod 666? Right now it's always 600 (owned by root), and I have to chmod it. I could create udev entries to resolve it, but I'ld really rather the module do it automagically.
Is it possible? I can't find any information in the cdev_init or cdev_add documentation on this.
A:
You can do it by setting the dev_uevent method in the class structure. In this method you have to set the DEVMODE uevent variable. Here an example
static int my_dev_uevent(struct device *dev, struct kobj_uevent_env *env)
{
add_uevent_var(env, "DEVMODE=%#o", 0440);
return 0;
}
static struct class my_class = {
.name = "myname",
.owner = THIS_MODULE,
.dev_uevent = my_dev_uevent,
[...]
};
|
[
"stackoverflow",
"0034977307.txt"
] | Q:
Add config file MailSettings to PropertyGrid
I'm busy building a quick little WinForms app that allows editing of a provided app.config file. I created a wrapper around the System.Configuration.Configuration class, exposing only the properties I want changed. I've done AppSettings and ConnectionStrings (using SqlConnectionStringBuilder) and now I'm moving onto system.net/mailSettings.
Here's the gist of my current structure:
public class ServerConfigFile : ConfigFile
{
...
[Category("Database Connection Settings")]
[DisplayName("Connection String")]
[RefreshProperties(RefreshProperties.All)]
[Description("The connection string used to connect to the datasource. Default is \"(LocalDB)\\v11.0\"")]
public ConnectionStringBuilderFacade ConnectionString { get; private set; }
...
protected override void ReloadProperties()
{
this.ConnectionString = new ConnectionStringBuilderFacade(this.UnderlyingConfig.ConnectionStrings.ConnectionStrings["EntitiesContainer"]);
...
this.MailSettings = this.UnderlyingConfig.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;
}
}
public abstract class ConfigFile
{
protected Configuration UnderlyingConfig { get; private set; }
...
public void RefreshFromFile(string exeFile)
{
this.UnderlyingConfig = ConfigurationManager.OpenExeConfiguration(exeFile);
this.ReloadProperties();
}
protected abstract void ReloadProperties();
}
I've been able to source the MailSettings from the config file:
this.MailSettings = this.UnderlyingConfig.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;
but since this was meant to be a quick app, I'm not quite ready to invest the time to write out a whole TypeConverter and UITypeEditor just for one small section.
It can be seen that what's needed are - smtp settings, delivery methods, pickup locations (if delivery method is specifiedDirectory), ssl, username, password...
My question: is there any existing PropertyGrid editor for MailSettings that I can plug and play, or do I have to bite the bullet and roll out my own, or do you fine people have an even better solution for me?
A:
So I ended up rolling out my own slapped together solution. I mapped the properties in the MailSettingsSectionGroup class to my own config class and just ran with it. something like the below:
[Browsable(false)]
public MailSettingsSectionGroup MailSettings { get; private set; }
[Category(MailSettingsCategory)]
[DisplayName("Pickup Directory Location")]
[RefreshProperties(RefreshProperties.All)]
[Description("The folder where to save email messages to be processed by an SMTP server.")]
[Editor(typeof(FolderNameEditor), typeof(UITypeEditor))]
public string SmtpPickupDirectoryLocation
{
get
{
return this.MailSettings.Smtp.SpecifiedPickupDirectory.PickupDirectoryLocation;
}
set
{
this.MailSettings.Smtp.SpecifiedPickupDirectory.PickupDirectoryLocation = value;
}
}
...
The output:
|
[
"stackoverflow",
"0011513561.txt"
] | Q:
Find a good homography from different point of view of objects?
I am doing object detection using feature extraction (sift,orb).
I want to extract ORB feature from different point of view of the object (train images) and then matching all of them with a query image.
The problem I am facing is: how can I create a good homography from keypoint coming from different point of view of the image that have of course different sizes?
Edit
I was thinking to create an homography for each train images that got say 3-4 matches and then calculate some "mean" homography...
The probleam arise when you have for example say just 1-2 matches from each train image, at that point you cannot create not even 1 homography
Code for create homography
//> For each train images with at least some good matches ??
H = findHomography( train, scene, CV_RANSAC );
perspectiveTransform( trainCorners, sceneCorners, H);
A:
I think there is no point on doing that as a pair of images A and B has nothing to do with a pair of images B and C when you talk about homography. You will get different sets of good matches and different homographies, but homographies will be unrelated and no error minimization would have a point.
All minimization has to be within matches, keypoints and descriptors considering just the pair of images.
There is an idea similar to what you ask in FREAK descriptor. You can train the selected pairs with a set of images. That means that FREAK will decide the best pattern for extracting descriptors basing on a set of images. After this training you are supposed to find more robust mathces that will give you a better homography.
A:
To find a good homography you need accurate matches of your keypoints. You need 4 matches.
The most common methos is DLT combined with RANSAC. DLT is a linear transform that finds the homography 3x3 matrix that proyects your keypoints into the scene. RANSAC finds the best set of inliers/outliers that satisfies the mathematicl model, so it will find the best 4 points as input of DLT.
EDIT
You need to find robust keypoints. SIFT is supossed to do that, scale and perspective invariant. I don't think you need to train with different images. Finding a mean homography has no point. You need to find an only homography for an object detected, and that homography will be the the transformation between the marker and the object detected. Homography is precise, there is no point on finding a mean.
|
[
"stackoverflow",
"0051231943.txt"
] | Q:
How to align the x-axis of a line and bar plot in one figure?
I'm using Pandas within Jupyter to try and draw the counts of one field (bar plot) and the average of another field (line plot) in one figure. My data is within one data frame, and renders OK if I just plot the data frame directly. However, I want the line graph to have a secondary_y axis while sharing the x-axis, so I am using the following code:
mobs_by_cr = data_frame.groupby("cr").agg({'hp': np.mean, 'cr': np.size})
ax = mobs_by_cr["cr"].plot(kind="bar", colormap='Paired')
mobs_by_cr["hp"].plot(kind="line", ax=ax, secondary_y=True)
If I graph either of those columns by itself then it lines up correctly with the x-axis. But when I try to get them both on the same figure by passing in ax=ax then they're mis-aligned.
Looking at the data, the dip in the line graph should be at 18 on the x-axis, not at 15.
hp cr
cr
0.000 3.848485 33.0
0.125 8.166667 24.0
0.250 14.522727 44.0
0.500 20.025000 40.0
1.000 28.710526 38.0
2.000 43.126984 63.0
3.000 59.205882 34.0
4.000 74.650000 20.0
5.000 96.114286 35.0
6.000 105.823529 17.0
7.000 111.090909 11.0
8.000 114.285714 14.0
9.000 149.700000 10.0
10.000 154.750000 8.0
11.000 178.700000 10.0
12.000 128.000000 5.0
13.000 173.333333 9.0
14.000 185.200000 5.0
15.000 175.166667 6.0
16.000 213.400000 5.0
17.000 252.428571 7.0
18.000 80.000000 1.0
19.000 262.000000 1.0
20.000 310.000000 3.0
21.000 273.750000 4.0
22.000 414.500000 2.0
23.000 438.250000 4.0
24.000 546.000000 2.0
30.000 676.000000 1.0
The data: 'cr,hp,cr\n0.0,3.8484848484848486,33.0\n0.125,8.166666666666666,24.0\n0.25,14.522727272727273,44.0\n0.5,20.025,40.0\n1.0,28.710526315789473,38.0\n2.0,43.12698412698413,63.0\n3.0,59.205882352941174,34.0\n4.0,74.65,20.0\n5.0,96.11428571428571,35.0\n6.0,105.82352941176471,17.0\n7.0,111.0909090909091,11.0\n8.0,114.28571428571429,14.0\n9.0,149.7,10.0\n10.0,154.75,8.0\n11.0,178.7,10.0\n12.0,128.0,5.0\n13.0,173.33333333333334,9.0\n14.0,185.2,5.0\n15.0,175.16666666666666,6.0\n16.0,213.4,5.0\n17.0,252.42857142857142,7.0\n18.0,80.0,1.0\n19.0,262.0,1.0\n20.0,310.0,3.0\n21.0,273.75,4.0\n22.0,414.5,2.0\n23.0,438.25,4.0\n24.0,546.0,2.0\n30.0,676.0,1.0\n'
A:
A pandas bar graph is a categorical plot. This means that the values are essentially plotted against their integer index, independent on what the x values would show numerically. Judging from the comments above this is what you would like to have.
A line plot is not categorical. It will plot against the numeric index values. Putting both kinds of plots in the same graph would fail. Also, there is no "categorical line plot" available.
But of course you can plot the line by plotting the values against their integer index as well.
Suppose you have the following dataframe
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({"x" : [1, 2.75, 100], "y1" : [1,2,3], "y2" : [300,100,275]})
df.set_index("x", inplace=True)
print(df)
# y1 y2
# x
# 1.00 1 300
# 2.75 2 100
# 100.00 3 275
You may plot the bar graph of y1 as in the question, but for the line plot make x a propper column first and instead of plotting y2 against the x values, plot it against a newly established integer index.
ax = df["y1"].plot(kind="bar")
df.reset_index()["y2"].plot(kind="line", ax=ax, secondary_y=True)
|
[
"english.stackexchange",
"0000017162.txt"
] | Q:
Referring to "the assertion made in the US Supreme Court's majority opinion"
I want to refer to an assertion that is part of the written majority opinion in a particular case, put forth by the US Supreme Court's majority for that case.
Question spurred by my attempts to do this in a comment to Non-religious mentions of God (or religious concepts) in the American English language .
How can I say this succinctly and correctly? I'm assuming that there may be legal terminology and journalistic conventions I should be aware of.
I don't think "the Court's majority opinion's assertion" is especially desirable, for instance.
A:
I'm not sure if this exactly answers your question, but I read a lot of legalese as part of my day job, and I've never seen a reference to any court's "claim." Plaintiffs and defendants make many "claims," but courts' opinions contain findings and conclusions. "Claims" has an aura of advocacy -- something the courts don't engage in (not officially, at least).
Also, depending on context, you might not need to say "majority." You only need to specify if you're quoting from a dissent or a concurring opinion, or if you're contrasting the majority opinion with a dissent or a concurrence.
If I were writing the comment you mention, I might say something like
The Court found that . . . .
I don't find anything grammatically wrong with your version, though.
A:
If you find that a possessive form is clumsy, as for instance because multiple possessives would end up being used in the same sentence, you can generally rephrase the possessive structure as a prepositional phrase or similar construct. Usually A's B can be alternatively phrased as B of A or perhaps as B belonging to A if the idea of ownership needs to be emphasized. So you might choose to transform one or both of the possessives in the Court's majority opinion's claim; if both possessive were to be eliminated, the result might be the claim in the majority opinion of the Court.
|
[
"stackoverflow",
"0000669981.txt"
] | Q:
Killing a process on exit
My project has an object that creates a process. It this object's Dispose function, it kills the process (or tries to). However, if the program crashes, it leaves the process running and doesn't clean up. Which causes the program to fail next time because it tries to launch the process again and can't get a lock on it.
How can I make sure this process is killed? I always use the object that creates the process in a using block
For reference I'm using C# and .NET 3.5
A:
Define "crashes"; there are different levels of crash... for example, if something actively kills your process, you will have very little chance to run any Dispose/finalizers etc - but if your thread unwinds gracefully (even through exception), you should be OK (since you are using using). Can you clarify what the setup is?
|
[
"stackoverflow",
"0030327533.txt"
] | Q:
what is the environment variable for 'app alias' on OpenShift?
I have checked all the variables listed on the official link,
For a deployed app on openshift, How do i get the alias of the app?
I've added subdomain.example.com as the alias, but the variable OPENSHIFT_APP_DNS is just showing the *.rhcloud.com address but not the alias added, how do I access the alias with environment variables?
A:
There is not currently an environment variable that holds this information within your application. If you need to retrieve it programmatically you might check into the OpenShift Online API (https://access.redhat.com/documentation/en-US/OpenShift/2.0/html/REST_API_Guide/)
|
[
"stackoverflow",
"0009058343.txt"
] | Q:
SQL Multiple Entry Syntax
I'm having trouble finding out the proper syntax for selecting from a table all entries that have a multiple occurrence, and was hoping somebody would be able to point me in the right direction.
This IS homework, so please answer it in a way that abides by the rules and doesn't make me a cheater. Thank you!
A:
You can GROUP BY whatever defines a row having multiple occurrence, then select only those HAVING COUNT(*) > 1 like this:
SELECT col1, col2
FROM theTable
GROUP BY col1, col2
HAVING COUNT(*) > 1
|
[
"stackoverflow",
"0044449729.txt"
] | Q:
Prevent validation when you have hide field Codeigniter
I am doing an airline reservation and I have 2 radio button.
1) One way
2) Round Trip
The things that I've done is when I select the Round Trip, all the fields are there(Depart, return and number of passengers) but I when select One way radio button the return field should hide.
In my controller, I have validation that all fields are required. The problem is, whenever I tried to search in One Way(the return field is hidden) it gives me an "Return field is required" error
Question: How can I prevent the validation in return field when I choice the One Way radio button?
View
<div class="pure-u-1-1 searchcontainer center">
<div class="pure-u-1-1 findcheaptxt">
<span>Find Cheap Flights</span>
</div>
<div class="pure-u-1-1 radiobtn">
<form action="">
<input type="radio" name="flight_type" value="one_way" class="onew" style="" >One Way
<input type="radio" name="flight_type" class="roundw" style="" checked>Round Trip
</form>
</div>
<form method="post" enctype="multipart/form-data" action="<?= base_url() .'User/search'?>">
<?= validation_errors(); ?>
<div class="pure-u-1-1 fromto">
<div class="pure-u-1-1">
<label for="from" class="margin2px">From</label>
<select name="flight_from">
<option value="">-- Please select depature --</option>
<?php foreach($countries as $country):?>
<option value ="<?= $country->country_name?>" ><?= $country->country_name?></option>
<?php endforeach?>
</select>
</div>
<div class="pure-u-1-1">
<label for="to" class="tomargin">To</label>
<!-- <input type="text" class="fromto"><br> -->
<select class="fromto" name="flight_to">
<option value="">-- Please select destination --</option>
<?php foreach($countries as $country):?>
<option value ="<?= $country->country_name?>" ><?= $country->country_name?></option>
<?php endforeach?>
</select>
</div>
<div class="pure-u-1-1 dr" name ="depart">
<label for="depart" class="drr">Depart</label>
<input type="date" id="depart" name="depart" class="departreturn">
</div>
<div class="pure-u-1-1 dr" id="try">
<label for="return" class="drr">Return</label>
<input type="date" id="return" name="return" class="departreturn"><br>
</div>
</div>
<div class="pure-u-1-1 personfield">
<!-- <div class="pure-u-1-5 margin">
Adult<br>
<input type="text" name="" class="person">
</div>
<div class="pure-u-1-5 margin">
Seniors<br>
<input type="text" name="" class="person">
</div>
<div class="pure-u-1-5 margin">
Children<br>
<input type="text" name="" class="person">
</div>
<div class="pure-u-1-5">
Class<br>
<input type="text" name="" class="person">
</div> -->
<div class="pure-u-1-5 margin">
Number of Passengers<br>
<input type="text" name="no_of_passengers" class="person">
</div>
</div>
<div class="pure-u-1-1 center">
<button class="submitbtn">Search Now</button>
</form>
</div>
</div>
</div>
Controller
public function search()
{
$data['countries'] = $this->CrudModel->get('countries');
$this->form_validation->set_error_delimiters('<div class="alert alert-danger" role="alert">', '</div>');
$this->form_validation->set_rules('flight_from', 'Select depature', 'required|trim');
$this->form_validation->set_rules('flight_to', 'Select Destination', 'required|trim');
if ($_POST['flight_type'] == 'round_trip')
{
$this->form_validation->set_rules('depart', 'Date of flight', 'required|trim');
$this->form_validation->set_rules('return', 'Date of return', 'required|trim');
$this->form_validation->set_rules('no_of_passengers', 'Number of Passengers', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->index();
}
else
{
$search_result = array(
$flight_from = $_POST['flight_from'],
$flight_to = $_POST['flight_to'],
$depart = $_POST['depart'],
$return = $_POST['return'],
$no_of_passengers = $_POST['no_of_passengers']
);
$data['search_result'] = $this->CrudModel->search('flight',$flight_from,$flight_to,$depart,$return,$no_of_passengers);
$this->load->view('partials/header');
$this->load->view('partials/nav');
$this->load->view('result',$data);
}
}
else
{
$this->form_validation->set_rules('depart', 'Date of flight', 'required|trim');
$this->form_validation->set_rules('no_of_passengers', 'Number of Passengers', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->index();
}
else {
$search_result = array(
$flight_from = $_POST['flight_from'],
$flight_to = $_POST['flight_to'],
$depart = $_POST['depart'],
$no_of_passengers = $_POST['no_of_passengers']
);
$data['search_result'] = $this->CrudModel->search('flight',$flight_from,$flight_to,$depart,$no_of_passengers);
$this->load->view('partials/header');
$this->load->view('partials/nav');
$this->load->view('result',$data);
}
}
}
My ajax/js when hiding the return field
<script type="text/javascript">
$(document).on('change', 'input:radio[name=flight_type]', function(){
$('div[id^="try"]').toggle(); // hide all DIVs begining with "my_radio_"
$('#' + $(this).attr('id') + '_text').show(); // show the current one
});
</script>
A:
First of all you have to add value to round trip:
<input type="radio" name="flight_type" value="round_trip" class="roundw" style="" checked>Round Trip
Then do validation condition like below:
// Global validation for this method
if ($_POST['flight_type'] == 'round_trip')
{
$this->form_validation->set_rules('depart', 'Date of flight', 'required|trim');
$this->form_validation->set_rules('return', 'Date of return', 'required|trim');
}
else if($_POST['flight_type'] == 'one_way'){
// add validation for one way trip
}
|
[
"stackoverflow",
"0019184989.txt"
] | Q:
How can I learn about the state of activity without overriding related functions?
Is there a way to learn about the state of activity without overriding onPause, onResume, etc?
A:
I found answer.
It's about home button but works fine with detecting app state (is it in background or not):
http://tutorials-android.blogspot.com/2013/08/detect-home-button-press-in-android-and.html
|
[
"stackoverflow",
"0009411736.txt"
] | Q:
XmlDocument.SelectSingleNode and prefix + xmlNamespace issue
I have the following string loaded to an XML document:
<?xml version='1.0' encoding='utf-8'?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<soapenv:Fault>
<faultcode>soapenv:Server</faultcode>
<faultstring>El cliente con los parámetros introducidos no existe./faultstring>
<detail>
<ns:ClienteWSDo29Exception xmlns:ns="http://services.do29.imq.es">
<Do29Exception xmlns="http://services.do29.imq.es" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ax211="http://model.do29.imq.es/xsd" xmlns:ax213="http://dto.do29.imq.es/xsd" xmlns:ax29="http://exception.do29.imq.es/xsd" xsi:type="ax29:Do29Exception">
<ax29:classname>class es.imq.do29.dao.ClienteDaoImpl</ax29:classname>
<ax29:trace xsi:nil="true" />
<ax29:previous xsi:nil="true" />
<ax29:method>getCliente</ax29:method>
<ax29:id>1</ax29:id>
<ax29:message>El cliente con los parámetros introducidos no existe.</ax29:message>
</Do29Exception>
</ns:ClienteWSDo29Exception>
</detail>
</soapenv:Fault>
</soapenv:Body>
</soapenv:Envelope>
Then following the case with namespaces in xml i tried:
XmlDocument xmldocu = new XmlDocument();
xmldocu.LoadXml(xml);
XmlNamespaceManager namespaces = new XmlNamespaceManager(xmldocu.NameTable);
namespaces.AddNamespace("ax29", "http://services.do29.imq.es");
XmlNode nodemsgx = xmldocu.SelectSingleNode("//message", namespaces);
XmlNode nodemsg = xmldocu.SelectSingleNode("//ax29:message", namespaces);
But nodemsgx and nodemsg are null :S Whats the correct way to do it?
I used //message becouse i want to get any node of that type not the specific path to this node...
A:
The ax29 prefix in the XML document is set to the "http://exception.do29.imq.es/xsd" namespace, not "http://services.do29.imq.es".
Try this:
namespaces.AddNamespace("ax29", "http://exception.do29.imq.es/xsd");
XmlNode nodemsg = xmldocu.SelectSingleNode("//ax29:message", namespaces);
|
[
"stackoverflow",
"0057076057.txt"
] | Q:
DAX LOOKUPVALUE to return "Undefined" instead of blank?
How to get an alternative result string message "Not found" or "Undefined", if the LOOKUPVALUE function does not find a match? The documentation of the LOOKUPVALUE function mentions it is easily possible by using the fourth parameter. The fourth parameter is optional. But when I type it, I receive an error message.
Here is why I need it. I want a Category of a product which has not been defined in a dictionary yet. It might be a classic scenerio. The dictionary table is updated manually with some lag and thus it does not contain all the unique products which pop up in FactTable. I want to solve it by Bridge table which will automate manual feeding of Dictionary.
I use the following Bridge table.
Bridge =
ADDCOLUMNS(
DISTINCT(UNION(DISTINCT(FactTable[product]), DISTINCT(Dictionary[product])))
, "FoundCategory"
, LOOKUPVALUE(
Dictionary[category]
, Dictionary[product]
, FactTable[product]
--, "Undefined" -- Uncommenting this argument throws error
)
)
Edit. After 2019 update of Power BI, this problem perished. It must have been a sort of a bug. The above code is working. Hurray!
How to force LOOKUPVALUE function to return Undefined string value instead of blank()?
I can think of this:
Bridge =
ADDCOLUMNS(
DISTINCT(UNION(DISTINCT(FactTable[product]), DISTINCT(Dictionary[product])))
, "FoundCategory"
, IF(ISBLANK(
LOOKUPVALUE(
Dictionary[category]
, Dictionary[product]
, FactTable[product])
)
,"Unmapped"
,LOOKUPVALUE(
Dictionary[category]
, Dictionary[product]
, FactTable[product])
)
)
However I wonder if it does not calculate the LOOKUPVALUE twice. If so, what might be more efficient way?
Here are the tables if you would like to recreate the problem.
FactTable:
let
Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WSiwoyElVitWJVkpKzANCMLMgvySxJF8pNhYA", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type text) meta [Serialized.Text = true]) in type table [product = _t])
in
Source
Dictionary:
let
Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WSiwoyElV0lFKKyrNLFGK1YlWKsgvSSzJBwqVpaanliQmAaVjYwE=", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type text) meta [Serialized.Text = true]) in type table [product = _t, category = _t])
in
Source
A:
One other way to do this is to use the LOOKUPVALUE functions alternative value field. This allows you to specify a value returned instead of blank, thus saving having to do a check to see if it is blank.
LOOKUPVALUE in Microsoft's online documentation on the function.
Edit:
Did a quick test in Power BI Desktop and was able to get alternate values to work in a calculated column to an existing model.
LOOKUPVALUE(
Dictionary[category]
, Dictionary[product]
, FactTable[product])
, "Undefined"
)
|
[
"stackoverflow",
"0051588235.txt"
] | Q:
Bootstrap select doesn't update selected options properly
I am using bootstrap select plugin, When the options at bottom of the select is selected the bootstrap select does not refresh the select properly(the previously selected options remains as selected as the boostrap select does not remove the selected class properly),
Do I have to listen the change event on bootstrap select and refresh the options, This is not occurring while having lesser options, What mightbe the solution for this
$('.selectpicker').selectpicker({
});
Js fiddle :
https://jsfiddle.net/aarthi_101/79rz3j1w/18/,
I have posted an issue at github,
https://github.com/snapappointments/bootstrap-select/issues/85
A:
Just refresh when change the select and it'll work well.
The code :
$('select').on('change',function(){
$(this).selectpicker('refresh');
});
|
[
"stackoverflow",
"0033429068.txt"
] | Q:
web2py redirect to a incorrect page
I am learning web2py. I found a redirect error between 2 very simple actions.
This application which I simple modify from the web2py manual is just used to help me to understand the controlflow,request.args and request.vars of web2py.
Here is the code in my default controller,
def index():
redirect(URL("first",args=1))
def first():
return dict()
def second():
return dict()
Then I create the first.html and second.html
first.html is
<h1>What is your name?</h1>
<form action="second">
<input name="visitor_name" />
<input type="submit" />
</form>
second.html is
<h1>Hello {{=request.vars.visitor_name}}</h1>
I input something to the form in the first.html,but when I press the submit button it doesn't redirect to the "second" action. And I found something wrong in the url of the browser
http://127.0.0.1:8000/welcome/default/first/second?visitor_name=zhangsan
I am very confused and do many test. I change the code in the index
from
def index():
redirect(URL("first",args=1))
to
def index():
redirect(URL("first"))
And the redirect make sense. I am vary confused about this. Is this a bug in web2py or I misunderstand the controlflow of web2py?
A:
The book is incorrect (though the source has now been fixed on Github). In <form action="second">, because "second" is not preceded by a "/", the browser interprets it as being relative to the URL of the current page, so it gets appended to the current URL (which is why the form gets submitted to /default/first/second).
Instead, use the URL() helper to generate the proper URL:
<form action="{{=URL('default', 'second')}}">
which will result in the following HTML:
<form action="/welcome/default/second">
In general, it is always best to use the URL() helper to generate internal URLs (particularly if you are using the URL rewrite system, as it will automatically translate the URL based on the rewrite rules).
|
[
"stackoverflow",
"0029398038.txt"
] | Q:
Can't establish a connection using ESP8266 and Arduino uno
I'm using an Arduino Uno Rev3 with ESP8266 to connect into a network and send some data through TCP sockets. I'm using the following code to establish a connection
boolean connectWifi() {
String cmd = "AT+CWJAP=\"";
cmd += SSID;
cmd += "\",\"";
cmd += PASS;
cmd += "\"";
Serial.flush();
Serial.println(cmd);
delay(5000);
if(Serial.find("OK")) {
Serial.println("Connected");
return true;
} else {
Serial.println("Not connected");
return false;
}
}
but everytime I call this function inside the arduino loop(), I receive "Not connected".
I have already tried to connect direct from serial monitor running an empty code on Arduino and this AT command worked very well. Someone have any idea about what is wrong?
Connections:
(Used when I need to send commands right from arduino code)
Arduino ------------ ESP8266
3.3v --------------------- vcc
gnd ---------------------- gnd
3.3v ------------------- CH_PD
TX ------------------------ RX
RX ------------------------ TX
(Used when I need to send commands right from arduino serial monitor)
Arduino ------------ ESP8266
3.3v --------------------- vcc
gnd ---------------------- gnd
3.3v ------------------- CH_PD
TX ------------------------ TX
RX ------------------------ RX
A:
I just uploaded blank.bin into ESP and everything worked fine. There was some example code in conflict with Arduíno.
|
[
"math.stackexchange",
"0001636693.txt"
] | Q:
Cauchy integral formula12
$\int 1/(z^2 + 2i)dz$
I've tried writting it as $1/(z-1+i)*(z+1-i)$ but then it's impossible to find solution.
Any help would be great, thanks in advance.
A:
Let $I$ be the integral given by
$$I=\oint_{|z|=3}\frac{1}{z^2-2i}\,dz$$
We note that the poles of the integrand are at $z= \pm(1+ i)$, both of which are contained in the circle $|z|=3$.
We can decompose the integrand as
$$\frac{1}{z^2-2i}=\frac{1}{2(1+i)}\left(\frac{1}{z-(1+i)} -\frac{1}{z+(1+i)}\right)$$
Then, we have
$$I=\frac{1}{2(1+i)}\left(\oint_{|z|=3}\frac{1}{z-(1+i)} \,dz-\oint_{|z|=3}\frac{1}{z+(1+i)}\right)=\frac{1}{2(1+i)}\left(2\pi i -2\pi i\right)=0$$
|
[
"stackoverflow",
"0053726201.txt"
] | Q:
remove last part of string following '&&&' with JavaScript Regex
I'm trying to use a regex in JS to remove the last part of a string. This substring starts with &&&, is followed by something not &&&, and ends with .pdf.
So, for example, the final regex should take a string like:
parent&&&child&&&grandchild.pdf
and match
parent&&&child
I'm not that great with regex's, so my best effort has been something like:
.*?(?:&&&.*\.pdf)
Which matches the whole string. Can anyone help me out?
A:
You may use this greedy regex either in replace or in match:
var s = 'parent&&&child&&&grandchild.pdf';
// using replace
var r = s.replace(/(.*)&&&.*\.pdf$/, '$1');
console.log(r);
//=> parent&&&child
// using match
var m = s.match(/(.*)&&&.*\.pdf$/)
if (m) {
console.log(m[1]);
//=> parent&&&child
}
By using greedy pattern .* before &&& we make sure to match **last instance of &&& in input.
|
[
"stackoverflow",
"0051862300.txt"
] | Q:
UnauthorizedAccessException for limited permissions user via REST API
not sure if this is the right place to post dev question so please point me to the right place if its not...
I have a customer that gave a user permission to one specific list.
for example:
https://[tenant].sharepoint.com/sites/qa/permissions/lists/tasks
The user cannot browse to the site:
https://[tenant].sharepoint.com/sites/qa/permissions
But he can get to the list with no problems.
When we try to get the list items using REST api, that user gets "UnauthorizedAccessException" error.
Rest API url we tried:
https://[tenant].sharepoint.com/sites/qa/permissions/_api/web/lists/getbytitle('tasks')
https://[tenant].sharepoint.com/sites/qa/permissions/_api/web/lists/getbytitle('tasks')/items
Users with at least read permissions on the site /sites/qa/permissions have no problems getting to both these API endpoints.
Is there a different way to make the REST API work for users with permissions to just one list?
Is there a limitation of the REST API and it does not support that?
Thanks!
(I posted this on technet as well, and will update here if I get an answer there)
A:
You can deactivate the site collection feature Limited-access user permission lockdown mode.
When this feature is activated, users with "Limited access" as permissions have reduced permissions which prevent them from accessing the list item/documents properties. This will cause the Unauthorized Exception error while accessing SharePoint artefacts.
So, go to your Site Settings > Site collection features
And Deactivate the Limited-access user permission lockdown mode feature.
After that, refresh and check.
More details - Enable or disable site collection features
|
[
"physics.stackexchange",
"0000550843.txt"
] | Q:
Friction in the case of a inclined plane
Why is the direction of friction on an inclined plane always "up the incline" when a body goes up or down the plane with pure rolling motion?
A:
Case 1: Ball rolls up the plane. Gravity retards the ball, so its linear velocity will decrease. In order to prevent slipping, angular velocity should also decrease. So friction should provide a torque opposite to the rotation of the ball. This direction turns out to be up the plane at the lower most point of the ball. The diagram should make it understandable.
Case 2 : Ball rolls down the plane. In this case gravity accelerates the particle. So its linear velocity increases. In order to keep up, its angular velocity must also increase. Friction provides torque to increase angular velocity, which turns out to be up the plane as well.
|
[
"stackoverflow",
"0027669836.txt"
] | Q:
Write the value of a variable defined in one form in another form
I've been googling around for the past few hours and am still unsure of an answer regarding the above question. The code is below:
optionsForm.h
public: String^ hostScreenOption;
private: System::Void saveButton_Click(System::Object^ sender, System::EventArgs^ e) {
if (hostScreenTrueRadio -> Checked == true)
{
hostScreenOption = "True";
}
else if (hostScreenFalseRadio -> Checked == true)
{
hostScreenOption = "False";
}
Form::Close();
}
finalForm.h
#include "optionsForm.h"
String^ name;
String^ city;
private: System::Void continueButton_Click(System::Object^ sender, System::EventArgs^ e) {
StreamWriter^ optionsWriter = gcnew StreamWriter("Game Files\\Millionaire\\preferences.txt");
if (nameBox -> Text == "")
{
warningLabel -> Text = "Please must enter your name!";
}
else
{
name = nameBox -> Text;
}
if (cityBox -> Text == "")
{
warningLabel -> Text = "You must enter your city and country!";
}
else
{
city = cityBox -> Text;
}
optionsWriter -> WriteLine (hostScreenOption);
optionsWriter -> WriteLine (name);
optionsWriter -> WriteLine (city);
delete optionsWriter;
Application::Exit();
Process::Start("Game Files\\Millionaire Host Screen.exe");
}
What I have is optionsForm, which is a form with radiobuttons and labels on it for selecting options (each radio button is either true or false) If the true button is clicked, assign the value of "True", as a string, to hostScreenOption and vice versa. On finalForm, the user enters their name, city and country and then presses continue. The text inside the name textbox and the text inside the city textbox are assigned to the string variables name and city respectively. Finally, all these variables are written to a .txt file which is loaded by a separate program. The name and city values are written to the .txt file with no issues, however the hostScreenOption is not. The error I receive is "hostScreenOption - undeclared identifier" which I am confused by since I have declared it as a public variable and have included optionsForm.h. Can any of you point me in the right direction of what I may be doing wrong or what might be a more efficient way of doing what I'm attempting?
A:
The variable in optionsForm.h has to be extern, so: public: extern String ^ hostScreenOption;.
And then you have to redefine it in finalForm.h: String ^ hostScreenOption;
I'm not sure if this is going to work, because I don't know if hostScreenOption is global defined or in a class, you'll have to try.
But why do you use a String ^? It costs a lot of memory, so instead try using a bool and declare it extern and global in optionsForm.h, then do the same as above in finalForm.h: bool hostScreenOption;
At least replace optionsWriter -> WriteLine (hostScreenOption); with an if condition:
if (hostScreenOption)
optionsWriter -> WriteLine ("True");
else
optionsWriter -> WriteLine ("False");
|
[
"unix.stackexchange",
"0000166482.txt"
] | Q:
cat STDIN won't work twice in script
I have a script that outputs various information and the text fields of an html form (method POST). When I attempt to cat <&0, it displays properly. However a few lines down, I try to cat <&0 again and nothing is printed. What am I doing wrong?
....
cat <&0
echo Content length is $CONTENT_LENGTH
cat <&0 | sed -e 's/&/\n/g' | cut -d'=' -f2
....
A:
You are doing nothing wrong: this is what we should expect.
The first cat <&0 consumes the entire contents of standard input because that's what cat does: it reads all of its input until the end.
When the second cat <&0 runs, there is nothing left to consume on standard input: the end of file was already reached previously.
If, in a shell script, you need to make 2 or more passes through your standard input, you have to dump it into a temp file, then process the temporary file as many times as you want.
Securely creating temporary files in /tmp and making sure they are correctly disposed of when your script terminates or dies is left as an exercise for you :-)
By the way, the <&0 is unnecessary and does nothing. Its function is to point standard input to file descriptor 0... which is standard input... which is by definition where standard input already points! You can just make that command cat alone instead.
A:
If you want to read from standard input twice, you need to buffer it somehow (most likely, in a temporary file). The first cat can be replaced by a call to tee which also writes the data to a file, which can be reread by the second call to cat (which is not necessary either; sed can read from the file directly).
tee > input_buffer # Copy standard input to a file and standard output
echo Content length is $CONTENT_LENGTH
sed -e 's/&/\n/g' input_buffer | cut -d = -f2
|
[
"stackoverflow",
"0033761801.txt"
] | Q:
Plotting multiple heat maps gnuplot
I have been attempting to plot two heat maps with data from two data files using gnuplot. I have plotted heat maps using gnuplot before, but never tried to "overlay them".
My attempt is as follows:
set terminal pngcairo
set xrange[-2:2]
set yrange[-2:2]
unset surface
set view map
set pm3d
set size square
set key outside
set pm3d depthorder
splot "file_1" u 1:2:3 w pm3d notitle, \
"file_2" u 1:2:3 w pm3d notitle
This produces the following output:
There is a faint ring which corresponds to one of the data files but this is not what is desired. By removing the map you can see what the data looks like:
So the first plot has plotted the outer, lower ring but seems to have not plotted the inner taller ring even though it has registered its scale. What I am looking for is a view of this second plot from above.
By manipulating the view of this 3-D plot, I can do this:
but is there a way to obtain a top down view of this plot without having to set the view, and by just using the view map and splot commands? The view method does not look as good, and I would like to know why it does not behave as expected.
Thank you in advance
A:
In the meantime that the bug will be fixed you can use the following workaround:
max(a,b)=(a>b)?a:b
splot "<paste file_1 file_2" u 1:2:(max($3,$6)) w pm3d notitle
Because in this case depth ordering is equivalent to sorting the z values.
|
[
"stats.stackexchange",
"0000419484.txt"
] | Q:
Confusion about proof in "Representation Learning with Contrastive Predictive Coding"
In the Appendix A.1 of the paper "Representation Learning with Contrastive Predictive Coding", the author prove $\log N-\mathcal L_N$ is the lower bound of mutual information between $x_{t+k}$ and $c_t$, $I(x_{t+k}, c_t)$, where and $N$ is the number of sample(one positive sample $x_{t+k}$ and N-1 negative samples $x_j\in X_{neg}$) and $\mathcal L_N$ is roughly the noise contrastive estimation loss defined as
$$
\mathcal L_N=-\mathbb E_X\left[\log {f_k(x_{t+k}|c_t)\over\sum_{x_j\in X}f_k(x_j|c_t)}\right]\\
where\quad f_k(x_{t+k},c_t)\propto{p(x_{t+k}|c_t)\over p(x_{t+k})}
$$
Here is the proof they provide
I'm confused about Equation 9: why is $E_{x_j}{p(x_j|c_t)\over p(x_j)}$ equal to 1?
A:
Letting $\nu$ be the dominating measure of these densities (and assuming it's the same), we'll have
$$
E_{x_j}\left(\frac{p(x_j\mid c_t)}{p(x_j)}\right) = \int \frac{p(x_j\mid c_t)}{p(x_j)} p(x_j)\,\text d\nu(x_j) \\
= \int p(x_j\mid c_t)\,\text d\nu(x_j) = 1.
$$
We don't have to worry about $0/0$ issues since that happens on areas with zero probability under $p(x_j)$.
|
[
"math.stackexchange",
"0003066413.txt"
] | Q:
Simplify $\frac{\sqrt{mn^3}}{a^2\sqrt{c^{-3}}} * \frac{a^{-7}n^{-2}}{\sqrt{m^2c^4}}$ to $\frac{\sqrt{mnc}}{a^9cmn}$
I need to simplify $$\frac{\sqrt{mn^3}}{a^2\sqrt{c^{-3}}} \cdot \frac{a^{-7}n^{-2}}{\sqrt{m^2c^4}}$$
The solution provided is: $\dfrac{\sqrt{mnc}}{a^9cmn}$.
I'm finding this challenging. I was able to make some changes but I don't know if they are on the right step or not:
First, I am able to simplify the left fractions numerator and the right fractions denominator:
$\sqrt{mn^3}=\sqrt{mn^2n^1}=n\sqrt{mn}$
$\sqrt{m^2c^4}=m\sqrt{c^2c^2} = mcc$
So my new expression looks like:
$$\frac{n\sqrt{mn}}{a^2\sqrt{c^{-3}}} \cdot \frac{a^{-7}n^{-2}}{mcc}$$
From this point I'm really at a loss to my next steps. If I multiply them both together I get:
$$\frac{(n\sqrt{mn})(a^{-7}n^{-2})}{(a^2\sqrt{c^{-3}})(mcc)}.$$
Next, I was thinking I could multiply out the radical in the denominator but I feel like I need to simplify what I have before going forwards.
Am I on the right track? How can I simplify my fraction above in baby steps? I'm particularly confused by the negative exponents.
How can I arrive at the solution $\dfrac{\sqrt{mnc}}{a^9cmn}$?
A:
\begin{align}
\frac{\sqrt{mn^3}}{a^2\sqrt{c^{-3}}} \cdot \frac{a^{-7}n^{-2}}{\sqrt{m^2c^4}} &= \frac{\sqrt{mn^3}}{a^2\sqrt{c^{-3}}} \cdot \frac{1}{a^7n^{2} mc^2}\\
& = \frac{\sqrt{mn^3}}{a^2} \cdot \frac{\sqrt{c^{3}}}{a^7n^{2}mc^2} \\
& = \frac{\sqrt{m}n\sqrt{n}c\sqrt{c}}{a^9 n^{2}m c^2} \\
& = \frac{\sqrt{nmc}}{a^9 n m c} \\
\end{align}
A:
$$\frac{\sqrt{mn^3}}{a^2\sqrt{c^{-3}}}\cdot\frac{a^{-7}n^{-2}}{\sqrt{m^2c^4}} = \frac{\sqrt{mn^3}a^{-7}n^{-2}}{a^2\sqrt{m^2c^{-3}c^4}}$$
From here, you use the following identity:
$$a^{-b} = \frac{1}{a^b}$$
You can simplify from here:
$$= \frac{\sqrt{mn^3}}{a^9n^2\sqrt{m^2c}} = \frac{\sqrt{n^3}}{a^9n^2\sqrt{mc}} = \color{blue}{\frac{\vert n\vert\sqrt{n}} {a^9n^2\sqrt{mc}}} = \color{green}{\frac{\sqrt{nmc}}{a^9cm\sqrt{n^2}}} = \frac{\sqrt{nmc}}{a^9cm\vert n\vert}$$
Notice the step highlighted in blue. Clearly, when dealing with real numbers, the radicand must be non-negative (and the denominator can’t be $0$), so $mc > 0$. Therefore, in the next step, we can note that $nmc > 0$, and since $mc > 0$, then $n > 0$, so the absolute value of $n$ is $n$ itself. (Mathematically, $\vert n\vert = n$.) Hence, the final result becomes
$$\frac{\sqrt{nmc}}{a^9cmn}$$
Addition: This is, of course, not to make the problem seem more confusing than it actually is. However, it is a common error to forget the absolute value sign when dealing with even indices. $\sqrt{a^2}$ is not $a$, it’s $\vert a\vert$ because $a$ itself may be negative, but the returned value is always non-negative. For example, $\sqrt{(-2)^2} = \sqrt{4} = 2 = \vert -2\vert$. (This also applies to all even indices, such as fourth roots, sixth roots, etc. Always be careful when dealing with these.)
|
[
"stackoverflow",
"0029333407.txt"
] | Q:
Meteor {{#markdown}}
I am making a forum with markdown support.
I've been using meteor's markdown parser {{#markdown}} and have found something disturbing that I can't seem to figure out.
I am using {{#markdown}}{{content}}{{/markdown}} to render the content inserted into database.
The disturbing thing, for example, if someone writes up html without inserting it into the code block in the content...
example
<div class = "col-md-12">
Content Here
</div>
This will render as a column. They could also make buttons and etc through writing the HTML for it.
How to disable this behaviour so that when HTML is written it will not render into HTML but just simply show it as text?
A:
You can write global helper, which will strip all html tags:
function stripHTML(string){
s = string.replace(/(<([^>]+)>)/ig, '');
return s;
}
Template.registerHelper('stripHTML', stripHTML)
Usage :
{{#markdown}}{{stripHTML content}}{{/markdown}}
Test it in console:
stripHTML("<div>Inside dive</div> Text outside")
|
[
"stackoverflow",
"0052523561.txt"
] | Q:
Azure Functions VS Deploy Environment Variables
I'm developping the Azure Functions in VS2017. I'm using several environment variables. Is there a way when deploying to have them create when they don't exist.
I understand that they should not be copied (values) each time as on production they will have different values then in dev.
But creating a empty variable would be nice, is there a way or am I doing something wrong. Now I've stored them as indicated in the local file ...
A:
Environment variables are usually stored in Application settings on portal, and empty values are not allowed.
As you know there could be difference between production and dev, I recommend you to set Application settings in VS when publishing. VS provides a friendly UI with both remote and local settings, you can choose to insert from local or create new settings.(Note the empty value here means there's no such setting in corresponding environment)
|
[
"stackoverflow",
"0019254681.txt"
] | Q:
Rails, how can I make a synchronous serial queue than works in multi-thread/process
In my Rails 4 with Ruby 2 app I've the following model:
A Playlist can have many Tracks and each Track has its position in its Playlist. For each new Track I want to set its position to be the last, in thread-safe and/or multi-process-safe way.
In my research I found a bunch of projects that handle background jobs but I don't want this to be background, I want it to be synchronous. So the caller of my API will get the response with the correct position.
The question is: what's the best way to make a synchronous serial queue that will be used to set the position of a Track in its Playlist?
A:
If you want it to be synchronous, then you don't need a queue. Instead you'd just wrap a bit of code in a transaction where you find the last track position for that playlist, then set the position of the new track to be one more, then save the new track. Something like this (assuming you're in a controller action):
@playlist = Playlist.find params[:id]
@track = Track.new params[:track]
@playlist.transaction do
last_track = @playlist.tracks.order("posistion desc").first
@track.position = last_track.position + 1
@track.save
end
|
[
"stackoverflow",
"0045275438.txt"
] | Q:
css transition is not trigger by add classes in a same function
when I click the window, CSS transition is not trigger.
const div = document.querySelector('div');
window.onclick = function() {
div.classList.add('fade');
div.classList.add('in');
}
.fade {
opacity: 0;
}
.fade.in {
transition: opacity 2s linear;
opacity: 1;
}
<div>aaaa</div>
then I change the script, use setTimeout to add the second class in, it works.
const div = document.querySelector('div');
window.onclick = function() {
div.classList.add('fade');
setTimeout(function() {
div.classList.add('in');
});
}
.fade {
opacity: 0;
}
.fade.in {
transition: opacity 2s linear;
opacity: 1;
}
<div>aaaa</div>
so I think, is nees a period time between CSS property change can trigger CSS transition?
so i add the time between add classes. it also not work.
<script>
window.onclick = function(){
div.classList.add('fade');
for(var i=0;i<10000; i++){
console.log(i);
}
div.classList.add('in');
}
</script>
why change classes in a same function can not trigger a css transition?
A:
If we go deeper in working of JavaScript V8 engine, the execution could be broken down which could clarify the current behavior. JavaScript is single threaded, more precisely
one thread == one call stack == one thing at a time
As shown above setTimeout is part of WebAPIs which comes within browser. The priority of WebAPIs is lower than 'stack' methods which are core JavaScript functions.
As mentioned above "This is the crucial part: making multiple changes to an element's classList does not cause the element to be redrawn with each change"
The reason for this is "Render Queue" which is functional part of V8 architecture as shown below:
The rendering happens between the 'stack' method execution. After all the stack is empty 'event loop' is triggered and it pulls any method which was passed to WebAPIs. This is the reason, in second scenario when the script is changed to use setTimeout, it works.
More detailed explanation of this can be seen on Philip Roberts blog
https://youtu.be/8aGhZQkoFbQ
|
[
"health.meta.stackexchange",
"0000000018.txt"
] | Q:
Are questions about Medical History on-topic?
Though this question is completely unrelated, it got me thinking. Should we allow questions about Medical History to be asked here? I was thinking that one of these questions could be like
When was {disease} first identified?
or
What led to the myth that {medical myth} is true?
I do think that these types of questions would be interesting, but would they be a good fit here?
A:
I would think they would be on topic as they can easily relate to current medical issues. There might be some controversy over some topics as some are considered myth by some people and considered fact by others. An example of this is the debate over vaccination and you will find people on both sides of that posting on this site.
The main problem will be keeping them from becoming primarily opinion based rather then fact based.
A:
The site claims to be for "health-related questions". History is not really health related to me. It might be a sub-topic of a discussion, if someone wants indication about difference between current and old medications for example, but purely historical question seems off-topic to me.
Furthermore:
When was {disease} first identified?
Is encyclopaedia question, so definitely not worth here.
What led to the myth that {medical myth} is true?
Is probably primarily opinion based.
|
[
"scifi.stackexchange",
"0000127352.txt"
] | Q:
Who was in the original Marvel A-list?
I keep reading that Iron Man was not really in the Marvel A-list until the first Iron Man movie.
So which characters were in the A-list before the MCU started?
These were two of the articles I read that referred to Iron Man as a former B-lister:
"On This Day Eight Years Ago 'Iron Man' Was Released, Changing Marvel Studios Forever" – Forbes
"Iron Man? Thor? Which B-List Superhero Has The Brawn To Make It Big?" – Mtv News
The honest trailer for Iron Man also refers to him as a B-list superhero.
The article "Reality Check: There are only about half a dozen A-list superheroes" on IO9 defines an "A-lister" as a character thus.
How can you tell if a hero is an "A" lister? It's partly about exposure beyond comics, including things like Saturday morning cartoons that help get a particular character into the minds of children. Or just the sheer amount of merchandising a particular character spawns at Toys 'R' Us. But also, the real "A" list heroes have already had multiple films at this point — and in the case of Superman, there was a TV show that lasted 10 years.
So for the context of this question, could we define an "A-lister" as a character that generates income in more ways than just the comics, and thus is more bankable?
A:
This could be quite a broad topic so first of all
What defines an A lister?
Dictionary.com defines an A-lister as:
A group of desirable or admired people who are welcomed especially in social and professional situations:
e.g.Hollywood's A list turned out for the Oscars.
In celebrity term it is usually the pull that celebrity has, or how Bankable they are.
This is measured on the Ulmer Scale named after James Ulmer.
The Ulmer scale is a 100-point method used to quantify a star's value to a
film production, in terms of getting a movie financed and the cameras
rolling. The Ulmer Scale also takes into account an actor's history
(box office successes vs. failures), versatility, professional
demeanor, and ability and willingness to travel and promote movies.
Bankability of Marvel Heroes
We can work out similar Bankability with the Marvel comic book heros if we can work out how many comics they have sold.
If we take DC's undisputed A-list as an example they have the Trinity of Batman, Superman and Wonderwoman, this is pretty universally accepted as their big hitters.
Lets try to find out Marvel's Trinity...
Now there are A LOT of comics that have been sold over the decades and I do not have a month to try to collect all these together and come up with an answer.
However
Using the figures provided on Comichron I have managed to get the figures from the 60s (1960-1969) and one year in the 90s (there was A LOT more figures from the 90s), 1995 to be precise.
I chose 1995 because it should be close enough to present day to give an idea on current popularity but be far enough removed from films that could skew the popularity.
1960's
Taking the 1960s as a whole the sales looked like this:
Title Avg Sales
Tales to Astonish/Incredible Hulk 2,173,925
Tales of Suspense/Captain America 2,103,794
Rawhide Kid 1,553,267
Amazing Spider-Man 1,447,473
Fantastic Four 1,344,143
Strange Tales/Doctor Strange 1,273,947
Thor 1,156,209
Sgt. Fury and his Howling Commandos 1,059,073
Avengers 1,056,070
X-Men 1,030,275
Kid Colt Outlaw 929,967
Journey into Mystery 757,727
Daredevil 537,845
This would give a Trinity of The Hulk, Captain America and Spiderman (ignoring Rawhide Kid for the fact we don't hear too much about him now)
1995
The figures below are not pure sales but are the index attributed by the Diamond Comic Distributors. The higher the number the more sales.
Title Diamond Comic Distributors
Order Index (Combined for all Titles)
X-Men (and Spin offs) 10460.4
Spider-Man (and Spin offs) 3481.3
Fantastic Four (and Spin offs) 1129.54
The Hulk 557.58
Punisher 555.51
Avengers 539.02
Ghost Rider 370.55
Iron Man (and Spin offs) 360.08
Captain America 254.49
Daredevil 214.39
Thor 162.45
Doctor Strange 127.45
Guardians of the Galaxy 121.23
Phantom 75.23
Blaze 68.46
Nova 66.3
Namor 49.1
Blade the Vampire Hunter 34.8
The Trinity at this point has shifted a little with X-Men being undisputed kings, with Spider-Man and the Fantastic Four completing the set but quite a way behind.
I don't think it is a coincidence that these three were sold off when Marvel needed money to stop them from going bankrupt.
So Spider-Man and the Fantastic Four have been around the top for quite a while, whereas X-Men had a massive resurgence and most of the MCU characters had suffered a dramatic drop off pre-MCU.
Iron Man is quite a way down on the list from the 90s, as are Captain America and Thor. The Hulk Sits in fourth but his film rights were also sold off as Marvel needed the cash.
|
[
"stackoverflow",
"0021952686.txt"
] | Q:
Firefox executes both if and else?
I run into this pretty weird thing into firefox, probably I'm missing something but somehow both the if and the else clause in the following code gets executed?
if($.fx.off)
{
widget.css({opacity: 1});
}
else
{
widget.delay(delay).animate({top: "+=100"},10).animate({top: "-=100",opacity: 1}, 1000);
}
When tracing ff starts with the if line, moves to: widget.css({opacity: 1});, and afterwards it continues executing: widget.delay(delay).animate({top: "+=100"},10).animate({top: "-=100",opacity: 1}, 1000);??
Anybody a clue what is going on?
$.fx.off is defined as off in this case.
A self contained minimal example would be:
$.fx.off = false;
if($.fx.off)
{
alert('me');
}
else
{
alert('and me to!');
}
However I doubt it replicates....
A:
The problem is caused by 2 individual faults. One i made an error somewhere else in the code, which excecutes a code pretty similar to the else case, so it seemed the else case was executed. and the second the debug (step by step) in firefox seems pretty dodgy. it marks lines that do not get executed.
I found this by implementing the minimal example an running it from the code. The alerts both get a mark as if they are executed, however at the one that is not executed it does not run. So i't an error in the debugger.
Then i searched the code for the animation and found it to be an error combined with a css3 animation tag.
Problem solved
|
[
"stackoverflow",
"0011706387.txt"
] | Q:
MouseOver trigger doesn`t work after programmatically set Foreground
I'm new to WPF, but searching internet for some days I couldn't figure out my problem.
After I programmatically change Foreground property, IsMouseOver trigger doesn't work. Please be tolerant and thank in advance :)
<Style x:Key="ZizaMenuItem" TargetType="{x:Type Button}">
<Setter Property="SnapsToDevicePixels" Value="True" />
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="Margin" Value="5,0,5,0"/>
<Setter Property="Height" Value="30"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Label FontSize="14" Content="{TemplateBinding Content}" Name="ZizaMenuItemText" />
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="ZizaMenuItemText" Property="Foreground" Value="#ff0000"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<StackPanel Height="30" Name="ZizaMenu" Orientation="Horizontal" Margin="0,12,0,0" VerticalAlignment="Top">
<Label Content="ZIZA" FontSize="11" FontWeight="Bold" Foreground="Black" Height="25" Margin="20,0,10,0" />
<Button Name="ZizaMenuInteresting" Click="ZizaMenuItemClicked" Content="ИНТЕРЕСНОЕ" Style="{StaticResource ZizaMenuItem}" />
<Button Name="ZizaMenuBest" Click="ZizaMenuItemClicked" Content="ЛУЧШЕЕ" Style="{StaticResource ZizaMenuItem}" />
<Button Name="ZizaMenuAuto" Click="ZizaMenuItemClicked" Content="АВТО" Style="{StaticResource ZizaMenuItem}" />
</StackPanel>
private void ZizaMenuItemClicked(object sender, RoutedEventArgs e)
{
// get label object from template
Button zizaMenuItem = (Button)sender;
Label zizaMenuItemText = (Label)zizaMenuItem.Template.FindName("ZizaMenuItemText", zizaMenuItem);
// set Foreground color for all buttons in menu
foreach (var item in ZizaMenu.Children)
if (item is Button)
((Label)(item as Button).Template.FindName("ZizaMenuItemText", (item as Button))).Foreground = Brushes.Black;
// set desired color to clicked button label
zizaMenuItemText.Foreground = new SolidColorBrush(Color.FromRgb(102, 206, 245));
}
A:
That is horrible code, do not mess with controls inside control templates, ever. Template.FindName is something only the control that is being templated should call internally to get its parts, and only those, everything else should be considered uncertain.
If you need to change a property template bind it, and then bind or set said property on the instance. In terms of precedence you need to make sure not to create a local value which overrides the triggers (that is what you did). You can use a Style and Setter on the Label to bind the default Foreground.
<Label.Style>
<Style TargetType="Label">
<Setter Property="Foreground" Value="{TemplateBinding Foreground}"/>
</Style>
</Label.Style>
Now you just need to set the Foreground of the Button itself, the Trigger should still internally have precedence over that Setter.
|
[
"stackoverflow",
"0014316417.txt"
] | Q:
Opencart 1.5.4 addToCart() first time page shows function does not work
I am currently working on a project in Open Cart 1.5.4. I slighty moved the cart into another div without any problems. The thing is on new computers and first time they enter the site it´s not possible for the customer to add a product to cart. If they go into another page and then back it works just fine. The javascript file is loaded properly without any problems.
Hope this explanation explains the problem or bug pretty good.
Thanks in advance.
JAVASCRIPT
function addToCart(product_id, quantity) {
quantity = typeof(quantity) != 'undefined' ? quantity : 1;
$.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
data: 'product_id=' + product_id + '&quantity=' + quantity,
dataType: 'json',
success: function(json) {
$('.success, .warning, .attention, .information, .error').remove();
if (json['redirect']) {
location = json['redirect'];
}
if (json['success']) {
//$('#notification').html('<div class="success" style="display: none;">' + json['success'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');
$('.success').fadeIn('slow');
try {
$('#cart-total').html(json['total']);
}
catch(err) {
console.log(err.message());
}
$('html, body').animate({ scrollTop: 0 }, 'slow');
$(".heading").animate({backgroundColor: "#FFFFFF"}, 'slow');
$(".cart_arrow").attr("style", "display: block;");
$(".heading").animate({backgroundColor: "#585858"}, 'slow');
}
}
});
}
A:
Found the cause of the problem. When Open Cart is installed and domain is about to be choosen, you can choose www or non-www. Depends on the one you choose the other wont work.
So the solution to the problem htaccess redirect for this one from non-www to www adress
RewriteCond %{HTTP_HOST} ^domain.com$ [NC]
RewriteRule ^(.*) http://www.domain.com/$1 [R=301,L]
RewriteBase /
RewriteRule ^sitemap.xml$ index.php?route=feed/google_sitemap [L]
RewriteRule ^googlebase.xml$ index.php?route=feed/google_base [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !.*\.(ico|gif|jpg|jpeg|png|js|css)
RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA]
The redirect has to be over RewriteBase /
Thanks and I hope this helps in the future for anyone nedded this kind of support
|
[
"stackoverflow",
"0020393781.txt"
] | Q:
Quantifiers in a regular expression used with awk behave unexpected
I want to process this list: (Of course this is just an excerpt.)
1 S3 -> PC-8-Set
2 S3 -> PC-850-Set
3 S3 -> ANSI-Set
4 S3 -> 7-Bit-NRC
5 PC-8-Set -> S3
6 PC-850-Set -> S3
7 ANSI-Set -> S3
This is what I did:
awk -F '[[:blank:]]+' '{printf ("%s ", $2)}' list
This is what I got:
1 2 3 4 5 6 7
Now I thought the quantifier + is equivalent to {1,}, but when I changed the line to
awk -F '[[:blank:]]{1,}' '{printf ("%s ", $2)}' list
I got just blanks and the whole line was read to $1.
Can someone explain this behaviour please? I'm thankful for every answer!
A:
Try
awk --re-interval -F '[[:blank:]]{1,}' '{printf ("%s ", $2)}' list
--re-interval
Allow interval expressions (see Regexp Operators) in regexps. This is now gawk's default behavior. Nevertheless, this
option remains both for backward compatibility, and for use in
combination with the --traditional option.
A:
You are using a Gawk which is from before this November 2010 commit, found by git bisect.
http://git.savannah.gnu.org/cgit/gawk.git/commit/?id=40b3741f63c19e38077d57f4ce4737916ec5073e
The change indeed hinges on the defaulting behavior with respect to intervals, which become on by default (as POSIX requires them to be).
It looks like the --re-interval option becomes relegated only for use with --traditional; i.e. that if --traditional is enabled, then support for {m,n} goes away, but can be selectively brought back with --re-interval.
In your version, {m,n} is unrecognized by default, with or without --traditional. This is true up to this commit:
commit 00ef0423acd97cb964a2bae54c93a03a8ab50e5e
Author: Arnold D. Robbins <arnold@******>
Date: Fri Jul 16 14:55:10 2010 +0300
Move to 3.1.8.
and you're behind that still, on 3.1.5.
|
[
"askubuntu",
"0000544646.txt"
] | Q:
How to install Google Drive on Ubuntu 14.04?
I am using Ubuntu 14.04, I tried to search for Google Drive on Ubuntu Software Center, but couldnot find it. Searched for answers in Askubuntu but all I found was ways to install Google Drive on Ubuntu 12.04 which didn't worked for me.
Can anyone please give me some ideas?
Update: Don't know why they marked it as duplicate entry, as the link mentioned in question gives answer for Ubuntu 12.04, which as I see is two different things.
A:
Updated 9/15/2015 Due to Google's changing API you might be having problem during installation of Grive. So the site I was referencing have also changed their tutorial for installing Grive2.
You can find new tutorial on this new link: How to install Google Drive Grive2 on Ubuntu
To install Grive2 in Ubuntu, Linux Mint and derivatives by using the main WebUpd8 PPA, use the following commands:
sudo add-apt-repository ppa:nilarimogard/webupd8
sudo apt-get update
sudo apt-get install grive
Yes, It is true that there isn't a native google drive client for linux yet, so you couldn't get app on Software Center. And ways to install in 12.04 and 14.04 are somewhat different.
Old outdated reference Tutorial How to install Google Drive on Ubuntu 14.04
A:
There is no official client of Google Drive for Linux based OSes, you can use grive/grive-tools though.
sudo add-apt-repository ppa:thefanclub/grive-tools
sudo apt-get update
sudo apt-get install grive-tools
Then search for grive in the dash and follow the installers instructions.
|
[
"stackoverflow",
"0010885418.txt"
] | Q:
Finding duplicate entries SQL
I have a table of called Member(Unique ID is MemberID) that has numerous member duplicates with only the First and Last Names being different, but the Business Name, Address, City, State and Zip Codes are all the same. Records were imported with duplicates.
How can I run a script to find duplicate members where the BusinessName, Addr1, City, State, and ZIP are all the same.
I want to list them all on a page, so I can choose which ones to eliminate.
Any ideas how I can create a script for this?
Many thanks in advance,
Paul
A:
select * from Member as m
where exists(select MemberID
from Member as m2
where
(m.BusinessName = m2.BusinessName or (m.BusinessName is null and m2.BusinessName is null)) and
(m.Addr1 = m2.Addr1 or (m.Addr1 is null and m2.Addr1 is null)) and
(m.City = m2.City or (m.City is null and m2.City is null)) and
(m.State = m2.State or (m.State is null and m2.State is null)) and
(m.ZIP = m2.ZIP or (m.ZIP is null and m2.ZIP is null)) and
m.memberID <> m2.MemberID)
With the above query the where is checking to see if a duplicate entry exists. The subquery returns a result only if there is a copy where the MemberID does not match. This means if there is a unique row then there will be no results whereas if there is a row with one or more copies then it will be returned.
|
[
"gis.stackexchange",
"0000186706.txt"
] | Q:
Trouble getting leaflet-label plugin to work on geojson file
I cannot figure out how to get labels on my featureLayers to show in my LeafLet map for a mapbox featureLayer using the leaflet-label plugin. I thought all i needed to do was add
.bindLabel('Look revealing label!')
Please help.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>A Site Survery of Antikythera Greece</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.mapbox.com/mapbox.js/v2.3.0/mapbox.js'></script>
<link href='https://api.mapbox.com/mapbox.js/v2.3.0/mapbox.css' rel='stylesheet' />
<!--labeling scripts-->
<script src='https://api.mapbox.com/mapbox.js/plugins/leaflet-label/v0.2.1/leaflet.label.js'></script>
<link href='https://api.mapbox.com/mapbox.js/plugins/leaflet-label/v0.2.1/leaflet.label.css' rel='stylesheet' />
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>
<div id='map'></div>
<script>
//load the map
L.mapbox.accessToken = 'pk.eyJ1IjoibWFwcGluZ3RoaW5ncyIsImEiOiJkSy1MRlNVIn0.jt2ol5HlgFaCdx4Ajn5WjA';
var map = L.mapbox.map('map')
.setView([35.87, 23.3], 14);
// Load all the layers in
L.marker([35.87, 23.3]).bindLabel('Look revealing label!').addTo(map);
var geologyLayer = L.mapbox.featureLayer(geologyLayer, {
style: {
"color": "Black",
"weight": 3,
"opacity": .5,
}
})
.loadURL('http://jwitcoski.github.io/Antikythera/data/geology.geojson')
.bindLabel('Look revealing label!')
.addTo(map);
//map legend
L.control.layers({
'Mapbox Satellite': L.mapbox.tileLayer('mapbox.satellite').addTo(map),
'Mapbox Light': L.mapbox.tileLayer('mapbox.light'),
'Thunderforest Outdoors' : L.tileLayer('http://{s}.tile.thunderforest.com/outdoors/{z}/{x}/{y}.png', {
attribution: '© <a href="http://www.thunderforest.com/">Thunderforest</a>, © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
}),
'MtbMap' : L.tileLayer('http://tile.mtbmap.cz/mtbmap_tiles/{z}/{x}/{y}.png', {
attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> & USGS'
}),
'Esri_WorldImagery' : L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
attribution: 'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'
}),
},
{
"Geology": geologyLayer,
}).addTo(map);
;
</script>
</body>
</html>
A:
Seems like bindLabel doesn't work as expected with asynchronously loaded data with loadURL(). If you pass geojson directly, it works:
// jQuery usage just for the sake of brevity
jQuery.get('http://jwitcoski.github.io/Antikythera/data/geology.geojson').success(function(data) {
var geologyLayer = L.mapbox.featureLayer(data, {
style: {
"color": "Black",
"weight": 3,
"opacity": .5,
}
})
.bindLabel('look label')
.addTo(map);
})
Hope this helps!
|
[
"ukrainian.stackexchange",
"0000000568.txt"
] | Q:
Який знак лапок є нормованим в українській мові?
В школі нас вчили ставити лапки отак: „приклад“.
Приблизно так само виправляв лапки редактор Microsoft Word часів мого навчання в школі/інституті, замінюючи (AutoCorrect) "прямі" лапки в залежності від обраної мови тексту так:
„українська“;
«російська»;
“англійська”.
Власне, саме завдяки Microsoft Word я зрозумів, що «оце» — теж є лапками (до цього я їх бачив виключно в таблицях змісту книжок російських віршів — і думав, що це якийсь специфічний знак для позначення вірша без заголовка). Хоча, навіть зрозумівши, що воно — теж лапки, я довго не міг до них звикнути, вручну виправляючи їх навіть у російських текстах.
Тим не менш, скоро я побачив:
спочатку — що нові редактори виправляють "прямі" лапки на «отакі» навіть в українських текстах;
потім, коли трішки розібрався — використання «отаких» лапок навіть у сучасному правописі: § 124. ЛАПКИ (« ») — з використанням „отаких“ лише для другого рівня вкладеності:
«Ти дивився кінофільм „Данило — князь галицький“?» — спитав він товариша.
Коротше, запитання:
Чи дійсно в 90х–2000х були зміни в нормах, що замінили „такий перший рівень (і не знаю, як раніше позначався другий, може, «отак», а може, й ніяк)“ на «такий перший рівень і „такий другий рівень“»? чи це лише розбіжність між традиціями рукописної та типографської графіки та некоректна конфігурація текстових редакторів на додачу? Шукаючи старі версії правопису на захист „звичних“ для мене лапок, я знайшов лише проект-99, де лапки взагалі “англійські” (і ще невідомо, чи не результат це неточної оцифровки).
Чи є якісь документи, що нормують (чи хоча б рекомендують), які саме лапки слід використовувати в українських друкованих текстах? Бо в правописі, власне, ніде не написано, що саме «такі» слід використовувати на першому рівні, а „такі“ — лише для другого. Хоча графіку самого правопису можна сприймати як зразок, але це не є конкретним правилом чи рекомендацією (і невідомо, наскільки обов'язковим для наслідування є той зразок, може, можна і так, і так).
A:
Щодо українських документів та рекомендацій, є посібник Партико 3. В.
Загальне редагування: нормативні основи. (Навчальний посібник. — Л.: ВФ Афіша, 2006., с. 277)
Ось, що в ньому сказано:
Цитати можна виділяти трьома способами:
а) за допомогою лапок; при цьому, коли всередині цитати є інші лапки, їх подають у такій послідовності: «хххх "ххххх " хххх»;
б) за допомогою шрифтових виділень; в) за допомогою поліграфічних
засобів, наприклад, лівосторонніх втягувань, міжабзацних відступів
зверху та знизу цитати тощо.
Питання зовнішнього вигляду лапок взагалі не тема правопису, за традицією це царина технічних редакторів, в СРСР традиційно було два типу лапок: «типографські» та „рукописні“. Звичайно, що пересічні громадяни в докомп'ютерну епоху не мали відношення до видавничої справи, тому ніхто ніколи не робив акцентів на зовнішньому вигляді лапок, у ГОСТах (наприклад ГОСТ 7.1—84), що нормують видавничу діяльність детально описувалось, де лапки вживати, але сам вигляд лапок не описувався.
З появою комп'ютерів друкувати літературу стало дуже легко, це почали робити люди без фахової підготовки, часто покладаючись на систему виправлення MS Ворду, але вона не була налаштована згідно наших нормативів, тому ми сьогодні спостерігаємо деякий безлад у цьому питанні.
|
[
"stackoverflow",
"0005263853.txt"
] | Q:
Return no view from action in ajax requests struts 2
I have a drop down list for locale selection, when user changes it then i send an ajax request to an action where i set a session perimeter
Now the problem is that what should i return from the execute() method of the action
A:
You can return an HTTP 200 OK, which should be an empty, successful response.
<result name="empty" type="httpheader">
<param name="status">200</param>
</result>
I would make a global result so that you can use it any action.
|
[
"stackoverflow",
"0030031090.txt"
] | Q:
Spring websockets and group messages
I would like to implement a chat using Spring websockets. What will be the best way to implement groups?
Register a new UserDestinationMessageHandler for URLs like /group/{groupname}/queue/* and create a new UserDestinationResolver. Are there any examples for this?
Make the controller implement ApplicationListener<SessionConnectedEvent>. But how can I get the session attributes from the event?
In both options I was taking into account that I will register the group to which the user belongs into session attributes.
A:
I ended up creating a destination like "/topic/group/{name}/message" managed by message broker and have user subscribed to it.
To send a message you can either send it to the same destination or you can send it to a destination like "/app/message" and have it forward it from there. The latter option has the advantage that you can filter the message.
|
[
"stackoverflow",
"0045688518.txt"
] | Q:
Android No resource matches android:windowIsFloating
I am trying to make my activity as popup / floating activity after watching this video
https://www.youtube.com/watch?v=fn5OlqQuOCk
But I want to make window background Semi Translucent.
So I added windowIsFloating -> true
<style name="AppTheme.NamTheme">
<item name="android:windowIsFloating">true</item>
<item name="android:windowCloseOnTouchOutside">true</item>
</style>
But getting following error
Error:(2374, 21) No resource found that matches the given name: attr 'android:windowIsFloating'.
A:
Add a parent android theme to your custom theme. For example,
<style name="AppTheme.NamTheme" parent="android:Theme.Light.NoTitleBar">
<item name="android:windowIsFloating">true</item>
<item name="android:windowCloseOnTouchOutside">true</item>
</style>
|
[
"stackoverflow",
"0033624751.txt"
] | Q:
Grouping routes with Flow Router in Meteor
In Flow Router, I have some routes
/projects/project-name
/projects/project-name/tasks
/projects/project-name/tasks/deleted-tasks
/projects/project-name/tasks/completed-tasks
/projects/project-name/tasks/labels/school
/projects/project-name/tasks/labels/football
/projects/project-name/tasks/labels/training
/projects/project-name/tasks/labels/personal
[...]
So almost all of my routes should share most of the same characteristics.
Are there any tricks to group my routes, so I do now have to check if the project exists in every single route or if can I say that some routes build upon other routes, so I do not have to write the long paths for all the routes?
I have found Flow Router, but it doesn't seem that's right tool to accomplish what I need.
A:
Flow router definitely has the ability to group your routes. You can group them as follows -
var projectRoutes = FlowRouter.group({
prefix: '/projects/project-name',
name: 'projects',
});
To handle routers within this group, you can add
// route for /projects/project-name
projectRoutes.route('/', {
action: function() {
BlazeLayout.render(...);
}
});
// route for /projects/project-name/tasks
projectRoutes.route('/tasks', {
action: function() {
BlazeLayout.render(...);
}
});
This is just an example for grouping your routes.
You can read more here.
|
[
"stackoverflow",
"0020760002.txt"
] | Q:
Identical forms interfering
I have a problem with two forms, that is being submitted by the same button.
When the first form is submitted it's being hidden and the other form is showed.
Now when i click the button on the second form, the variable value still contains 'give' from the selectbox in the first form.
What am i doing wrong?
Jquery code:
$('.submit_button').click(function() {
var value = $(".input_action").val();
alert(value);
switch(value) {
case 'give':
$('#content_wrapper').hide();
$('#send_wrapper').show();
break;
default:
alert("default");
break;
}
});
Html code:
Form 1:
<div id='content_wrapper'>
<form class='form_content' method='post' action=''>
<select name='action' class='input_action'>
<option selected='give'>Give</option>
</select>
<input class='submit_button' type='button' name='button' value='submit'>
</form>
Form 2:
<div id='send_wrapper'>
<form name='form_content' class='form_content' method='post' action=''>
<input name='input_action' class='input_action' value='' type='hidden'>
<input class='submit_button' type='button' name='button' value='submit'>
</form>
</div>
A:
$(".input_action").val() will always give you the value of the first element that matches in the document.
If you want to get the one from the current form, then you need to find the current form and then find the matching element within that.
The context of the event handler will be the element clicked, so you can get that with this.
You can get the form using the form property.
You can then use the jQuery find method to get the element you want.
var value = $( this.form ).find('.input_action').val();
|
[
"stackoverflow",
"0050771084.txt"
] | Q:
How to get rid of zeros in a calculation so an error does not occur Python
Hi I am working on a calculator program and am trying to solve an issue where when a zero is in front of the calculation.
For example, 03+03 an error occurs as I am using eval. the calculation must be kept in string form as eval uses the string form and gives me the sum. I need to find a way to get rid of the zeros before the calculation happens through eval.
A:
Here is a completely working code. I assume you want to remove leftmost trailing zero of a number.
import re
calculation = '03030+010340'
res = re.sub('^0*|(?<=[-\+\*/])0*', '', calculation)
print(res)
# 3030+10340
How?
re.sub substitutes a pattern with whatever we want.
Inside re.sub:
First parameter is the pattern to be substituted.
^0* matches starting 0 zero or more times.
(?<=[-\+\*/])0* matches 0s that follow -, +, *, / operators.
Second parameter is to specify what to replace with.
Third parameter is the input string.
Also, I suggest not to use eval. Read about dangers of eval here. Use ast.literal_eval to get result of operation like so:
ast.literal_eval(res) # Don't forget to import ast
|
[
"stackoverflow",
"0032565510.txt"
] | Q:
Does Emmet work with Sublime Text in Vintage Mode?
None of these commands produce a response in Sublime Text 2 on Windows. Emmet is installed. Using vintage mode. Question: how to use Emmet in Vintage Mode on Sublime Text 2?
html:5
div>ul>li
div+p+bq
A:
You can use Ctrl + E to manually expand an abbreviation.
You can also try adding the following to your User keybindings in order to make Tab work normally:
{ "keys": ["tab"], "args": {"action": "expand_abbreviation"}, "command": "run_emmet_action", "context": [{"key": "emmet_action_enabled.expand_abbreviation"}]}
|
[
"math.stackexchange",
"0001309360.txt"
] | Q:
Unique homomorphism between quotients
I am working on an exercise I found rather entertaining, albeit I found myself struggling at how to attack this problem as I don't know from which angle to approch it and tips or tricks would be appricaited.
Let $\varphi:R_1\to R_2$ be a ring homomorphism such that $\varphi(I_1)\subseteq I_2$ where $I_1$ is an ideal of $R_1$ and $I_2$ of $R_2$. Show that there is a unique homomorphism $\phi:R_1/I_1\to R_2/I_2$ such that the following diagram commutes
$\require{AMScd}
\begin{equation}\begin{CD}
R_1 @>\varphi>> R_2\\
@VV{\eta_1}V @VV{\eta_2}V\\
R_1/I_1 @>\phi>> R_2/I_2
\end{CD}\end{equation}$
Where $\eta$ are the natural homomorphisms between rings and their quotient rings.
I am unfamiliar somewhat with tackling how to show that morphisms are unique which is my main issue, I don't know how to demonstrate that.
A:
This theorem relies on a very important fact about homomorphisms.
If $\alpha\colon R\to S$ is a ring homomorphism, $I$ is an ideal of $R$ such that $I\subseteq \ker\alpha$ and $\eta\colon R\to R/I$ is the canonical projection, there exists a unique ring homomorphism $\beta\colon R/I\to S$ such that $\alpha=\beta\circ\eta$.
(Uniqueness) Suppose $\beta$ exists. Then, for $r+I\in R/I$, we have
$$
\beta(r+I)=\beta(\eta(r))=\beta\circ\eta(r)=\alpha(r)
$$
so the action of $\beta$ is determined by $\alpha$ and this settles uniqueness.
(Existence) We want to show that, if $r+I=r'+I$, then $\alpha(r)=\alpha(r')$, so that setting $\beta(r+I)=\alpha(r)$ does not depend on the particular representative of the coset. This is true because $r+I=r'+I$ is equivalent to $r-r'\in I$, which implies $r-r'\in\ker\alpha$ and therefore $\alpha(r-r')=0$: thus $\alpha(r)=\alpha(r')$ as desired.
Therefore the position $\beta(r+I)=\alpha(r)$ defines a map $R/I\to S$; checking it's a ring homomorphism is easy.
Now that we have the general theorem, we can apply it to our present situation. Let $S=R/I_2$ and $\alpha=\eta_2\circ\varphi$.
If we prove that $I_1\subseteq\ker\alpha$, we can apply the theorem and get a unique ring homomorphism $\psi\colon R_1/I_1\to R_2/I_2$ such that
$$
\psi\circ\eta_1=\alpha=\eta_2\circ\varphi
$$
(I use $\psi$ instead of $\beta$ as in the theorem to comply with your notation; $\eta_1\colon R_1\to R_1/I_1$ and $\eta_2\colon R_2\to R/I_2$ are the canonical projection).
All we need is to show that $I_1\subseteq \ker\alpha=\ker(\eta_2\circ\varphi)$, that is, for $x\in I_1$, $\eta_2\circ\varphi(x)=0+I_2$. But, by assumption $\varphi(x)\in I_2$, so $\varphi(x)\in\ker\eta_2$ and therefore
$$
\eta_2\circ\varphi(x)=\eta_2(\varphi(x))=0+I_2
$$
as desired.
|
[
"stackoverflow",
"0040999618.txt"
] | Q:
Zabbix trigger expression external check
I created a external check that returns a value formatted like :
File System Storage Percent:12.34
Is that possible to create a trigger that check if the value > 50% ?
{my_host:my_external_check.py.str(File System Storage Percent:50.00)}=1
I saw that regexp exists but it does not return the value found.
A:
Change your script to return the value without the extra text - like 12.34. Then you can use the usual Zabbix trigger functions last(), min(), avg(), max() and others.
|
[
"stackoverflow",
"0042357872.txt"
] | Q:
Python optimize data structure
I failed in an interview problem solving. They presented a json object:
{
"UserName": "Tom Las",
"title": "Director"
},
{
"UserName": "Mike Sea",
"title": "senior manager"
},
{
"UserName": "Jojo Lee",
"title": "manager",
"direct Report": "Mike Sea"
},
{
"UserName": "Luke Shi",
"title": "manager",
"direct Report": "Mike Sea"
},
{
"UserName": "Bob Aeo",
"title": "engineer",
"direct Report": "Luke Shi"
},
{
"UserName": "Zobu hu",
"title": "engineer",
"direct Report": "Tom Las"
}
Require a formated output of organization structure like:
Mike Sea - senior manager
Jojo Lee
Luke Shi
Bob Aeo
Tom Las - Director
Zobu hu
Here is my solution. I use two dictionary to track leader and team member information and use " "*n to indent team member in sub team. I feel below code is clumsy and not flexible to show more levels of sub team, for example if "Bob Aeo" also has team member under him. Should i consider different data structure instead of dictionary in this case? Thanks!
#!/usr/bin/env python
from collections import defaultdict
MemberInfo = [
{
"UserName": "Tom Las",
"title": "Director"
},
{
"UserName": "Mike Sea",
"title": "senior manager"
},
{
"UserName": "Jojo Lee",
"title": "manager",
"direct Report": "Mike Sea"
},
{
"UserName": "Luke Shi",
"title": "manager",
"direct Report": "Mike Sea"
},
{
"UserName": "Bob Aeo",
"title": "engineer",
"direct Report": "Luke Shi"
},
{
"UserName": "Zobu hu",
"title": "engineer",
"direct Report": "Tom Las"
}
]
Leader={}
Team=defaultdict(list)
for line in MemberInfo:
if "direct Report" not in line and line['UserName'] not in Leader:
Leader[line['UserName']] = line['title']
elif line['direct Report']:
Team[line['direct Report']].append(line['UserName'])
for key,value in Leader.iteritems():
print("{} - {}".format(key,value))
for Member in Team[key]:
if Member in Team:
print(" {}".format(Member))
print(" "*4 + ' '.join(Team[Member]))
else:
print(" {}".format(Member))
A:
Build a tree... I changed "direct reports" to "manager" since I think the point is to name the person's manager in the MemberInfo object. The reverse link of a manager is a list of direct reports, so that's what I setup in the example below. I started by indexing the list, addied a "direct reports" list and then filled out that list. Then it was just a question of a recursive routine that would print and entry followed by any direct reports. The code makes no assumptions about how bloated the organization is, but does assume that there are no loops in the list... I once reported to myself at a job I had and that played havoc with all sorts of software. Interestingly, I was working on code that managed Active Directory Manager and directReports fields at the time.
MemberInfo = [
{
"UserName": "Tom Las",
"title": "Director"
},
{
"UserName": "Mike Sea",
"title": "senior manager"
},
{
"UserName": "Jojo Lee",
"title": "manager",
"Manager": "Mike Sea"
},
{
"UserName": "Luke Shi",
"title": "manager",
"Manager": "Mike Sea"
},
{
"UserName": "Bob Aeo",
"title": "engineer",
"Manager": "Luke Shi"
},
{
"UserName": "Zobu hu",
"title": "engineer",
"Manager": "Tom Las"
}
]
def crawl_ranks(name, indent=''):
"""Prints member and direct report names recursively"""
member = member_index[name]
print('{}{}'.format(indent, member['UserName']))
for name in sorted(member.get('direct reports', [])):
crawl_ranks(name, indent=indent + ' ')
# index by name for easy lookup
member_index = {member['UserName']:member for member in MemberInfo}
# add direct reports list to member info
for member in MemberInfo:
member['direct reports'] = []
# add dummy index entry for bossless persons
member_index[None] = {'direct reports':[]}
# add member name to boss's direct reports list
for member in MemberInfo:
member_index[member.get('Manager')]['direct reports'].append(member['UserName'])
# print, starting with top-level managers
for name in sorted(member_index[None]['direct reports']):
crawl_ranks(name)
|
[
"stackoverflow",
"0021219447.txt"
] | Q:
Calculating percentile of dataset column
A quick one for you, dearest R gurus:
I'm doing an assignment and I've been asked, in this exercise, to get basic statistics out of the infert dataset (it's in-built), and specifically one of its columns, infert$age.
For anyone not familiar with the dataset:
> table_ages # Which is just subset(infert, select=c("age"));
age
1 26
2 42
3 39
4 34
5 35
6 36
7 23
8 32
9 21
10 28
11 29
...
246 35
247 29
248 23
I've had to find median values of the column, variance, skewness, standard deviation which were all okay, until I was asked to find the column "percentiles".
I haven't been able to find anything so far, and maybe I've translated it incorrectly from greek, the language of the assignment. It was "ποσοστημόρια", Google Translate pointed the English term to be "percentiles".
Any tutorials or ideas on finding those "percentiles" of infert$age?
A:
If you order a vector x, and find the values that is half way through the vector, you just found a median, or 50th percentile. Same logic applies for any percentage. Here are two examples.
x <- rnorm(100)
quantile(x, probs = c(0, 0.25, 0.5, 0.75, 1)) # quartile
quantile(x, probs = seq(0, 1, by= 0.1)) # decile
A:
The quantile() function will do much of what you probably want, but since the question was ambiguous, I will provide an alternate answer that does something slightly different from quantile().
ecdf(infert$age)(infert$age)
will generate a vector of the same length as infert$age giving the proportion of infert$age that is below each observation. You can read the ecdf documentation, but the basic idea is that ecdf() will give you a function that returns the empirical cumulative distribution. Thus ecdf(X)(Y) is the value of the cumulative distribution of X at the points in Y. If you wanted to know just the probability of being below 30 (thus what percentile 30 is in the sample), you could say
ecdf(infert$age)(30)
The main difference between this approach and using the quantile() function is that quantile() requires that you put in the probabilities to get out the levels, and this requires that you put in the levels to get out the probabilities.
A:
Using {dplyr}:
library(dplyr)
# percentiles
infert %>%
mutate(PCT = ntile(age, 100))
# quartiles
infert %>%
mutate(PCT = ntile(age, 4))
# deciles
infert %>%
mutate(PCT = ntile(age, 10))
|
[
"stackoverflow",
"0006731063.txt"
] | Q:
Poor mans crontab Zend Framework implementation
Are there any readily available "Poor man's crontab" implementations (php script called every minute or so) that can be easily integrated into Zend Framework? Preferably utilizing a view script dashboard, for jobs management, populated by controller.
*Edit:
I found a Zend_Scheduler, which appear to do somewhat what I'm after. What's missing is a mechanism to stay self sustained (not rely on external crontabbed wget or similar), but execute on actual page loads.
Is there a suitable place in Zend framework I can piggyback $scheduler->run() from? Bootstrap::__destruct() or similar? In order to complete rendering the view, and push to client before any scheduled tasks take place? (So the client won't be affected by any long running taks that might be scheduled.
(Schedule naturally won't be accurate when there are no visitors, but my assumption here is that any scheduled task wouldn't have to be performed if no-one is around to see the result)
*Edit2:
Zend_Scheduler is so old, it's incompatible with newer Zend Framework versions, and thus not working as intended. Are there any other self sustained libraries that can be used for this?
A:
I guess you mean Drupal's poormanscron module. The Zend Framework does not ship with anything like that and actually neither does Drupal but they have modules which are created and supported by the Drupal community.
Zend Framework unfortunately is missing something like community driven modules. You have to find your modules somewhere in the wild. I doubt it you will find something like poormanscron but maybe you can take that module and with a few minor changes works in ZF.
|
[
"stackoverflow",
"0001651450.txt"
] | Q:
Why is my if statement not firing?
I have the following Objective-c Function
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];
NSString *key = [keys objectAtIndex:section];
NSArray *nameSection = [mysearchdata objectForKey:key];
static NSString *SectionsTableID = @"SectionsTableID";
static NSString *TobyCellID = @"TobyCellID";
NSString *aName = [nameSection objectAtIndex:row];
if (aName == @"Toby")
{
TobyCell *cell = [tableView dequeueReusableCellWithIdentifier:TobyCellID];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"TobyCell" owner:self options:nil];
for (id oneObject in nib)
if ([oneObject isKindOfClass:[TobyCell class]])
cell = (TobyCell *)oneObject;
}
cell.lblName.text = [nameSection objectAtIndex:row];
return cell;
}
else
{
//standard cell loading code
}
}
All I want is for the if Statement to fire when the Row is equal to My Name - very exciting.
if (aName == @"Toby")
I have put in an alert and the Value is being set and its being set to Toby but the If statement is not executing just the else part. It is obviously something simple that I'm missing.
I am learning Objective-C
A:
This if statement:
if (aName == @"Toby")
compares pointers, not strings. You want:
if ([aName isEqualToString:@"Toby"])
This isn't really different from plain C; you can't use == to compare strings there either.
|
[
"math.stackexchange",
"0002450037.txt"
] | Q:
How would you prove that this sum involving prime gaps has a limit?
Let $p_k$ = the $k$th prime.
$$
\varphi(n) = \sum_{k=1}^{n-1} e^{i 2 \pi \frac{p_{k+1} - p_k}{p_n}}
$$
seems to approach a constant point in $\Bbb{C}$ as $n \to \infty$. How can I prove it though?
A:
I doubt the convergence.
By Bertrand's postulate, we will (except for small $n$) always have $p_{k+1}-p_k<\frac12 p_n$, which already gives all summands positive imaginary part.
By known generalization of Bertrand, for each $\epsilon>0$, we have $p_{n+1}<(1+\epsilon)p_n$ for almost all $n$. Thus for $n$ large enough, all $\frac{p_{k+1}-p_k}{p_n}$ are small (between $0$ and $\frac16$, say), either beacuse $p_{k+1}$ is not much larger than $p_k$, or because $p_n$ is much larger than $p_{k+1}$. Then we have $n-1$ summands with each having real part $>\frac12$, say.
More precisely, the above shows that $$\Re\phi(n)\sim n-1. $$
|
[
"movies.stackexchange",
"0000004531.txt"
] | Q:
Is Cobb's reaction honest or sarcastic/angry
In Inception there is the following dialogue between Cobb and Ariadne (forgive me for not being word-accurate):
Ariadne: Why can't you return home?
Cobb: Because everybody thinks I killed her (Mal).
...
Cobb: Thank you.
Ariadne: For what?
Cobb: Not asking if I did it.
I am not completely sure how to interpret Cobb's reaction here. It may be obvious, but while he seems to really thank her for not asking (maybe believing she doesn't care or believes he didn't do it), to me he seems kind of angry or annoyed when saying this. But it may be just me misinterpreting his behaviour here (or the German synchronizer distorting it).
So how is his reaction to be interpreted (while this sounds like an open discussion question, I guess there was a clear intent by the writer how his reaction should come across):
Did he indeed thank her along the lines of "Thank you for not asking, it's refreshing to see somebody not caring about it and just concentrating on the work."?
Or was it more like "Thank you for not asking and just trusting me not to have done it."?
Or was it really a sarcastic thank you and an angry/annoyed reaction, like "Thank you for not asking! You're thinking I did it, don't you?"?
I tend to the more obvious first version, but he just seemed kind of angry to me, which would favor the third version.
A:
He does sound a little angry or bitter when he says that line. You could put that down to him suspecting that she is thinking that question, which would indeed make it slightly sarcastic.
However, given his circumstances: a man wanted for murder, a man who operates with criminals on a daily basis who are unlikely to keep their thoughts to themselves - it is likely that this is not the first time he's had this conversation, and that other people have been less generous in their presumption of his innocence, or even just less likely to keep silent when told.
My impression from that exchange was that he had had that conversation before, and was bitterly pleased that she had not immediately asked him the question. Bitterly because he probably knows it is in her mind, but that she has not blurted it out. He says the 'thank you' fairly soon, so also managing to head-off the chance that she is about to ask. He manages to both imply that he believes he is innocent, without the embarrassment of having to deal with the question directly.
|
[
"stackoverflow",
"0012717901.txt"
] | Q:
Zend Framework Render Barcodes Into Multiple PDF Pages with other content
I am trying to create pages of incrementing labels that include barcodes. I can get a barcode into a PDF, and I can get it superimposed on other content in the PDF (see below). But I can't figure out how to assign a barcode to a certain page of a pdf using something maybe like
Zend_Barcode::factory('code39', 'pdf',
$barcodeOptions, $rendererOptions)->setResource($page)->draw();
or
$page = Zend_Barcode::factory('code39', 'pdf', $barcodeOptions,
$rendererOptions)->setResource($pdf)->draw();
Both of the above snippets cause errors when set in the context of my larger code. Further down is code that renders with no errors, but doesn't give me what I need.
This question is identical to Zend Framework Render Barcodes Into PDF Pages, which never reached a working answer from what I can see.
First, to get this to work, I copied the Zend version 1.11 Barcode library into my Zend version 1.7.2 library folder. I also copied a free non-monospaced font into my application/library as the code shows.
I can create a multi-page PDF of labels. And I can put a barcode in a PDF. What I can't do is put barcodes on multiple pages. I'll show what I am doing, and hopefully you can tell me what I am doing wrong or need to do.
First I have this little snippet that puts a barcode in a PDF:
// A font path is mandatory for Barcode Pdf output.
// This application defines ROOT_DIR in index.php. Others may define APPLICATION_PATH.
// Monospaced fonts apparently don't work here.
$barcodeOptions = array(
'text' => '11111',
'font' => ROOT_DIR . '/library/Rbs/Barcode/FreeSerif.ttf'
);
$rendererOptions = array(
'topOffset' => 50,
'leftOffset' => 50
);
Zend_Barcode::factory('code39', 'pdf',
$barcodeOptions, $rendererOptions)->setResource($pdf)->draw();
Then I have this (long) code that creates labels. I've commented below near the bottom the two main places I have experimented putting the barcode, but the core problem seems to be that I don't know how to put a barcode on a certain page of a PDF:
public function labelsAction()
{
$request['starting_label_number'] = '100001';
$request['label_count'] = 32;
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$filename= 'files/inventory_labels.pdf';
$form['units_name'] = 'inches';
$form['units_factor'] = 72;
$form['margin_bottom'] = 0.5;
$form['margin_left'] = 0.19;
$form['label_width'] = 2.625;
$form['label_height'] = 1.0;
$form['label_spacing_column'] = 0.125;
$form['label_margin'] = 0.1;
$form['label_column_count'] = 3;
$form['label_row_count'] = 10;
try
{
// create PDF
$pdf = new Zend_Pdf();
// define font resource
$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_TIMES_ROMAN);
$total_pages = ceil($request['label_count'] / ($form['label_column_count'] * $form['label_row_count']));
$current_label_number = $request['starting_label_number'];
// Create each page
for ($page_number = 1; $page_number <= $total_pages; $page_number++)
{
// create A4 page
$page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_LETTER);
// write text to page
// Fill up each page with labels or blanks
for ($row = 1; $row <= $form['label_row_count']; $row++)
{
for ($column = 1; $column <= $form['label_column_count']; $column++)
{
if ($current_label_number - $request['starting_label_number'] < $request['label_count'])
{
$label_center_y =
(
$form['margin_bottom']
+ ($form['label_row_count'] - $row + 0.5) * $form['label_height']
) * $form['units_factor'];
$label_center_x =
(
$form['margin_left']
+ ($column - 0.5) * $form['label_width']
+ ($column - 1) * $form['label_spacing_column']
) * $form['units_factor'];
// Get our bearings $xleft, $ybottom, $xright, $ytop, $filltype
$page->drawRectangle(
$label_center_x - $form['label_width'] * $form['units_factor'] / 2,
$label_center_y - $form['label_height'] * $form['units_factor'] / 2,
$label_center_x + $form['label_width'] * $form['units_factor'] / 2,
$label_center_y + $form['label_height'] * $form['units_factor'] / 2,
Zend_Pdf_Page::SHAPE_DRAW_STROKE
);
// define image resource
$image = Zend_Pdf_Image::imageWithPath('images/new/logo.jpg');
// write image to page $xleft, $ybottom, $xright, $ytop
$image_width = 125;
$image_height = 30;
$image_y_offset = 13;
$page->drawImage(
$image,
$label_center_x - $image_width / 2,
$label_center_y - $image_height / 2 + $image_y_offset,
$label_center_x + $image_width / 2,
$label_center_y + $image_height / 2 + $image_y_offset
);
$text_width = 108;
$page->setFont($font, 10)
->drawText('www.pristineauction.com', $label_center_x - $text_width / 2, $label_center_y - 10);
$text_width = 68;
$page->setFont($font, 22)
->drawText($current_label_number, $label_center_x - $text_width / 2, $label_center_y - 32);
$current_label_number += 1;
}
}
}
/* If I insert the barcode creator here inside the label loop, I get a barcode all by itself on the first PDF page, with labels following on subsequent pages. Not bad, but not right. */
// add page to document
$pdf->pages[] = $page;
}
/* If I insert the barcode creator here outside the label loop, I get a barcode superimposed on the first PDF page. Not bad, but not in page loop, and not repeating. */
// save as file
$pdf->save($filename);
$this->_redirect('/' . $filename);
} catch (Zend_Pdf_Exception $e) {
die ('PDF error: ' . $e->getMessage());
} catch (Exception $e) {
die ('Application error: ' . $e->getMessage());
}
}
A:
Well, I found the answer, thanks to Javier Bracero at http://javierbracero.blogspot.com/2012/01/zend-generate-pdf-including-list-of.html
You can supply page index as an argument! Very nice to finally know that.
The good parts:
// Create Pdf definition
$pdf = new Zend_Pdf();
// Define font resource for Pdf library
$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_TIMES_ROMAN);
// Must set a TTF for Barcode library
// This application defines ROOT_DIR in index.php. Others may define APPLICATION_PATH.
Zend_Barcode::setBarcodeFont(ROOT_DIR . '/library/Rbs/Barcode/FreeSerif.ttf');
// Create the Pdf library elements for each page and add it to the document
// before printing the Barcode elements onto that page
for ($page_index = 0; $page_index <= $last_page_index; $page_index++)
{
// create a new Pdf page
$page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_LETTER);
// write Pdf elements to the page
// add page to document
$pdf->pages[] = $page;
}
// Add barcodes to each page after it is added.
for ($page_index = 0; $page_index <= $last_page_index; $page_index++)
{
$barcodeOptions = array(
'text' => $current_label_number
);
$rendererOptions = array(
'topOffset' => $label_center_y + 3,
'leftOffset' => $label_center_x + 12
);
Zend_Barcode::factory('code39', 'pdf',
$barcodeOptions, $rendererOptions)->setResource($pdf, $page_index)->draw();
$current_label_number += 1;
}
// save as file
$pdf->save($filename);
The whole label maker:
// By Tom Haws 2012-10-03
// Prints labels with barcodes to pdf
public function labelsAction()
{
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$request['start_number'] = max(1, $this->_request->getParam('start-number'));
$request['label_count'] = $this->_request->getParam('label-count');
$inventory_number = $request['start_number'];
$filename= 'files/inventory_labels.pdf';
$form['units_name'] = 'inches';
$form['units_factor'] = 72;
$form['margin_top'] = 0.5;
$form['margin_bottom'] = 0.5;
$form['margin_left'] = 0.19;
$form['label_width'] = 2.625;
$form['label_height'] = 1.0;
$form['label_spacing_column'] = 0.125;
$form['label_margin'] = 0.1;
$form['label_column_count'] = 3;
$form['label_row_count'] = 10;
$last_page_index = ceil($request['label_count'] / ($form['label_column_count'] * $form['label_row_count'])) - 1;
$current_label_number = $request['start_number'];
try
{
// Create PDF
$pdf = new Zend_Pdf();
// Define font resource for Pdf library
$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_TIMES_ROMAN);
// Must set a TTF for Barcode library
Zend_Barcode::setBarcodeFont(ROOT_DIR . '/library/Rbs/Barcode/FreeSerif.ttf');
// Create the Pdf library elements for each page and add it to the document
// before printing the Barcode elements onto that page
for ($page_index = 0; $page_index <= $last_page_index; $page_index++)
{
// create the new Pdf page
$page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_LETTER);
// write Pdf elements to the page
// Fill up each page with labels or blanks
for ($row = 1; $row <= $form['label_row_count']; $row++)
{
for ($column = 1; $column <= $form['label_column_count']; $column++)
{
if ($current_label_number - $request['start_number'] < $request['label_count'])
{
// Note that Pdf library uses a coordinate system with origin at bottom left
$label_center_y =
(
$form['margin_bottom']
+ ($form['label_row_count'] - $row + 0.5) * $form['label_height']
) * $form['units_factor'];
$label_center_x =
(
$form['margin_left']
+ ($column - 0.5) * $form['label_width']
+ ($column - 1) * $form['label_spacing_column']
) * $form['units_factor'];
// Draw a design guidance frame for each label.
// $xleft, $ybottom, $xright, $ytop, $filltype
/*
$page->drawRectangle(
$label_center_x - $form['label_width'] * $form['units_factor'] / 2,
$label_center_y - $form['label_height'] * $form['units_factor'] / 2,
$label_center_x + $form['label_width'] * $form['units_factor'] / 2,
$label_center_y + $form['label_height'] * $form['units_factor'] / 2,
Zend_Pdf_Page::SHAPE_DRAW_STROKE
); */
// define image resource
$image = Zend_Pdf_Image::imageWithPath('images/new/logo.jpg');
// write image to page $xleft, $ybottom, $xright, $ytop
$image_width = 125;
$image_height = 30;
$image_y_offset = 20;
$page->drawImage(
$image,
$label_center_x - $image_width / 2,
$label_center_y - $image_height / 2 + $image_y_offset,
$label_center_x + $image_width / 2,
$label_center_y + $image_height / 2 + $image_y_offset
);
$text_width = 108;
$page->setFont($font, 10)
->drawText('www.pristineauction.com', $label_center_x - $text_width / 2, $label_center_y - 1);
$text_width = 68;
$page->setFont($font, 22)
->drawText($current_label_number, $label_center_x - 72, $label_center_y - 25);
$current_label_number += 1;
}
}
}
// add page to document
$pdf->pages[] = $page;
}
// Add barcodes to pages of document.
$current_label_number = $request['start_number'];
for ($page_index = 0; $page_index <= $last_page_index; $page_index++)
{
for ($row = 1; $row <= $form['label_row_count']; $row++)
{
for ($column = 1; $column <= $form['label_column_count']; $column++)
{
// Note that barcodes use a coordinate system with origin at top left
$label_center_y =
(
$form['margin_top']
+ ($row - 0.5) * $form['label_height']
) * $form['units_factor'];
$label_center_x =
(
$form['margin_left']
+ ($column - 0.5) * $form['label_width']
+ ($column - 1) * $form['label_spacing_column']
) * $form['units_factor'];
// A font path is mandatory for Barcode Pdf output.
// This application defines ROOT_DIR in index.php. Others may define APPLICATION_PATH.
$barcodeOptions = array(
'text' => $current_label_number
);
$rendererOptions = array(
'topOffset' => $label_center_y + 3,
'leftOffset' => $label_center_x + 12
);
Zend_Barcode::factory('code39', 'pdf',
$barcodeOptions, $rendererOptions)->setResource($pdf, $page_index)->draw();
$current_label_number += 1;
}
}
}
// save as file
$pdf->save($filename);
$this->_redirect('/' . $filename);
} catch (Zend_Pdf_Exception $e) {
die ('PDF error: ' . $e->getMessage());
} catch (Exception $e) {
die ('Application error: ' . $e->getMessage());
}
}
|
[
"cooking.stackexchange",
"0000021721.txt"
] | Q:
What to do with crumbled muffins?
I made some muffins that apparently didn't have enough liquid to stick together (perhaps substituting Greek yogurt for sour cream was not such a good idea, as that, butter, and an egg contributed the only liquid). So the muffins crumbled completely on leaving the greased tin. Are there any culinary uses for them, or am I stuck trying to eat the big chunks and throw the rest out? They are so crumbly that packing them to the office for breakfast like I usually do won't work.
The specific ones I made are cinnamon coffee cake flavored, but I'd be curious about the general case.
A:
I would make "cake balls" out of them. Maybe make this Apple Butter Frosting, combine with the crumbles and form balls out of the combo and then freeze or refrigerate them. I think these would be best served "uncoated" so maybe a quick cream cheese icing drizzle across the tops. Serve as a dessert and enjoy.
A:
Since it sounds like they are basically a dried out batter at this point, I would turn to implementations that rely on those kind of food-stuffs;
With some further baking and possibly additional brown sugar and butter or apple-sauce, I would use them for a crumble topping. If they are coffee and cinnamon an apple-cardamom cobbler would benefit nicely.
The crumbles could be incorporated into a biscuit batter recipe
In all likelihood, any kind of recipe that relies on a granola could probably be referenced for further ideas.
You could also use the crumble as a stand-in for oat based no-bakes. The no-bakes might feel mealy to the tooth, so not entirely eliminating the oat might work best.
If you wanted to repurpose, you might try thinking of it as a material to be suspended. With an ingredient like well-blended coconut butter (not to be confused with coconut oil or milk or cream) you could create a base with which to make a kind of post-raw bar cookie (basically press and chill the coconut butter in a pan on top of wax/parchment paper, pulse the muffin bits with some dates or brown rice syrup, and once the butter sets press the bits/dates mixture into the top and drizzle with some ganache or whatever).
A:
I would use the crumbs to make a trifle dessert. Layer the crumbs with pudding and fruit in a glass serving container. You can use the muffin crumbs for the bottom, middle, or top layers and fill the layers in between with vanilla pudding, banana, and walnuts for a tasty combination. Top the trifle with whipped cream and more nuts or sliced fruit.
You could also make a bread pudding. Combine about 3 cups of crumbs with a cooked custard mixture (recipe below) and place the baking pan with the combination inside a second pan half-filled with water.
For the custard mixture... heat 2 cups half and half just to a boil and pour into a mixture of 1/2 cup sugar, 3 eggs and 2 egg yolks. Bake at 325 degrees F for 1 hour or until a knife inserted comes out clean.
|
[
"stackoverflow",
"0029815310.txt"
] | Q:
Materialize: dropdown in "if" statement doesn't work
I tried to implement a dropdown list that is only visible when the user is signed in. The dropdown list works when outside the "if" statement but not inside. The buttons "Foo" and dropdown button are shown, however it doesn't "dropdown".
header.html
<!-- Header -->
<template name="header">
<nav>
<div class="nav-wrapper">
<a class="brand-logo" href="{{pathFor 'home'}}">Logo</a>
<ul id="nav-mobile" class="right hide-on-med-and-down">
{{#if currentUser}}
<!-- dropdown1 trigger -->
<li>
<a class="dropdown-button" href="#!" data-activates="dropdown1">
<i class="mdi-navigation-more-vert"></i>
</a>
</li>
<li><a href="#">Foo</a></li>
{{else}}
<li><a href="{{pathFor 'signin'}}">Sign in</a></li>
{{/if}}
<li><a href="{{pathFor 'about'}}">About</a></li>
</ul>
</div>
</nav>
<!-- dropdown1 structure -->
<ul id="dropdown1" class="dropdown-content">
<li class="signout"><a href="#!">Sign out</a></li>
</ul>
</template>
header.js
Template.header.rendered = function () {
$(".dropdown-button").dropdown({
belowOrigin: true // Displays dropdown below the button
});
};
What could be the problem?
A:
When your Template.header.onRendered lifecycle event is first fired, the dropdown HTML elements are not yet inserted into the DOM because the condition {{#if currentUser}} is not yet met (it takes a small amount of time before being actually logged in a Meteor app, that's why Meteor.user being reactive is handy !).
This is why your jQuery dropdown initialization fails : the DOM is not yet ready ! The solution is quite simple thoug : refactor your Spacebars code to put the dropdown markup in its own separate template :
<template name="dropdown">
<li>
<a class="dropdown-button" href="#!" data-activates="dropdown1">
<i class="mdi-navigation-more-vert"></i>
</a>
</li>
<li><a href="#">Foo</a></li>
</template>
Then insert the child template inside your header template :
{{#if currentUser}}
{{> dropdown}}
{{else}}
{{! ... }}
{{/if}}
This way the dropdown will have its own onRendered lifecycle event that will get triggered only after the user is logged in, and at this time the dropdown DOM will be ready.
Template.dropdown.onRendered(function(){
this.$(".dropdown-button").dropdown({
belowOrigin: true // Displays dropdown below the button
});
});
Sometimes refactoring your code into smaller subtasks is not just a matter of style, but it makes things work the way intended.
|
[
"philosophy.stackexchange",
"0000038635.txt"
] | Q:
When is a thing the same as another thing?
I keep having a thought, which is probably silly. It would be good if you could put it to rest, or point me to an area of discourse where this is discussed.
Take two things in the abstract, which differ in some ways that are known. If we remove those things which make them different, do we have the same thing?
If we do the same in the physical world with two objects that are different and remove those things which make them different, do they become the same thing?
As an example, if we take two different photons and remove the things which make them different, do they become the same photon?
Could this explain what is happening with Quantum Mechanical weirdness?
A:
David Deutsch has tried to explain quantum mechanics along the lines you have considered in his book "The Beginning of Infinity" chapter 11.
A physical system can exist in multiple instances that are identical in every measurable respect - Deutsch describes them as fungible. A quantum system changes over time by rules that dictate how many of the fungible instances of a system change their values. The rule doesn't dictate which instances out of the fungible set change their values since there is no way to distinguish them before the change. Deutsch uses this idea to explain features of quantum interference and other features of quantum mechanics.
For a blog post explaining how some of these ideas correspond to the formalism of quantum mechanics, see
https://conjecturesandrefutations.com/2015/04/04/fungibility-in-quantum-mechanics/
|
[
"es.stackoverflow",
"0000061344.txt"
] | Q:
Asignar un Select a un Table en Funcion SQL
En una función en SQL Server hay alguna manera de crear una tabla y asignarle el valor de una consulta, algo como
CREATE TABLE AuxAlumnos
(
Id int,
Nombre varchar (10),
Apellido varchar(10)
);
Y a esa tabla asignarle el valor de un SELECT * FROM Alumnos
A:
Si se puede o puedes hacer con tablas temporales o tablas concretas te quedara algo similar a esto :
Tabla concreta :
CREATE PROCEDURE MI_PROCEDIMIENTO
AS
CREATE TABLE #AuxAlumnos
(
Id int,
Nombre varchar (10),
Apellido varchar(10)
);
INSERT INTO #AuxAlumnos (ID,NOMBRE,APELLIDO)
SELECT ID,NOMBRE,APELLIDO
FROM Alumnos
Tabla Temporal :
CREATE PROCEDURE MI_PROCEDIMIENTO
AS
DECLARE @AuxAlumnos TABLE
(
Id int,
Nombre varchar (10),
Apellido varchar(10)
)
INSERT INTO @AuxAlumnos (ID,NOMBRE,APELLIDO)
SELECT ID,NOMBRE,APELLIDO
FROM Alumnos
luego solo debes hacer el select a la tabla que acabas de crear.
Espero sea de tu ayuda
Saludos
|
[
"stackoverflow",
"0051597556.txt"
] | Q:
UPDATE Statement with Randomly Assigned Values
I'm trying to synthetically generate some seed values for a database. I have a list of employees and I want roughly 30% of them to be classified as "Minority" and the rest "Non-Minority", I thought that the following would work but it's classifying everyone as "Minority":
UPDATE datasetitems
SET minority = CASE WHEN (FLOOR(RAND()*(10-1+1)+1) > 3)
THEN 'Minority' ELSE 'Non-Minority' END;
A:
For what you are trying to do RAND() will not work because it generates a single random value for the batch which is why you're not seeing any variance. To generate a random value for each row use:
ABS(CHECKSUM(NEWID())%<desired max random number>)
Note this sample data:
DECLARE @datasetitems TABLE (minority VARCHAR(20));
INSERT @datasetitems(minority)
SELECT TOP (10) NULL FROM sys.all_columns;
SELECT CASE ABS(CHECKSUM(NEWID())%2) WHEN 0 THEN 'minority' ELSE 'non-minority' END
FROM @datasetitems;
Returns:
------------
non-minority
non-minority
minority
minority
minority
non-minority
minority
non-minority
minority
minority
ABS(CHECKSUM(NEWID())%2) will return a 0 or 1 for each row meaning that you'll have a 50/50 chance that you'll return minority or non-minority. This logic:
SELECT CASE ABS(CHECKSUM(NEWID())%4) WHEN 0 THEN 'minority' ELSE 'non-minority' END
FROM @datasetitems;
... would mean that there's a 1 in 4 chance that "minority" will be returned and a 3 in 4 chance that "non-minority" is returned. To apply this logic to your update, your code would look like this:
UPDATE @datasetitems
SET minority = CASE ABS(CHECKSUM(NEWID())%2) WHEN 0 THEN 'minority' ELSE 'non-minority' END
FROM @datasetitems;
|
[
"stackoverflow",
"0038641524.txt"
] | Q:
Nginx reverse proxy to Unicorn - nginx configuration is incorrect?
I followed this tutorial to configure my rails app to run Unicorn, and be reversed proxy by Nginx on my AWS ubuntu instance.
I am able to access the nginx, "Welcome to nginx!" default page, running on the site from the outside(security is configured properly). But it is not serving the rails app.
My unicorn is running under /home/ubuntu/appname/shared/sockets/unicorn.sock=
I ran sudo service unicorn restart just in case.
when i run sudo service --status-all it returns:
[ ? ] unicorn_gpei-tk
As I mentioned nginx is definitely running, here is the config located in /etc/nginx/sites-available/default:
upstream app {
# Path to Unicorn SOCK file, as defined previously
server unix:/home/ubuntu/appname/shared/sockets/unicorn.sock fail_timeout=0;
}
server {
listen 80;
server_name localhost;
root /home/ubuntu/appname/public;
try_files $uri/index.html $uri @app;
location @app {
proxy_pass http://app;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
}
error_page 500 502 503 504 /500.html;
client_max_body_size 4G;
keepalive_timeout 10;
}
symlink in /etc/nginx/sites-enabled is default -> /etc/nginx/sites-available/default -- I guess second question would be: is the sites-enabled necessary? The tutorial does not mention/require it, I came across this after the 1000 other resources I am attempting to decipher this issue.
Other info: if I run Unicorn as a user I am able to connect to it on port 8080, so Unicorn does run on it's own as well and serve the site.
And I've also restarted nginx service a few times as well, still does not update the config, probably because I have it wrong somewhere.
Really am not seeing what I am missing, any clues/ideas? thanks.
Edit:
I went into /var/log/nginx/error.log (there's an error.log.1 but it doesnt seem to be updating) and this is showing up:
2016/07/28 16:21:19 [error] 11763#11763: *2 open() "/usr/share/nginx/html/favicon.ico" failed (2: No such file or directory), client: XX.XXX.XXX.XX, server: localhost, request: "GET /favicon.ico HTTP/1.1", host: "my_public_address.com", referrer: "http://my_public_address.com/"
and /var/log/nginx/access.log is:
XX.XXX.XXX.XX - - [28/Jul/2016:16:24:58 +0000] "GET /favicon.ico HTTP/1.1" 404 571 "http://my_public_address.com/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36" "-"
A:
I found the issue and fixed it.
You need to include the configuration for what you want. in /etc/nginx/nginx.conf comment out the default config because it is pointing to localhost.
add the configuration you want to the here. in my case it was this:
/etc/nginx/sites-available/* i only have one config file in there but just felt like putting *.
restart nginx service.
many newbie hours of headache all gone now.
|
[
"stackoverflow",
"0055981622.txt"
] | Q:
re-numbering list members in python
How can re-numbering list members respectively from zero to n in Python ?
for example :
In : [4, 10, 12, 40, 4, 12, 20, 21]
Out : [0, 1, 2, 3, 0, 2, 4, 5]
A:
Here you go, the solution for your problem
x=[4, 10, 12, 40, 4, 12, 20, 21]
y=[0]
nextIndex=1;
for i in (range(1,len(x))):
for j in range(i):
if(x[i]==x[j]):
y.append(y[j])
break
if(j==i-1):
y.append(nextIndex)
nextIndex+=1
print(y)
Output:
[0, 1, 2, 3, 0, 2, 4, 5]
Basically what the user is trying is to get a same index for repeated integer and assigning new one for new integer
@Rafat try to be more clear with your questions next time.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.