What may go wrong if I don't use === or !== in PHP

Question:
Possible Duplicate:
php == vs === operator
Is there a difference between !== and != in PHP?

In PHP, the condition of the if command contains operator === and !==.
I never use them. So I wonder when will we actually need to call them?
E.g.
if (FALSE !=  someMethod() ) {
}

if (FALSE !== someMethod() ) {
}

What may go wrong with the 1st if?
Comment: exact duplicate of the 1000s of the kind
Comment: Before asking, you should try to spend some time on google
Comment: @Col.Shrapnel When you vote close you can nominate one of the '1000's.
Comment: @NamGVU Did my answer help you?
Comment: @Paulpro No, sorry it's not.
Answer: 0 == '' == null == false == array()

If you need to know the difference between two of these, you need ===.
http://php.net/manual/en/function.strpos.php
int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

strpos('apple', 'a') == 0

strpos('apple', 'b') == false

Without a === you won't know if 'apple' has 'a' in the first position or if it doesn't exist.
Comment: For strpos sample, I don't think comparing with boolean value is the right usage of this method.
Comment: Though, your statement on `0`, `null`, `''`, `false`, and `array()` is the excellent point-out for me. Great thanks.
Answer: Take an example like this:
$str = '*Hello*World*';
if (FALSE != strpos($str, '*')){
    // Echo if string has an '*' in it!
    echo $str;
}

This won't work, because strpos() returns the index of the first match. In this case it returns 0. FALSE == 0, but FALSE !== 0.
Comment: @NamGVU `strpos` returns a boolean if there is no match. It can also return `0` if the match is at the very beginning of the string. If you use `!=` you can't tell whether it returned `0` or `false`, but if you use `!==` you can tell the difference between a match at the beginning of a string or no match at all.
Comment: @NamGVU Also see the warning in the section about the return values in the PHP manual page for [strpos](http://php.net/manual/en/function.strpos.php)
Comment: I think your good scenario describe a wrong usage of `strpos` function - the meaning of the returned integer value SHOULD NOT be used as boolean at all. And that's not persuade enough for me to use !== there indeed.
Comment: Agree. My bad not reading the manual carefully. Thanks a lot for helping me to know that!
Comment: After all, this leads to PHP's design for such `strpos` function - I mean if PHP considers FALSE and 0 to be "the same" when compared, then they should make strpos to be the traditional way as other languages do e.g. C++, Java, C# ect.
Comment: @NamGVU Yeah, PHP is a very weird language in many different ways.
Answer: PHP uses loose comparison when you use == and !=' instead of===and '!==. Loose comparison means, that types are compared on 'similarity'. To get an overview of how types compare, look here
Comment: Would be lovely if you would bring up some samples. Thanks


Include content of a block in a view template

Question: I'm trying to create a Twig view that renders:

Intro block
View content
outro block (yes, made up word for the opposite of intro)

The reason I'm putting these three things in one view is that I have a repeating background pattern; if each item is rendered alone, the background does not display smoothly across/through each element.
I've been trying to put this line - {% include 'block--intro.html.twig' %}, based upon block.html.twig - into the appropriate place of the view twig file, but when the page containing this view is rendered the {{ contents }} of the block is empty.
How should I be trying to do this?
I am using Drupal 8.2.4. The base theme is Bootstrap; we are using a subtheme of that.
Answer: You can't mix different templates types like views and block templates. Every template has other variables and so the block template doesn't find the content variable in the views template context.
In your case for a View you could place the block in the header or footer in Views UI. For example a Rendered entity - Block.
In general you can use the module Twig Tweak instead of {% include %} to render a block template or any other entity template:
{{ drupal_entity('block_content', 1) }}

This works, because it renders the entity in its own variable scope and so you can place it everywhere in twig.

While entities normally render in their own template, block content is special, because it doesn't have a template on its own. So the command above only shows the fields. To get the block wrapper you need to use drupal_block().


Intuition behind characterizations of supremum?

Question: Can anyone help me understand the intuition behind the characterization of the supremum? I understand supremums and infinmums in the context of the Completeness Property / Supremum Property, which is: Let $S \subset E$.
(1) $b$ is an upper bound of $S$ if $\forall x \in S$, $x \leq b$.
(2) $\beta$ is the supremum of $S$ if for all upper bound $b$ of $S$, $\beta \leq b$.
However, once you throw an epsilon into the definition, ie. Characterization of the supremum, I'm suddenly lost on what a supremum is. The Characterization of the supremum states that $\beta$ is a supremum if:
$$\forall \epsilon > 0, \exists s_{\epsilon}\text{ s.t. }\beta - \epsilon \leq s_{\epsilon}.$$
What does that mean?!?
Thanks so much for the help!!
Comment: Your "Characterization of the supremum" is not correctly stated, which might play a role in your difficulty in understanding it. In (2) you express the idea that $\beta$ is greater than or equal to every upper bound $b$ of $S$.  Actually the idea of a supremum is that of *least upper bound*, so (2) should have said $\beta \le b$ for every upper bound $b$ of $S$ *and* that $\beta$ itself is also an upper bound of $S$.
Comment: Instead of supremum say "least upper bound".
Comment: @LordSharktheUnknown Can you elaborate on why? Aren't supremums and least upper bounds the same thing? Thanks!
Comment: "least upper bound" tells you exactly what it is.
Comment: @hardmath, oops typo - I will fix it. Thanks!
Comment: You are still missing the requirement (for $\beta$ to be a supremum of $S$) in (2) that $\beta$ is an upper bound.
Answer: For β to be a least upper bound, everything smaller must fail to be an upper bound (if there were something smaller that is still an upper bound, then β wouldn't be the least upper bound). That is, given any B < β, B must not be an upper bound. B is an upper bound if it's larger than everything in the set: for all s in the set, s < B. So not being an upper bound would be the negation of that. In other words, to fail to be an upper bound, there must be something in the set larger than B. So for every B smaller than β, there must be something in the set larger than B. If B is smaller than β, then we must be able to get to B by subtracting something from β. So the characterization says that no matter how small an amount (ϵ) we subtract from β, we end up with a number (β-ϵ) that is smaller than some member of the set (sϵ), and thus β-ϵ is not an upper bound.
Or, another way of putting it is there is no "space" between β and the set; if you were standing on the number line at β and stretched out your arms, you would hit a member of the set, no matter how short your arms are; there is no ϵ such that you can go ϵ away from β and not reach the set.
Comment: Thanks so much! You explained this better than my professor has for weeks! The "space" example makes a lot of intuitive sense to me. Does this mean that the characterization of the supremum also states the uniqueness of the least upper bound?


Make a modal load faster

Question: I have created a full page modal box to appear on pageload. I have one problem though. My homepage has to completely load before the modal shows up and I would like the modal to appear faster and not show any of my homepage. Is there any way to speed up a modal or make sure the homepage doesn't show before the modal? Any help is appreciated. Thank you!
Comment: Normally you would load the absolute minimum of the web page and then load everything else via AJAX. That's the most reliable way of doing this.
Answer: Check out Yahoo's best practices for high performance web sites (and Google's) .

Instead of loading the entire page, just load the minimum to show the modal, then post-load the rest.
If the guest is on your site before seeing the modal, pre-load any resources the client will need to render the modal. If you cache these resources, that will save time when they get to the modal.
Eliminate unnecessary resources. For example, if your modal has an image, can it be replaced with CSS? Even a small image requires the overhead of an additional HTTP Request (unless it was preloaded).

I could go on, but these resources from Google and Yahoo are very helpful.
Comment: This is great info, but is there anything quick and easy for the time being? I'm still a beginner at javascript and do not have time to implement any involved changes.
Comment: Every homepage is different, so I can't say exactly what is making your homepage slow without more information. You don't need to use all of them, but taking the time to deeply understand these performance fundamentals will help you on all of your projects, letting you pick and choose from these options to suit a project's unique needs.

Make a modal load faster


Jquery "scrollTop" & "height" .click delay issues

Question: Having a couple of small issues with my code. I've written out a JQUERY sequence where you would click "sign up" and you get scrolled down where a form reveals itself. For now I have a button on the bottom where the function closes the form and scrolls you back to the top.
The example can be seen here: http://www.icecable.com/sandbox/priority%5Fsign%5Fup/test.html
Click on "Sign Up Now" and the animation works correctly. Click "Close and Return to Top" and the animation, again, works correctly. The problem comes after this.
If you try clicking on either "Sign Up Now" button the "height" animation begins as normal but there is a large delay on the "scrollTop" animation for no apparent reason.
Here is my code
$(document).ready(function() {

$('.dealer').click(function(e) {
    e.preventDefault();
    $('html, body').animate({
        scrollTop: '860'
    }, 1800, "easeInOutQuint");
});

$('.top').click(function(e) {
    e.preventDefault();
    $('html, body').animate({
        scrollTop: '0px'
    }, 1500, "easeInOutQuint");
});

$('.dealer').click(function(e) {
    e.preventDefault();
  $('#priority').animate({
    height: 'show'
    }, 1200,  "easeInOutCirc");
});

$('.top').click(function(e) {
    e.preventDefault();
  $('#priority')
    .animate({
        height: 'hide'
        }, 590, "easeInQuint");

});

//Form for Distributors

$('.distributor').click(function(e) {
    e.preventDefault();
    $('html, body').animate({
        scrollTop: '860'
    }, 1800, "easeInOutQuint");
});

$('.top').click(function(e) {
    e.preventDefault();
    $('html, body').animate({
        scrollTop: '0px'
    }, 1500, "easeInOutQuint");
});

$('.distributor').click(function(e) {
    e.preventDefault();
  $('#distributor').animate({
    height: 'show'
    }, 1200,  "easeInOutCirc");
});

$('.top').click(function(e) {
    e.preventDefault();
  $('#distributor')
    .animate({
        height: 'hide'
        }, 590, "easeInQuint");

    });
});

Anything I'm doing wrong? Is there a way to reset the events after the forms have been hidden again? Any help/insight/resources would be greatly appreciated!
Will
Answer: Without a fiddle, I cannot say for sure, but I suggest that you use some console.log calls to print out to start and end scrollTop values. I have had some issues like this before, and they are typically due to issues with scrolling the wrong amounts and restoring to the wrong amounts.
The likely case, which you might not notice, is that when you scroll back up, your scrollTop value goes beyond 0 to some negative number. The window cannot scroll to a negative scrollTop, so it would have to "wait" until the value returns to 0 before it can begin the visible animation.
NOTE: It is possible for this to happen, even if you have set the scrollTop to zero, as this may not have been its initial position. When I said "negative", what I meant was "negative relative to the initial position".
Update: Take a look at this page. It also links to a corresponding SO post and tells you how to smoothly scroll to the top. I have used modified versions of the code before and, though it is very similar to what you have, the SO posts might give you a little extra insight.
I would also change your animate functions to only call on the "html" element, instead of both the "html" element and the "body" element.
Comment: Much appreciated response! I tried editing the top position values but I was still getting the delay. I'm not sure how to call for the position values as it scrolls in the console log. So I don't think it's going into the negative number for position but it might just be going passed the original number as you suggested. I just can't figure out how to see that. Thanks again.
Comment: I do not believe that you can display the positions during the scrolling (I may be mistaken - I don't remember), but so long as you can check before the scrolling starts and after it stops, you should be able to get some good data.


Decomposition of $l$ in a subfield of a cyclotomic number field of an odd prime order $l$

Question: Let $l$ be an odd prime number and $\zeta$ be a primitive $l$-th  root of unity in $\mathbb{C}$.
Let $K = \mathbb{Q}(\zeta)$.
Let $A$ be the ring of algebraic integers in $K$.
Let $G$ be the Galois group of $\mathbb{Q}(\zeta)/\mathbb{Q}$.
$G$ is isomorphic to $(\mathbb{Z}/l\mathbb{Z})^*$.
Hence $G$ is a cyclic group of order $l - 1$.
Let $f$ be a positive divisor of $l - 1$.
Let $e = (l - 1)/f$.
There exists a unique subgroup $G_f$ of $G$ whose order is $f$.
Let $K_f$ be the fixed subfield of $K$ by $G_f$.
Let $A_f$ be the ring of algebraic integers in $K_f$.
Let $\mathfrak{l} = (1 - \zeta)A$.
$\mathfrak{l}$ is a prime ideal lying over $l$.
Let $\mathfrak{l}_f = \mathfrak{l} \cap A_f$.
My question: Is the following proposition true? If yes, how would you prove this?
Proposition
(1) $lA = \mathfrak{l}^{l-1}$.
(2) $lA_f = \mathfrak{l}_f^e$.
(3) $\mathfrak{l}_fA = \mathfrak{l}^f$
Answer: Note: I am going to use $p$ everywhere instead of $l$.
Yes, and it all follows from the fact that $p$ is totally ramified. To see this, show that $N_{K/\mathbb{Q}}(1-\zeta) = p = [A : \mathfrak{p}]$ and notice that $p = \prod_{k \in (\mathbb{Z}/p\mathbb{Z})^\times} (1 - \zeta^k) = \epsilon (1 - \zeta)^{p-1}$ for some cyclotomic unit $\epsilon$. Hence $pA = \mathfrak{p}^{p-1}$.
$(2)$ and $(3)$ are immediate consequences of $(1)$.


Is possible to add a field to content moderation's states?

Question: I'm on D 9.4.x and using content moderation module.
Is possible to add a custom field to the states of the workflows\module?
E.g. add a boolean?
Answer: Out of the box? No.
You will have to create a custom module that adds such boolean field to your content types or entity types.
Via hook_form_alter you can use #ajax with #access OR alternatively use #states to show/hide the field when a different moderation state is selected.
Comment: @Giuseppe That is because content moderation state is not a [fieldable entity](https://www.drupal.org/docs/7/api/field-api/making-an-entity-fieldable)
Comment: Probably I was not clear, I'm trying to add the field to the state itself, e.g. to the `draft` state. The problem I'm facing it's that the code I found in internet about isn't working. I don't know if the reason is because the `core/modules/workflows/src/StateInterface.php` doesn't extends any other of the "entity" interfaces, or else.


user id mapping failing with nfs and ldap

Question: I have a NFS4 export (from FreeBSD ZFS filesystem) with root_squash turned off (-maproot=root).
Until recently I've been mounting this drive without problems on several machines (mostly Ubuntu 12.04 server), but all of a sudden I've run into this strange problem:
On three OSes I've tried to setup (Mint 15, Ubuntu 13.04, Ubuntu 12.04 client) I do the ldap and nfs configuration and mount the drives and everything appears fine.  I can see appropriate user and group names mapped from ids.  But if I try to chown any of these files to any other user it always sets them to nobody:nobody.
Note, this does not happen on the older machines.  I've even copied the exact configurations (/etc/idmapd.conf, /etc/ldap*, /etc/pam.d/*) from the older Ubuntu 12.04 machines to the new one and it still won't work!  It also seems mostly restricted to chown.  I can touch new files as any user and they have correct ownership.  I have no idea what's going on.
The only clue I might have gotten is that the broken machines give this error in syslog (after increasing verbosity in idmapd):
Sep 10 16:58:48 cabernet rpc.idmapd[1009]: nfs4_name_to_uid: calling nsswitch->name_to_uid
Sep 10 16:58:48 cabernet rpc.idmapd[1009]: nss_getpwnam: name 'firstname.lastname@example.com' domain 'test.com': resulting localname '5000'
Sep 10 16:58:48 cabernet rpc.idmapd[1009]: nss_getpwnam: name '5000' not found in domain 'test.com'

While the working machines give:
Sep 10 17:03:44 node-2 rpc.idmapd[2906]: nfs4_uid_to_name: calling nsswitch->uid_to_name
Sep 10 17:03:44 node-2 rpc.idmapd[2906]: nfs4_uid_to_name: nsswitch->uid_to_name returned 0
Sep 10 17:03:44 node-2 rpc.idmapd[2906]: nfs4_uid_to_name: final return value is 0
Sep 10 17:03:44 node-2 rpc.idmapd[2906]: Client 18: (user) id "5000" -> name "firstname.lastname@example.com"

So it looks like for some reason the broken machines are trying to use the id as the username.
Any advice?
Answer: This was resolved via the following setting in http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=500778
/etc/idmapd.conf
[General]
Cache-Expiration = 10

You can visit http://permalink.gmane.org/gmane.linux.nfs/44754


WooCommerce tracking variable product views/selects

Question: I'm just working on the tracking of woocommerce variable products with google analytics. Tracking simple products is not a big deal, because every page view is a product. However for me it's pretty interessing to know which product variations users looked at.
I need some similar stats for variable products. Which variable products did the users look at? My products do have quite some variations since one product has about 7 attributes.
I think it shouldn't be to hard to hook into the drop down selects of woocommerce variable products with js and fire on select.
How would you track the product variation views with google analytics?
I don't want to mix page views, sales and on the other hand view of product variations too much. I'd rather prefer to track the views of variations through events into a different view (or property). How you get those events into one view and everything else in the default view?
How would you track the parameters to be able to analyse them? My main filter will be product, than I want to filter on different attributes and see how the other attributes cluster on user impressions.
Anyone already has a script for this?
Answer: You can just add event handler for 'found_variation' in JS. That is woocommerce event for selecting variation.
And then use analytics built in function:
https://developers.google.com/analytics/devguides/collection/gajs/eventTrackerGuide
<code>jQuery(document).ready(function($) {
    $(this).on('found_variation', function(event, variation) {
        _gaq.push(['_trackEvent', 'Variation', 'Select', variation.variation_id]);
    });
});
</code>
Haven't tested it but in theory it should work.
And just check variable 'variation' to see what info is available.
Comment: Could have thought of tracking the variation id myself ^^ this makes much more sence than tracking single attribute changes! I really appreciate your code snipped @ViszinisA. works! Gonna Test in production now.


WTForms with a variable amount of textareas

Question: I have a HTML form with my Flask application which includes a textarea however, the user can press a button which adds another textarea to the form to create an infinite amount of textareas.
As I'm not using WTForms, validation is much harder and so I've done it on the client side with Javascript however anyone with programming skills can edit this code which is unsafe. I would prefer to validate the form with WTForms.
Is this even possible to do with WTForms and Flask or would I have to create my own method with Flask and flashing messages to validate the form? Thanks.
Edit:
HTML:
<form id="myForm">
  <input type="text">
  <textarea></textarea>
  <textarea></textarea>
</form>
<button onclick="add()">Add textarea</button>

So in my case, I also have an input at the beginning which I would like to validate. I would also like to validate that all the textareas so that they are not allowed to be empty.
I would like to validate this with WTForms though to create a form with WTForms, it must be created in Python and then rendered in HTML. As textareas are added to the form, they cannot be validated as they are not defined in the python code to create the WTForms.
The issue is, I would like to be able to add form elements to a form created with WTForms.
Comment: I think the answer is yes it is possible, but I am not sure I understand your concerns with validation. Have you used WTForms? I can see a way to add text areas as a result of a button click. You could use the `validate_on_submit()` function which is a part of WTForms as a trigger for adding a new text area. If this stuff is new to you, I can try writing up an answer. I am new to Flask as well though, so my answer will likely not be technically correct.
Comment: How would I go about this then? Because as far as I know, with WTForms I have to specify the form and it's textareas in Python before it is rendered in HTML.
Comment: I have yet to start actually writing code for this, which I plan to do regardless of whether or not an answer shows up, for my own learning purposes. I think if you declare a global dictionary in Python, you could communicate the button click to the Python script, and with proper control send off a new text area to be rendered, once re-directed. You might not need a global dictionary... but the arguments to render_template would need to be generated within the view function. That's how I am seeing it. I am sure though that there is an extension with this in mind.
Comment: I have no issue with adding a textarea to the page, I'm doing that with javascript, however it is just getting these new textareas to work with WTForms.
Comment: Can you show some of the code? i.e. The relevant parts of your flask app and the project directory structure. I'm not understanding your problem for some reason, I think seeing some code will help me understand what's going on.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/87668/discussion-between-skywalker-and-pav-sidhu).
Comment: Alright here is what I have thus far. [flasky-buttons](https://github.com/callmeskywalker/flasky-buttons). `git clone` it and make sure you all the extensions I import at the top of `buttons.py`. Run `python buttons.py` and then visit `http://localhost:5000/buttons`. I provide the same functionality of adding buttons via WTForms. I don't know what you want the submit button to do, store the data from all the fields? Hope this helps, let me know of any troubles. I will write up my answer once I have the submit button functioning
Answer: The way I solved this was by using WTForms to validate the <input type=text> and then using simple flash() messages for the textareas if they were empty.
@app.route('/form')
def form():
  form = some_form()

  if request.method == 'POST':
        newQuestions = []
        i = 1
        alreadyBlank = False
        while True:
            try:
                question = request.form['question' + str(i)]

                if question.strip(' \t\n\r') == '' and not alreadyBlank
                    flash('Please don\'t leave any questions blank.')
                    alreadyBlank = True

                newQuestions.append(question)
                i += 1
            except:
                break

  if form.validate_on_submit():
    input_content = form.input.data


How to use AES CBC using a key longer than 256 bits in Python

Question: Anyone have a way to encrypt/decrypt using Python to handle AES in CBC mode with a key of 1024 bits (128 bytes)? All the AES pkgs found so far seem to be limited to 256 bit keys. My crypto background is limited....
Comment: First of all, 1024 bit == 128 byte. Second, you can't.
Answer: AES is only defined for key sizes of 128, 192 and 256 bit. The is no way to use some other key size and still call it AES. If you want to be compatible with other implementations, you will have to stick to the defined key sizes.
Two common ways to get a key of the correct size are:

Simply slice only a part of your key off toatch one of the valid sizes. This should only be done if the big key was created with much entropy. If not then you might make brute forcing much easier.
Run the big key through some hash function such as SHA-256 to get a 256 bit key. Again, if the big key has low entropy the you should regard it as a long password and run it for example through PBKDF2 with many iterations.


Find records which have multiple occurrences in another table array (postgres)

Question: I have a table which has records in array. Also there is another table which have single string records. I want to get records which have multiple occurrences in another table. Following are tables;
Vehicle
veh_id |             vehicle_types
-------+---------------------------------------
    1  | {"byd_tang","volt","viper","laferrari"}
    2  | {"volt","viper"}
    3  | {"byd_tang","sonata","jaguarxf"}
    4  | {"swift","teslax","mirai"}
    5  | {"volt","viper"}
    6  | {"viper","ferrariff","bmwi8","viper"}
    7  | {"ferrariff","viper","viper","volt"}

vehicle_names
    id |  vehicle_name
  -----+-----------------------
    1  |  byd_tang
    2  |  volt
    3  | viper
    4  | laferrari
    5  | sonata
    6  |  jaguarxf
    7  |  swift
    8  |  teslax
    9  | mirai
    10 | ferrariff
    11 | bmwi8

I have a query which can give output what I expect but its not optimal and may be its expensive query.
This is the query:
select veh_name
from vehicle_names dsb
where (select count(*) from vehicle dsd
       where dsb.veh_name = ANY (dsd.veh_types)) > 1

The output should be:
 byd_tang
 volt
 viper

Answer: One option would be an aggregation query:
SELECT
   vn.id,
   vn.veh_name
FROM vehicle_names vn
INNER JOIN vehicle v
   ON vn. veh_name = ANY (v.veh_types)
GROUP BY
  vn.id,
  vn.veh_name
HAVING
  COUNT(*) > 1;

This only counts a vehicle name which appears in two or more records in the other table.  It would not pick up, for example, a single vehicle record with the same name appearing two or more times.


How to run cron automatically after node published?

Question: cron has to run after some time  of node publishing.I tried like this
<code> function custom_module_cron{
//($updated = node published time)
if(date("Y/m/d H:i:s") == date("Y/m/d H:i:s",$updated+60)){
//code here
}
}
</code>
but its not running automatically. Can anybody help ?
Comment: Can you elaborate on what you need to do 60 seconds after a node is published?  cron is likely not the right solution to your actual problem.
Answer: have you managed your cron configuration, if no then go to /admin/config/system/cron and set your cron settings to run on that interval of time.
Hope it solves your issue.
Comment: Thanks for your reply .But my requirement is not particular interval of time .after 60 seconds of every node publishing.


What happens if you have NS domains be resolved by their own NS servers?

Question: Let me explain.
For example, you have a site, site.com, and on the domain provider service, you decide you want to have your own nameservers, and enter the new addresses.
You decide to let these nameservers have domain names, ns.site.com.
Now what happens if a client wants to resolve my.site.com, as far as i understand it, it (client and/or recursive DNS servers) will ask for authority for the second level domain record of site.com, pick the NS name from it, and resolve that to contact it.
Now we have set the nameserver to ns.site.com, which lays in it's own domain... wait, that's recursive.
This is exactly what I think could be a problem, how is it solved in the real world? Does/did this ever happen?
Comment: See also: [What is a glue record?](https://serverfault.com/questions/309622/what-is-a-glue-record)
Comment: No need to be sorry! :) Without knowing that exact term, it would difficult to search for.
Comment: Well sorry, i did not know that even existed, that's why I'm asking.
Answer: From a nice post on serverfault

A glue record is a term for a record that's served by a DNS server
  that's not authoritative for the zone, to avoid a condition of
  impossible dependencies for a DNS zone.
Say I own a DNS zone for example.com. I want to have DNS servers
  that're hosting the authoritative zone for this domain so that I can
  actually use it - adding records for the root of the domain, www,
  mail, etc. So, I put the name servers in the registration to delegate
  to them - those are always names, so we'll put in ns1.example.com and
  ns2.example.com.
There's the trick. The TLD's servers will delegate to the DNS servers
  in the whois record - but they're within example.com. They try to find
  ns1.example.com, ask the .com servers, and get referred back to...
  ns1.example.com.
What glue records do is to allow the TLD's servers to send extra
  information in their response to the query for the example.com zone -
  to send the IP address that's configured for the name servers, too.
  It's not authoritative, but it's a pointer to the authoritative
  servers, allowing for the loop to be resolved.


Adding a detail record in a master-detail window view

Question: I'll preface with "Brand new to Cocoa" -- I have a master/detail page on my app:  Students that may have one or several contacts (i.e. parents, relatives, etc).  I have a Student entity and a Contact entity with a relationship field called "contact" in the Student entity and another relationship field called "student" in the Contact entity.  The view has a TableView for the students and a TableView for the contacts with add and delete buttons to add a contact for the student that's highlighted in the table.  There are NSArrayController objects called Students and Contacts to manage the entities.  Students is bound to the File Owner (the NSDocument) ManagedObjectContext and the student name shows up fine in that TableView.  The Contacts array controller Content Set is bound to Students.Selection.Contact (a relationship field in the Students entity.
The Add button is connected to the add: method in the Contacts array controller and the Delete button is bound to the remove: method in the Contact array controller.  Clicking the Add button doesn't do anything -- and no errors on the log, so I'm not sure where the connection is missing.  Any ideas?
Answer: I figured it out -- there was a binding missing :)


Definition of series and their relation to sequences and functions

Question: I'm having some trouble making the connection between infinite series and the underlying sequences that they are summed over and both of their connections to functions. This question is a bit long, but please bear with me.

Wikipedia quote: A series is informally speaking the sum of the terms of an infinite sequence

-

A series is defined as the limit as $n \to \infty$ of it's partial sums $S_n$

My Understanding
If we want to define a series $\sum a_n$, the only way to do it, is to take the limit as $n \to \infty$ of it's partial sums $S_n$.
It's partial sums, being the finite summations from $i = 0$, to $n$ of a base infinite sequence $\{a_n\}_{n=0}^{\infty}$.
This base infinite sequence $\{a_n\}$ is really just a list of the infinite outputs of some function $f$. We can say that there exists a function $f : \mathbb{Z^+} \to \mathbb{R} $ such that $f(n) = a_n$, so essentially what we are really doing when we say ' we are taking the sum of the terms of an infinite sequence' is summing over the integer outputs of the function $f$.
So $\sum a_n$ is really just $\sum f(n)$, where $f : \mathbb{Z^+} \to \mathbb{R} $
It's partial sums $\sum_{i=0}^{n} a_i$, are sums with respect to the base infinite sequence $\{a_n\}_{n=0}^{\infty}$. Now if we think of this in terms of functions, the partial sum would be the sum of integer outputs of the function $f$ over an interval $[0, n]$, whereas the series would the sum of integer outputs of the function $f$ on the interval $[0, \infty)$
Partial Sum : $$\sum_{i \ \in \ [0, n]} f(n)  \ \ \text{where}\  f : \mathbb{Z^+} \to \mathbb{R}$$
Series : $$\sum_{i \ \in \ [0, \infty)} f(n) \ \ \text{where}\  f : \mathbb{Z^+} \to \mathbb{R}$$
Now, the partial sums then in turn, form a finite sequence, $S_0, S_1, ... S_n$, which can be expressed as $\{S_n\}_{i=1}^{n}$.
If we had to write it out $\{S_n\} = \{a_0, (a_0 + a_1),  (a_0 + a_1 + a_2), ... , (a_0 + a_1 +a_2 + ... + a_n)\}$
This sequence created by the partial sums is again really just a list of finite outputs of another function $g$. Again we can say that there exists a function $g : \mathbb{Z^+} \to \mathbb{R} $ such that $g(n) = S_n$. But $g$ is different from $f$ in that $g$ is a function whose outputs give the partial sums $S_n$, whereas the outputs of $f$ give the elements of the original sequence. And as it turns out $g$ is of more importance conceptually than $f$, because we determine convergence/divergence of $\sum f(n)$ from $g$.
Now by taking the limit of our sequence of partial sums, which is taking the limit of our function $g$ as $n \to \infty$, what we are doing is finding the value the function $g$ (the sums of our original base sequence $\{a_n\}$) converges towards (assuming the limit exists), and from that we can determine the sum of our series.
Essentially to make the jump from a finite sum to a series (from a finite sum to an an infinite one), all we do is evaluate a set of finite sums of increasing length with respect to a base infinite sequence (which is really just a function) and see if it tends towards some finite value (converges) (or not -diverges)
If the limit exists and is finite, we say the series converges, and the value of the limit is the value of the series, and if the limit is infinite or doesn't exist, then we say the series diverges, and the value of the series is $+\infty$ or $-\infty$
Everything I've said above can be compactly written below as follows:
$$\begin{align}
\sum_{n=0}^{\infty}a_n &\stackrel{\text{def}}{=} \lim_{n \ \to \infty} S_n \\
&= \lim_{n \ \to \ \infty} \underbrace{\sum_{i=0}^{n} a_i}_\text{Partial Sum} \\ \\
&= \underbrace{\lim_{n \to \infty} \left\{\gamma  n \right \}_{i=0}^{n}}_\text{* (1)} \\ \\
&\text{And since} \ \exists \ g : \mathbb{Z^+} \to \mathbb{R} \ni g : n \mapsto \gamma n \\ \\
&= \lim_{n \ \to \ \infty} \gamma n
\end{align}$$
Note: In $*(1)$, $\gamma n$ denotes a closed form expression of $\sum_{i=0}^{n} a_i$ (the partial sum). In this step we take the limit of the sequence of partial sums, which is as I mentioned above is essentially taking the limit of $g(n)$ as $n \to \infty$

Firstly if there is anything you spot wrong with my understanding of sequences and series, please inform me, as there is nothing I want more than to rectify misconceptions I might have.
Secondly from the point of view of analysis is my reasoning and understanding backwards or circular?
Is it fine for me to interpret sequences and series as I've done, are sequences really just the list of function outputs in disguise or are they a whole different beast completely?
I ask this as I've read the following quote :

The two basic concepts of calculus, differentiation and integration, are defined in terms of limits
  (Newton quotients and Riemann sums). In addition to these is a third fundamental limit process:
  infinite series.

And it got me wondering, are sequences and series more fundamental than functions themselves or is it the other way around? Which comes first from the point of view of analysis, sequences and series or functions?
Comment: Something that I forgot to add in this post, which would've made it too long, is that interpreting the sequences and series as I did, as functions, makes the results that the sequence ${\frac{1}{x}}$ converges yet the series $\sum_{i=0}^{\infty}\frac{1}{x}$ diverges extremely explicit as $f$ in my interpretation above can converge and $g$ need not converge.
Answer: You can define a function $f:X\to Y$ from and to any sets $X$ and $Y$, provided only that they are not empty.
As you have said, a sequence of real numbers is a function from $\Bbb N$ to $\Bbb R$. You can define sequences of anything (not only of real numbers), but as a function, the domain of a sequence must be $\Bbb N$, so sequences are particular cases of functions.
To define limits you need a topology. If you don't know what a topology is, the idea is that you need a way to define expressions like "for big enough $n$" or "tends to".
To define series you need a sum and the above mentioned topology. Although you don't need the explicit concept of topology in $\Bbb R$ to compute limits, it's still there.
What I mean is that the functions are very basic objects. Sequences are special functions and series are a complex (i. e., complicated) construct that need a rich structure to be defined.
Nevertheless, it must be noted that in some textbooks about calculus, some elementary functions are defined using series. But elementary functions are a very special kind of functions.
Comment: Thanks for this answer. I felt that the way sequences and series were treated in most introductory calculus (not analysis) courses to be very hand wavy, but what you've said has put some concrete basis for sequences and series .  Thank you for that!


How to check Installation in Mac os

Question: In my mac when I run javac -version command in terminal I get No Java runtime present, requesting install. but when I run which javac command I get /usr/bin/javac.
Do I need to install new jdk? And what should I do with the javac folder which is already present?
Answer: Try javac --version in terminal

How to check Installation in Mac os


Load-balanced Linux server across internet?

Question: I'm investigating setting up a load balanced server solution consisting of three CentOS 5.4 boxes.  Two of these boxes will reside in one facility, while a third will reside in a different facility.
I'm currently working to set up heartbeat, ldirectord, ipvsadm to load-balance the machines, but I'm not sure its going to work with
I'm not overly familiar with the details behind how all of these work, but is the load balancing going to work correctly when these servers are not all on the same LAN?  I'm not sure if heartbeat is using SNMP to send signals or not, which would only work over a LAN.  Has anyone tried this or found a different solution?
Answer: This is a large topic that gets complicated fast.  The CAP theorem is a good starting point, as it identifies the higher level choices that must be made.
When you are dealing with a write heavy Web application, it makes it more difficult to distribute load across the Internet while maintaining data integrity.  Read centric applications (search!) are easier to distribute, as you do not have to concern yourself with the logistics of writing the data.
ipvs allows Linux to essentially become a layer 4 switch.  I have had the most success with using it on layer 2 (ARP/ethernet-- link layer) and that would be my first choice, but it may be feasible to use something like LVS-Tun for geographically separate servers that do not have a connection on the broadcast layer.  Note, ipvsadm is the userland tool for ipvs and ldirectord is a daemon to manage ipvs resources.
heartbeat has effectively been succeeded by pacemaker.  To monitor the other server, it is essential to have multiple links.  The risk of not having a serial or redundant physical connection between the servers is substantially greater.  Even multiple physically distinct Internet connections that heartbeat monitors between the two sites are bound to go down.  This is where the risk of data comes into play, as automatic failover risks data corruption by split brain.  There is no ideal method to mitigate this risk.
You could inject more logic into the failover process.  For example:
If path1 is down, path2 is down, this process is not running, and I can't do this-- then failover.
This reduces the risk but even then still not necessarily to the point of being able to physically connect the servers over a short distance.
With static content, it is easy to employee the use of a Content Distribution Network.
Simple load balancing and failover can be accomplished using Round Robin DNS, which is more fallible.
Border Gateway Protocol is a network protocol that can enable high availability on the network layer.
Ultimately, with enough money (time/resources) an appropriate SLA can be developed to enable a high degree of availability.  Your budget will be your ultimate constraint.  Define your requirements and then see what you can accomplish within your budget, as there will be compromises.
I have often found that it makes more sense, at least in the case of write heavy applications, to enable high availability and automatic failover within the same physical premise.  As part of the disaster recovery plan and SLA to have a manual failover process to a physically separate site, which allows data integrity to be maintained yet still maintains a quality service level.
Comment: This doesn't sound overly difficult to set up, but the MySQL drawbacks for a write-heavy website is troubling. This definitely helps continue my investigation, thanks.
Comment: Take a look at Tungsten Replicator from Continuent.  http://www.continuent.com/community/tungsten-replicator  I've just started using it for master/master (n master) mysql replication.  Well worth a look.
Answer: Having different servers in different locations shouldn't be a problem, until they can reach each other.
The problem would be the bandwidth between them and what you make flow on it.
Heartbeat doesn't use snmp and could be multicast, unicast or broadcast. It's a specific protocol (anyway snmp works between lans sicne it's a udp protocol).
What kind of service are trying to load balance?
Comment: Apache will not be a problem, but load balance mysql is not so easy (bandwidth, clustering mysql is not easy and with some drawbacks)
Comment: We'll definitely be load balancing Apache, but there's a chance we'll be doing MySQL as well (or as a cluster).
Comment: Load balancing MySQL is easy with slave replication and a readonly ipvs VIP.  Writing you typically scale up or out with sharding, which is more complicated.
Comment: Ok, but if you want to load balancing a heavy write mysql server?
That's not so easy.
Answer: Another idea would be some implementation of DRBD with high availability.  Check this site out http://www.drbd.org/home/what-is-drbd/


twig for loop access value using array

Question: i have a for loop
{% for row in rows %}
    {{ row.content }}
{% endfor %}

will print out like this

 one

 two

 three

 ...

but what i want to is access the values using a key so i can pull the values individually so i can do some thing like this

 one

 one

 one

basically print the value anywhere i want on a div of my choice. Is it possible ?? please help
this is for a views template
Comment: Is this for a node template or a view template?
Comment: it is for views template --- it would be great if you can suggest a good book on twig with in-depth explanations and examples... i checked out the the symphony2 site the documentation is too short.. also seems like twig does not support switch statement.
Answer: In views-view.html.twig is not appropriate to style your row and fields.
To style them first you need override template "views_view_'format_style'" (format style specified when you edit/create a view). Here you can style row and access 'fields' variables (use kint(row) to see them).
Something like:
{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}
  {{ kint(row) }} {# devel #}

 {{row.content['#node'].getTitle()}}
 {# access fields #}

    {{ row.content }}

{% endfor %}

For style fields its better override field template.
For example field--node--body--article.html.twig:
{% set mode = element['#view_mode'] %}
{% if label_hidden %}
  {% for item in items %}
    {% if mode == 'full' %}

{{ item.content }}

    {% elseif mode == 'teaser' %}

{{ item.content }}

    {% endif %}
  {% endfor %}
{% else %}

{{ label }}

    {% for item in items %}

{{ item.content }}

    {% endfor %}

{% endif %}

source : In Drupal 8 view.html.twig file how do I access the view content such as individual field title and/or field content?
http://twig.sensiolabs.org/doc/tags/for.html
Answer: The fastest/easiest solution is to click on the field, then click on Re-Write Results
Use the replacement pattern for your field, and put something like this:

 {{ field_name }}

 {{ field_name }}

 {{ field_name }}

Alternatively, you could create a views-view-fields--[view-name]--[machine-name].html.twig file and put the same code there.

If your field in question, has unlimited values:

Click in your field and under Multiple field settings, uncheck the Display all values in the same row box.

its a views page with three fields... // 2 image and a text -- all of this needs to me printed on the same div..

Then in your template file put:

{{ fields.field_company_color_scheme.content }}
{{ fields.field_port_landing_feature.content }}
{{ fields.field_com.content }}

Comment: lets say the for loop has 7 element in it --- say "One" "two" "three" and so on... now if i were to called the field_name seven times how will the iteration work... will it cycle on its own and print the next content ? I can call the field_name had been for something like node/page for a content...
Comment: @TheNagaTanker, There is no need to for loop with my answer. Think of it as rows, `one` would be row 1, `two` would be row 2, etc...
Comment: its a views page with three fields... // 2 image and a text -- all of this needs to me printed on the same div..
Comment: @TheNagaTanker see updated answer.
Comment: these are the fields

field_company_color_scheme
field_port_landing_feature
field_com
Comment: Use the code given in the "Replacement Patterns"
Comment: sorry for keeping the questions coming -- appreciate your help...

i made the views page as html--portfolio-landing-views.html.twig

    {{ field_company_color_scheme }}
    {{ field_port_landing_feature }}
    {{ field_com }}

nothing is being displayed
Comment: @TheNagaTanker you need to name it as I mentioned in my original answer `views-view-fields--[view-name]--[machine-name].html.twig` and clear/flush the cache to see changes.
Comment: thank you so much... however its still not working have done exactly as you've said...
Comment: @TheNagaTanker lets assume [this is your machine name](http://i.stack.imgur.com/vsMjX.jpg) and your view name is "Hello World". Then your template name should be `views-view-fields--hello-world--block-1.html.twig` This template file needs to be inside your current theme's template folder. **Note:** The view preview will not show the changes since it uses the `Seven (admin) theme`. Unless you put the file in Seven's theme template folder, it will not show/reflect in the preview.
Comment: thank you for your valuable time you have spent to help me..
I did exactly as you said....

views-view-fields--portfolio-viadesign--page-1.html.twig is the template i created as you said. Also added a random text with the fields div... I do see that for every div section there are three iterations printing the text 3 time... however the pictures and the text associated with the fields do show up. By the way this is a views page.
Comment: @TheNagaTanker updated my answer, since you are using the template way, then you need to print them like this `{{ fields.field_name.content }}`
Comment: ive tried that too...nothing is printed out
Comment: thanks for the reply ... however each field is being iterated  twice so {{ fields.field_name.content }} will display two content in its index ( lets assume [0] [1]... if i add the second {{ fields.field_name.content }} statement it does not move to the next index [2] [3] but prints the content of [0] [1]
Comment: can we do something like this {{ products.0 }} / {{ products[0] }} / {{ products[random(5)] }}
Answer: SO this is what i've come up with
so instead of using
{% for row in rows %}
    {{ row.content }}
{% endfor %}

what i did was completely remove the for loop and used this instead

 {{ rows[0] . content}}

 {{ rows[1] . content}}

 {{ rows[2] . content}}

 {{ rows[3] . content}}

this way i can also control how many items are displayed and give a div name of your choice or within another div.
now the question remains on how to take apart the
  {{ rows[0] . content}}

the array within the {{ content }} part so they can be further broken apart... any Idea ???

twig for loop access value using array


How is 2nd and 3rd species in 4 part supposed to look like? How do I do it?

Question:

If second species is the 1st pic (the one with half notes) and 3rd species is the 2nd pic, how do i do that in 4 part writing? Like both...combined? "2nd and 3rd species in 4 parts". Im not sure how to do that
Answer: In Gradus ad Parnassum the three- or four-part examples for 2nd through 4th species show one line performing the half-notes or the "active" part of the species, and the other voices all use whole notes, e.g. something like:

The "active" line could be moved to any part, or you could also try writing multiple voices with the active line, which is where florid counterpoint gets to, eventually. Or, you could alternate where the active part is, so maybe the tenor moves in quarter notes one measure, then switches to whole notes while some other voice moves in quarter notes. (Unless, of course, your instructor is looking for something specific, in which case you probably should do that.)
Answer: The best answer is a long and painful one...
Don't give up until you can do all of them at once.  For four parts, for example,  you'll have your CF in whole notes, one voice in half notes, one voice in quarters, and one in suspensions.  It's maddeningly difficult at first but if you persevere writing florid counterpoint in 4 parts will be a breeze.
Fux will do little to help you, though.  Check out Jeppesen's book on counterpoint instead.   You'll have to get good at movable clef though...


With nginx, how to restrict access to proxied TCP resources per preread hostname or upstream?

Question: The nginx docs and guides show that you can perform ip-based whitelisting/blacklisting inside a stream block.
However, I cannot find out how to allow/deny connections based on ip, for only certain hostnames that are read using ssl preread.
Situation
I have a nginx box that is proxying for many services on a private network. Some of these services should be exposed outside the network, while some should not. This nginx box is proxying both internal and external connections.
# TCP proxying with SSL passthrough & vhosts
stream {
        map $ssl_preread_server_name $name {
            public.example.com      public;
            private.example.com     private;
            default                 default_upstream;
        }

        upstream public {
                server 10.0.0.2:443;
        }

        upstream private {
                server 10.0.0.3:443;
        }

        upstream default_upstream {
                server 10.0.0.4:443;
        }

        server {
                listen      443;
                proxy_pass  $name;
                ssl_preread on;
        }
}

How can I apply ip based blocking to only connections headed for private.example.com?
Answer: I found one simple way how to solve your issue. You should use additional server block to filter IPs. So, your config should looks like this one:
# TCP proxying with SSL passthrough & vhosts
stream {
        map $ssl_preread_server_name $name {
            public.example.com      public;
            private.example.com     private;
            default                 default_upstream;
        }

        upstream public {
                server 10.0.0.2:443;
        }

        upstream private {
                #server 10.0.0.3:443;
                server 127.0.0.1:444;
        }

        upstream default_upstream {
                server 10.0.0.4:443;
        }

        server {
                listen      444;
                proxy_pass  10.0.0.3:443;
                ssl_preread on;
                deny  192.168.1.1;
                allow 192.168.1.0/24;
                allow 10.1.1.0/16;
                deny  all;
        }

        server {
                listen      443;
                proxy_pass  $name;
                ssl_preread on;
        }
}

Comment: @AlexD is right. The 2nd server block gets all its connections from 127.0.0.1 so this does not work: `access forbidden by rule while initializing session, client: 127.0.0.1, server: 0.0.0.0:442`
Comment: @Casey you're right. Looks like something wrong in my config.
Comment: I have suspicion that server block listening on the port 444 will get all its connections from 127.0.0.1, so deny/allow directives will be useless.
Comment: Our application stays under nginx as proxy and it logs all requests with real IP addresses. So you could be wrong. Check it.
Comment: Interesting solution, will try it out.
Answer: Try with the below code block.
Tested and working just fine. Telnet on port 443 will successfully establish but on checking through a web browser you'll notice the connection is being closed for unwanted clients.
upstream poolwithlocalhostmemberonport_444 {
           server 127.0.0.1:444;
        }
upstream poolwithlocalhostmemberonport_442 {
           server 127.0.0.1:442;
        }

ssl_preread on;
map $ssl_preread_server_name $name {
            host1.com    poolwithlocalhostmemberonport_444;
            host2.com    poolwithlocalhostmemberonport_444;
            default      poolwithlocalhostmemberonport_442;
}

server {
        listen yourfloatingip:443;

        access_log /var/log/nginxsomething.access.log customstreamlogformat;
        error_log /var/log/nginx/something.error.log;

        proxy_protocol on;
        proxy_pass $name;
}

server {
        listen 127.0.0.1:444 proxy_protocol;

        set_real_ip_from 127.0.0.1; #will swap 127.0.0.1 as client addr with $proxy_protocol_addr content

        allow 10.0.0.0/8;
        allow 127.0.0.1;
        allow 126.96.36.199;
        deny  all;

        access_log /var/log/nginx/stream-access-internalfiltered.log customstreamlogformat;
        error_log /var/log/nginx/stream-error-internalfiltered.log;

        proxy_pass yournextupstream;
}

server {
        listen 127.0.0.1:442 proxy_protocol;

        set_real_ip_from 127.0.0.1;

        access_log /var/log/nginx/stream-access-unfiltered.log customstreamlogformat;
        error_log /var/log/nginx/stream-error-unfiltered.log;

        proxy_pass yournextupstream;
}


How to find all rectangular shaped tiles in an image?

Question: I want to detect and isolate (get sub-images) of all Rummikub tiles in an image. This is the image of Rummikub tiles:

I tried to find the contours of the tiles in an edged image. However, I could not manage to find all the contours of all the tiles.
This is what I got so far:
import matplotlib.pyplot as plt
from skimage.color import rgb2gray
import cv2
import imutils
from imutils import contours

# Load image
img = cv2.imread('RK1.jpg',3)

# Converting the image to grayscale.
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Smoothing without removing edges.
gray_filtered = cv2.bilateralFilter(gray, 6, 400, 400)

# Applying the canny filter
edges_filtered = cv2.Canny(gray_filtered, 50, 30)

# find contours in the edged image
contours= cv2.findContours(edges_filtered, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = imutils.grab_contours(contours)

# loop over our contours
for contour in contours:
    # approximate the contour
    peri = cv2.arcLength(contour, True)
    approx = cv2.approxPolyDP(contour, 0.015 * peri, True)

    # if our approximated contour has four points, then draw contour
    if len(approx) == 4:
        cv2.drawContours(img, [approx], -1, (0, 255, 0), 3)

This is the result:
Result of rectangle detection
I would very much appreciate suggestions on how to reliably find all the contours of all the tiles.
Answer: Here's a simple method

Convert image to grayscale and Gaussian blur
Adaptive threshold
Dilate to form single contours
Find contours and filter using aspect ratio and contour area
Extract ROI using Numpy slicing and save ROI

Detected objects

Here's each individually saved ROI

Code
import cv2

image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3,3), 0)
thresh = cv2.adaptiveThreshold(blur,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV,9,3)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
dilate = cv2.dilate(thresh, kernel, iterations=1)

cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]

ROI_number = 0
for c in cnts:
    area = cv2.contourArea(c)
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.05 * peri, True)
    if len(approx) == 4 and area > 1000:
        x,y,w,h = cv2.boundingRect(approx)
        ROI = image[y:y+h, x:x+w]
        cv2.imwrite('ROI_{}.png'.format(ROI_number), ROI)
        ROI_number += 1

cv2.imshow('thresh', thresh)
cv2.imshow('dilate', dilate)
cv2.waitKey()

Comment: Great, this is exactly what I wanted. Thank you!


Como adicionar reference no visual studio

Question: Na empresa temos um problema com algumas references doprojeto, pois as mesmas estão em pastas diferentes nas máquinas de cada programador e normalmente quando se faz check-in e de seguida get latest version, todos ficamos com problemas nas referidas references. E todos temos que as adicionar de novo.
A minha pergunta é se existe alguma possibilidade de alocar essas reference em algum sitio da team foundation server ou no nuget management ou se existe outro tipo de solução para este problema?
Answer: Essas referências são os frameworks corporativos ou bibliotecas que as empresas criam e deixar elas nas máquinas dos desenvolvedores em paths's fixos é a pior maneira de lidar com elas.
Gestão de componentes
Para .Net existe uma solução bastante elegante para componentes server-side: Nuget.
O Nuget é servidor de pacotes, é possível que ele já seja do seu conhecimento, através do site Nuget.org. O interessante é que não é necessário expor os pacotes através do site público, já que é possível ter um repositório privado de pacotes na empresa.
Pode-se começar criando uma pasta na rede com share para os desenvolvedores, e colocar os pacotes lá, com a extensão nupkg. Ou usar uma aplicação servidora, com portal, muito parecido com o site público e até mesmo com features que vão de autenticação até feeds para outros tipos de pacote. O Proget tem uma versão para uso comecial gratuíta e depois versões pagas com as features avançadas. Existem também outros servidores, tipo Myget, etc...
Configurar um repositório Nuget no Visual Studio
Para configurar um servidor nuget, Proget, por exemplo, ou mesmo uma pasta, como feed no Visual Studio, acesse o menu Tools > Options.
Na janela clique no campo Search Options e digite Nuget (1), clique em menu Package Sources (2), clique no botão com o sinal de + (3), dê um nome (4), e no campo Source coloque o endereço do feed (5) e clique em Update (6).
É interessante colocar como primeira opção, então com ele selecionado, clique na seta que aponta para cima (7), assim quando for buscar um pacote, será dado prioridade ao servidor interno de Nuget.

Veja que neste exemplo eu coloquei uma pasta compartilhada na rede, que terá os arquivos .nupkg. Se usar um servidor, o Source deverá ser um endereço de feed RSS.
Comment: Então o melhor que poderei tentar fazer para resolver esta situação será criar uma pasta partilhada pela rede onde se colocará estas bibliotecas externas e todos os developers apontam as referências no projeto para essa pasta?
Comment: Não entenda isso como uma pasta compartilhada, por que quando você cadastra no VS, é como se fosse um feed
E sim, usar Nuget vai ser o melhor que você pode fazer para gesta da componentização na sua aplicação
Comment: É possível criar tipo um repositório no Nuget das minhas libs? Para que desta forma todos possam ir lá buscar as libs e adicionar no projeto.
Comment: Sim a ideia é essa! Cria essa pasta é coloca os seus pacotes Nuget lá
Comment: E criando essa pasta onde a coloco para ficar visível a toda a team, é essa parte que não estou a perceber.
Comment: Complementei a resposta, veja se está claro agora
Comment: A sua resposta está espectacular e me ajudou imenso. Muito Obrigado


Getting the rate of drain from a tank

Question: A tank with a top radius of 1m, a bottom radius of 0.5m and a height of 2m is initially filled with water. Water drains through a square hole of side 3cm in the bottom.
How do I get the rate of drain,
\begin{equation}
\frac{\partial V}{\partial t}
\end{equation}
of the tank?
Answer: Conservation of mass and constant density tells us change in volume in the tank equals change in volume out of tank.
Thinking area times velocity gives you rate of volume change out of tank, by dimensional analysis.
Bernouli s principle says
$\frac{1}{2}v^2=gh$
$v=\sqrt{2gh}$
Area=side length of square hole squared.
Keep in mind h varies with time.
Volume in tank:
$V=\frac{\pi}{3}(h+2)(r_1+\frac{h(r_2-r_1)}{2})^2-\frac{\pi}{3}2r_1^2$
So :
$A\sqrt{2gh}=\frac{dV}{dt}$
Will give you a differential equation in h as function of t.
Insert back into expression for V to get it as function of t. Differentiate to find alternative expression for derivative.

Getting the rate of drain from a tank


Populate and edit seleted country code and flag on details page after creation using jQuery intl-tel-input plugin

Question: I am using intl-tel-input jQuery plugin for phone number fields on new entity creation. Now I have a details form where I can view all entered details for newly created entity. How do I populate selected country code and flag on phone fields there? Also I should be allowed to edit my details on that page(this means we can edit our phone number also). I am using JSF+Primefaces for frontend.
Form where phone input is taken:
<input id="adminPhone" name="adminPhone" type="tel" />
    <h:outputScript>
    $("#adminPhone").intlTelInput({
     initialCountry: "auto",
     geoIpLookup: function(callback) {
     $.get("http://ipinfo.io", function() {}, "jsonp").always(function(resp)
     {
     var countryCode = (resp && resp.country) ? resp.country : "";
     callback(countryCode);
     });
     },
     separateDialCode: true,
     utilsScript: "../resources/js/utils.js"
     });
    </h:outputScript>

Updated backing bean adminPhone property using getRequestParameterMap().get("adminPhone")value
Update/View details form as of now:

Answer: I used two fields to capture and store the country code and admin phone number on entity creation using getRequestParameterMap() in backing bean.
<input id="adminPhone" name="adminPhone" type="tel" />
<input id="adminCountryCode" name="adminCountryCode" type="hidden" />

Backing bean
Map<String, String> requestParams = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
this.selectedEntity.setAdminCountryCode(requestParams.get("adminCountryCode"));
this.selectedEntity.setAdminPhone(requestParams.get("adminPhone"));

Used above stored values to populate it on View details/Edit page using jQuery built-in options provided in plugin (initialCountry and entered phone number).
<input id="adminPhone" name="adminPhone" type="tel"/>
<input id="adminCountryCode" name="adminCountryCode" type="hidden" />
<h:outputScript>
    var adminCodeHidden = $("#adminCountryCode"),
    adminTelInput = $("#adminPhone");
    adminTelInput.attr("value", "#{dashboard.selectedEntity.adminPhone}");
    adminTelInput.intlTelInput({
       initialCountry: "#{dashboard.selectedEntity.adminCountryCode}",
       geoIpLookup: function(callback) {
       $.get("http://ipinfo.io", function() {}, "jsonp").always(function(resp) {
       var countryCode = (resp && resp.country) ? resp.country : "";
       callback(countryCode);
     });
    },
    separateDialCode: true,
    utilsScript: "../resources/js/utils.js"
});
</h:outputScript>


Cohomology with local coefficients and obstruction theory

Question: I'm reading about obstruction theory on Milnor & Stasheff and came across the following claim:
If $p:E(\xi)\rightarrow B$ is a vector bundle over a CW complex $B$ and $V_k(\xi)$ is  the associated Stiefel bundle of $k$-frames then there exists a cross-section over the $(n-k+1)$-skeleton of $B$ if and only if a certain well-defined  primary obstruction class in $$H^{n-k+1}(B;\{\pi_{n-k}V_k(F)\})$$ is zero. Here $\{\pi_{n-k}V_k(F)\}$ is local system of coefficients defined by the bundle of groups with fiber $\pi_{n-k}V_k(p^{-1}(b))$ over $b\in B$.
I'm trying to understand how such a class would be constructed. Here is what I have so far:
Suppose we have a section defined on the $(n-k)$-skeleton $s: B_{n-k}\rightarrow V_k(\xi)$ and I wish to extend it to the $(n-k+1)$-skeleton of $B$. For simplicity, I consider first the case that $B_{n-k+1}$ is obtained from $B_{n-k}$ by attaching a single $(n-k+1)$-cell $D^{n-k+1}$ via the attaching map $\alpha:\partial D^{n-k+1} = S^{n-k}\rightarrow B_{n-k}$. Then $B_{n-k+1}$ is the pushout of the inclusion $\partial D^{n-k+1}\rightarrow D^{n-k+1}$ along the attaching map and so a map $\hat{s}:B_{n-k+1}\rightarrow V_k(\xi)$ extending $s$ exists if and only if the restriction of $s$ to $\partial D^{n-k+1} = S^{n-k}$ can be extended to a map $D^{n-k+1}\rightarrow V_k(\xi)$, that is if $s|_{S^{n-k}}$ is nullhomotopic. So this ties the existence of an extension to the vanishing of an element of $\pi_{n-k}V_k(\xi)$.
My questions at this point are the following:
1) Where does cohomology with local coefficients come into play?
2) If the $(n-k+1)$-skeleton is obtained by adding more than a single cell how do we package all of that information into a single obstruction class?
Answer: I managed to make some progress and have answered my questions.
Since the composite $\partial D^{n-k+1} = S^{n-k}\rightarrow V_k(\xi)\rightarrow B$ is just the attaching map $\alpha$, it must be nullhomotopic and so by the homotopy lifting property we can homotope the original map $S^{n-k}\rightarrow V_k(\xi)$ to lie within a single fiber giving us an element of $\pi_{n-k}V_k(F_{b_0})$ for some $b_0\in B$. Here we implicitly using the fact that $\pi_1V_k(F) = 0$ so as to not have to worry about a choice of basepoint in $F_{b_0}$. So what we have done is found a way to assign to each $(n-k+1)$-cell $e_i^{n-k+1}$ of $B$ an element of $\pi_{n-k}V_k(F_{b_i})$ for some $b_i\in B$. It remains to package all of this information together. If we can canonically identify these groups over any fiber then we are done and this gives us an element of ordinary cohomology $H^{n-k+1}(B,\pi_{n-k}V_k(F))$. However, this occurs if and only if $\pi_1(B)$ acts trivially on the fibers. In general, this will not happen and that is when we obtain an element of cohomology with local coefficients $H^{n-k+1}(B,\{\pi_{n-k}V_k(F)\}$.


Plotting two seaborn graphs in subplots

Question: I need to plot two graphs side by side. Here the column in my dataset which I am interested in.
X
1
53
12
513
135
125
21
54
1231

I did
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
mean = df['X'].mean()

fig, ax =plt.subplots(1,2)
sns.displot(df, x="X", kind="kde", ax=ax[0]) # 1st plot
plt.axvline(mean, color='r', linestyle='--') # this add just a line on the previous plot, corresponding to the mean of X data
sns.boxplot(y="X", data=df, ax=ax[2]) # 2nd plot

but I have this error: IndexError: index 2 is out of bounds for axis 0 with size 2, so the use of subplots is wrong.
Comment: The onus is on you to provide dummy data for a [mcve]. And if the first one has index 0, what index does the second axes have?
Comment: I do not think it was essential, but I just added.
Comment: If it's not essential then remove it from your [mcve] ;)
Comment: Thanks JohanC. I am getting three plots, with lines separated from the kde plot.
Comment: Ok, Andras. I had seen also questions with no sample of data and not indication of the type of data, but just code and upvoted. I had provided information on the data I am using. It was randomly generated. It was to understand how to plot one plot with a separate line in a subplot, since it was ok for me to do it with only two plots (separated). By the way, I added the information on data.
Comment: I would like a density plot. The histplot also plots the bars. I would like just a density line, if possible.
Comment: got the error: ValueError: If using all scalar values, you must pass an index
Comment: yes. It has returned that error: ValueError: If using all scalar values, you must pass an index
Answer: sns.boxplot(..., ax=ax[2]) should use ax=ax[1] as there doesn't exist an ax[2].
sns.displot is a figure-level function, which creates its own figure, and doesn't accept an ax= parameter. If only one subplot is needed, it can be replaced by sns.histplot or sns.kdeplot.
plt.axvline() draws on the "current" ax. You can use ax[0].axvline() to draw on a specific subplot.  See What is the difference between drawing plots using plot, axes or figure in matplotlib?
The following code has been tested with Seaborn 0.11.1:
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

sns.set()
df = pd.DataFrame({'X': [1, 53, 12, 513, 135, 125, 21, 54, 1231]})
mean = df['X'].mean()

fig, ax = plt.subplots(1, 2)
sns.kdeplot(data=df, x="X", ax=ax[0])
ax[0].axvline(mean, color='r', linestyle='--')
sns.boxplot(y="X", data=df, ax=ax[1])
plt.show()

Comment: What is the lowest and highest value? How many values are there?  Can you add the image of the plot with `histplot(..., kde=True)` to the post? Could you add a large sample of your data to the post, preferably one that has the same error? Could you try `sns.kdeplot(x=df["X"].to_numpy(dtype=float), ax=ax[0])`?  This looks like a genuine bug, so it is important to get a preferably simple example at seaborn's github.
Comment: Thanks, JohanC. Unfortunately, as previously mentioned, with my dataset it returns that error. If I plot as distinct charts (kde and box plot), it does not return any error. I cannot understand why I am getting this error. Checking, I think it might be caused by sns.kdeplot
Comment: it works with histplot but not with kdeplot. I have the most updated version, so it is not a problem of version. I am not able to provide more than 10000 of rows ;) (they are all int and I also dropped nan values). It is weird that it is not working only with kdeplot. I also tried as you suggested (with reset_index) but nothing has changed. `sns.kdeplot(data=df.reset_index(drop=True), x="X", ax=ax1)`. Still same error.
Comment: I tried with your last suggestion (`sns.kdeplot(x=df["X"].to_numpy(dtype=float), ax=ax[0])`) and it works! No errors, no warnings :) If you could also include in your answer this last piece of code as alternative, it would be great. thank you so much, JohanC
Comment: I'm really interested in knowing what the problem with your dataframe might be.  This is a very unusual and mysterious error. Converting the dataframe to numpy should never be needed, but can help to pinpoint the real error.  Does it work with `sns.kdeplot(x=df["X"], ax=ax[0])`? And `sns.kdeplot(x=df["X"].to_numpy(), ax=ax[0])` without the `dtype`? Can you print out `pd.__version__` to be sure its `1.2.3`? And `sns.__version__` as `0.11.1`?
Comment: it only worked with `sns.kdeplot(x=df["X"].to_numpy(dtype=float), ax=ax[0])`, not with `sns.kdeplot(x=df["X"], ax=ax[0])`. I can confirm that both versions are the most updated (pandas 1.2.3 and sns 0.11.1) as I had to install both recently.

Plotting two seaborn graphs in subplots


Which should I record first?

Question: So my problem is that I don't know which is recorded first, do you record the orchestra first or do you record the drums or guitar first?
I've tried recording the drums first but it didn't sound right next to the orchestra.
I've also made a list of the things on which we should record first.
I'm not sure if this is the correct order:

Lead Vocal
Backing Vocal
Drums
Guitar
Piano
Orchestra
Comment: Sonically, it should make no difference. Are you working to a click track?
Comment: Depends, I prefer recording one rough thing, recording everything over the rough thing(s) and rerecording the rough things. This question is on unstable ground - Might get closed as "Opinion-Based". Slightly add more Information to the question to make it a not-Opinion-Based-Tone one.
Answer: If it's a rhythm-based song, lay down the rhythm section, drums, bass, enough piano or guitar to enable the lead singer.  Maybe a guide instrumental track of the melody to give the singer something to latch on to.   All these tracks can be replaced later if needed, but get the groove right - everyone else's performance will need to fit with it.    Then the lead vocal.   Then you can start building up the rest of the tracks, supporting the lead but, most importantly, leaving SPACE for the lead.
Everything can be re-done, improved.  But if the underlying beat is set, and everything else takes it into account from the outset, there won't be much 'fixing' to do.   Listen BEFORE you record rather than fixing AFTER.
Answer: All live, I guess? If you can only lay one track down first, drums is good.That sets the tempo (with a good drummer!) Drum breaks can always be overdubbed. Then the rest of the rhythm section - guitar (rhythm) and bass - any order.Assuming the drummer can play to a click track, it's worth including one. If not, and the drummer fluctuates, on what may essentially be a dance track, it may need to be quantised later. It may well help if the others - bass, guitar, vox play along to be heard only in the drummer's cans. It makes life easier for the drummer to have that to play along to, rather than just play in isolation.
That all gives the piano, orchestra and vocals something to latch onto.
Bear in mind that any rough bits can be overdubbed at a later stage, and it rather depends what the 'orchestra' is adding to the piece.If the piece is supposed to go out of time, then it's pretty important for the drumer to hear the others.

Which should I record first?


A Challenge on linear functional and bounding property

Question: I took a midterm exam and after that wrote this problem down.  My instructor was unable to solve it.
The problem is copied here in order for anyone to help me.

Suppose $f:E\to \mathbb{C}$ is a linear functional such that $\exists M \gt 0$ with the following property:
$$ \forall x \in E \;\; |f(x)| \le M||x|| $$
Show that $f$ is bounded.
Comment: Recall that in this case "bounded" means "continuous".
Comment: Your post would be easier to read if you used MathJax/LaTex formatting. A [homegrown tutorial](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) will get you started. A [quick overview](http://meta.math.stackexchange.com/questions/107/faq-for-math-stackexchange/117#117) may be helpful.
Comment: Thanks @hardmath, in this case would you please change it for me?
Comment: Ah okay, that's what I get for not reading "function-AL." My bad.
Comment: The property in the question is exactly the definition of boundedness. So you have to show that $f$ is bounded if it is bounded.
Answer: A bounded linear functional is just a special case of bounded linear operator, one for which the codomain is the field of scalars.  A linear mapping $f:E\to V$ between normed vector spaces is a bounded linear operator iff:
$$ \exists M \gt 0 \text{ s.t. } \forall x \in E \;\; ||f(x)||_V \le M||x||_E $$
The property given by this Question is then the very definition of a bounded linear operator, at least if we are assuming $f$ is a complex linear functional and complex vector space $E$ has the indicated norm $||\cdot ||$.
To prove that a bounded linear operator is continuous as a mapping of topological vector spaces, we need to show that for any open set $\mathscr{O}$ containing $f(x)$, there exists an open set $\mathscr{U}$ containing $x$ s.t. $f(\mathscr{U}) \subseteq \mathscr{O}$.
By the linearity of $f$ it suffices to carry out the argument for an open neighborhood of $f(0)=0$ in $V$, first translating $\mathscr{O}$ to an open neighborhood of the origin $\mathscr{O} - \{f(x)\}$ in $V$, and finally translating the open neighborhood of the origin in $E$ to an open set containing $x$ by adding $x$.
For normed vectors spaces $E,V$ this is precisely what the inequality involving positive (real) constant $M$ allows us to show.  Namely if $\mathscr{O}$ is a open set containing the origin in $V$, then there must be an $\epsilon \gt 0$ such that the $\epsilon$-ball around the origin is contained in $\mathscr{O}$:
$$ \forall y \in V \; (\; ||y||_V \lt \epsilon \implies y \in \mathscr{O} \;) $$
Setting $\delta = \epsilon/M$ we define $\mathscr{U}$ to be the $\delta$-ball around the origin in $E$:
$$ \mathscr{U} = \{ x \in E : ||x||_E \lt \delta \} $$
Now if $x \in \mathscr{U}$, we have by the inequality involving $M$:
$$ ||f(x)||_V \le M ||x||_E \lt M \cdot \delta \le \epsilon $$
Thus $f(\mathscr{U}) \subseteq \mathscr{O} $, as required to prove continuity.
Comment: Dear @Hardmath, i need more detail :)
Comment: @MichleJordan: Please have at least a quick look at the link I gave to defining "bounded linear operator".  Were you given a different definition?  Did I misinterpret what you mean by "linear functional" $f:E\to \mathbb{C}$?
Comment: i can say, i dont know...
Comment: @hardmath Presumably, "bounded" means "continuous" in the topological sense.
Comment: @DavidMitra: I've added a sketch of the proof that a bounded linear operator is continuous as a topological map, but I suspect this distinction will be difficult for the original poster to evaluate.


How to Create 2D array in javascript with json data

Question: I am using asp.net mvc framework and i have json data which i want to in 2d array.
Here is my data.
Json data(Input data)
var data=[{"ID":1,"Min":80,"Max":175},{"ID":2,"Min":90,"Max":240},{"ID":3,"Min":90,"Max":215},{"ID":4,"Min":50,"Max":120},{"ID":5,"Min":70,"Max":190},{"ID":6,"Min":50,"Max":120},{"ID":7,"Min":70,"Max":140},{"ID":8,"Min":80,"Max":160}];

I need to get Min and Max values from Json data.
Required output:
data=[[80,175],[90,240],[90,215],[50,120],[70,190],[50,120],[70,140],[80,160]]

Waiting for your response
Comment: Just a note, there are some SO Elite's, that will hammer you down for saying that's JSON data.  It's not, it's a javascript object, if you left out the `var data=` and the trailing `;`, then I would say it's JSON. :)
Comment: [json](http://json.org/) is a string. always.
Comment: Indeed, take out the bits I just said, and it's a string.
Comment: @PrateekJairath Could you please respond to the answers below? Thanks!
Answer: You can do this with map()

var data=[{"ID":1,"Min":80,"Max":175},{"ID":2,"Min":90,"Max":240},{"ID":3,"Min":90,"Max":215},{"ID":4,"Min":50,"Max":120},{"ID":5,"Min":70,"Max":190},{"ID":6,"Min":50,"Max":120},{"ID":7,"Min":70,"Max":140},{"ID":8,"Min":80,"Max":160}];

var result = data.map(function(e) {
  return [e.Min, e.Max];
})

console.log(result)
Answer: you can use map  (http://api.jquery.com/jquery.map/ )
var o = {"0":"1","1":"2","2":"3","3":"4"};

var arr = Object.keys(o).map(function(k) { return o[k] });

console.log(arr)

here an example on fiddle http://jsfiddle.net/8TT4p/67/
Answer: var data=[{"ID":1,"Min":80,"Max":175},{"ID":2,"Min":90,"Max":240},{"ID":3,"Min":90,"Max":215},{"ID":4,"Min":50,"Max":120},{"ID":5,"Min":70,"Max":190},{"ID":6,"Min":50,"Max":120},{"ID":7,"Min":70,"Max":140},{"ID":8,"Min":80,"Max":160}];

var data1 = [];
for(var i=0;i<data.length;i++){
  var temp = [];
  temp.push(data[i].Min);
  temp.push(data[i].Max);
  data1.push(temp);
}

Now data1 is your required array.
Answer: Another solution using Array.prototype.reduce to create the resulting array of arrays:

var data=[{"ID":1,"Min":80,"Max":175},{"ID":2,"Min":90,"Max":240},{"ID":3,"Min":90,"Max":215},{"ID":4,"Min":50,"Max":120},{"ID":5,"Min":70,"Max":190},{"ID":6,"Min":50,"Max":120},{"ID":7,"Min":70,"Max":140},{"ID":8,"Min":80,"Max":160}];

var result = data.reduce(function(prev, curr) {
  prev.push([curr.Min, curr.Max]);
  return prev;
}, []);

console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}


Finding string between custom tags and doing something with it

Question: On my new project, members are able to use my YouTube API and it will generate a tag like below for them to use it in whatever textarea they want:
<ymedia>http://www.youtube-nocookie.com/v/qQG0XfU-bFs</ymedia>

I want my PHP profile page to take the string between <ymedia></ymedia> and generate a similar code below using $ymstring for the string collected from the ymedia tag:
<?php
$u_agent = $_SERVER[''HTTP_USER_AGENT''];
if(preg_match(''/Opera/i'',$u_agent)){
<object width="320" height="240" data="".$ymstring."?fs=1&hl=en_US&rel=0"><param name="movie" value="".$ymstring."?fs=1&hl=en_US&rel=0" /><param name="allowFullScreen" value="true" /><param name="wmode" value="transparent" /><param name="bgColor" value="#ffffff" /><param name="flashvars" value="vu=".$ymstring."?fs=1&hl=en_US&rel=0" /></object>
} else {
<object width="320" height="240"><param name="movie" value="".$ymstring."?fs=1&hl=en_US&rel=0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="".$ymstring."?fs=1&hl=en_US&rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="320" height="240"></embed></object>
}
?>

Basically, I'm trying to find all the ymedia tags in a $string and replace them with my youtube coding above aimed at either Opera or the rest of other browsers.
Comment: What are you having problems with/what is the question?
Comment: I'm trying to find all the ymedia tags and replace them with my youtube coding above aimed at either Opera or the rest of other browsers.
Answer: This should work:
    preg_match("/<ymedia>(.*?)<\/ymedia>/", $Input, $Matches);
Then, your result would be in $Matches[1] which you could pass as $ymstring.
Comment: Will this do this for every ymedia tag found and keep it in it's relative html position?
Answer: You want to use preg_replace_callback for simplicity:
$html = preg_replace_callback('#<ymedia>(http://.*?)</ymedia>#',
         "ymedia_cb", $html);

function ymedia_cb($matches) {
    $url = $matches[1];

    return "<object src=$url>";
}

Obviously you would use your if/else construct to return the appropriate and complete object tag.


dynamic image / captcha image over load-balanced servers

Question: i have two servers which are load balanced in such a a way that each page request will be served from any one of the servers.
And in the project i am creating captcha images which will be created on any of the server which serves the page, and while loading it in browser ( img src) the call goes to other server because of the load balance implementation.
is there any workaround for this issue.
Answer: I am not sure whether this is the best solution.
i fixed the issue by reading up the captcha image as BLOB using file_get_contents function soon after the creating the image, and printed the image as BLOB image over HTML img src tag. so that no http request for image is send to the server.
The problem got solved for me.


What is the minimum number of guesses in order to guarantee to win the prize?

Question: Your friend will pick a $4$-letter word and you will make guesses in order to find it.
-A word can contain only the letters $A, B, C,\:\text {and} \:D$, and they can be used more than once. $(AAAA-DDDD)$.
-In your guess if at least three letters are in their correct places you will win a prize.
What is the minimum number of guesses in order to guarantee to win the prize?
Comment: An upper bound is $64$ since there are $64$ combinations for the first three letters, and you can run through these in $64$ tries, with the fourth letter of each guess being arbitrary.
Comment: Hint:  count the number of winning guesses, $W$, count the total number of guesses, $T$. The minimum is $T-W+1$
Comment: You shouldn't ever have to go through all the wrong guesses.  For instance if you guess ABCD as your first guess and its wrong, you can eliminate ABC?, AB?D, A?CD, and ?BCD words.
Comment: A lower bound is 20, since each of your guesses rule out 13 combinations (itself, and the $3\times 4$ ways of changing one of the four letters). There are 256 possibilities in total, so since $19\times 13<256$, 19 guesses cannot rule out all possibilities. Unfortunately, this is still far from the upper bound above.
Comment: I wondering whether this can be reduced to a domination number of some graph... Consider a graph where every vertex represents a possible 4 letter code.  Now let two vertices be adjacent if their 2 codes differ by exactly 1 spot.  Then, indeed, a dominating set would be a set of guesses where you are guaranteed success.
Comment: @lulu, It's for my clarification. How could you tell that this will be minimum.Because one can guess the correctly, before all wrong guesses. So, it will be smaller then your answer.
Comment: @SubhadeepDey   True!  But the OP said "guaranteed".  Let's say (inaccurately) that there are $100$ guesses, $40$ of which are correct.  If your luck is truly awful, you could guess $60$ times without every once being correct.  Granted that is improbable, but the OP did not ask about probability.
Comment: @paw88789, $ABCD$ is not wrong. OP says "at least" , not "at most".
Comment: @paw88789 Agreed.  I was thinking of blind guesses, as in random draws from an urn.
Comment: The question with strategy seems interesting.  Hard to see how to guarantee "mixing up" the triples in your guesses.  To be clear:  my comment referred only to blind guessing (no strategy) but I agree with the other commenters that this is not what the OP intended.
Comment: This question makes sense only if some probability/average number of guesses is involved. Otherwise min is 1.
Comment: @user264781: there are $16$ favorable combinations, as you only have to guess 3 letters correctly. So the lower bound is $19 = \operatorname{ceil}((256 - 16) / 13)$.
Comment: @user251257: what do you mean by favourable combination?
Comment: @user264781: if the complete correct answer is $ABCD$, then you win with any one of the guesses $?BCD$ (4 combinations), $A?CD$, $AB?D$, $ABC?$.
Comment: @user251257: you are double counting: ABCD is included in all four of those sets, you've forgotten to adjust for that.
Comment: @user264781: Oh right. Still $\operatorname{ceil}((256 - 13) / 13) = 19$. Anyway, I don't think this lower bound is realistic, as you don't known which 13 combinations (apart 1 of them) you can discard.
Comment: This question is from an ongoing competition: http://www.puzzleup.com/2015. Please see the math.SE policy on ongoing contest questions: http://meta.math.stackexchange.com/questions/16774/contest-problem-policy.
Answer: You are looking for the covering code number $K_4(4,1)$. Finding such numbers are very hard problems in general.
This particular one can be found in this paper, and it is equal to 24.
The covering table is also given, I reproduce it here:
AAAA
AABB
ABAB
ABBA
ACCC
ADDD
CACD
CCDA
CDAC
DDCA
DADC
DCAD
BAAB
BABA
BBAA
BBBB
BCCC
BDDD
CBCD
CCDB
CDBC
DDCB
DBDC
DCBD
Reference: Covering theorems for vectors with special reference to the case of four and five components.
R. G. Stanton, J. D. Horton and J. G. Kalbfleisch
Comment: This question is from an ongoing competition: http://www.puzzleup.com/2015. I've flagged it for moderator attention; you might want to delete your answer before the moderators get around to it. (Here's the math.SE policy on ongoing contest questions: http://meta.math.stackexchange.com/questions/16774/contest-problem-policy.)


Proxy settings in Java

Question: Googled and find few links about proxy settings in Java, but few things make me a little confused
1) Do we really need to set the proxySet property or not?
System.getProperties().put( "proxySet", "true" );
System.getProperties().put( "proxyHost", "proxy host" );
System.getProperties().put( "proxyPort", "8080" );

2) What's difference between setting http.proxyHost and proxyHost? basically, does it mean that the "proxyHost" one will be applied to all protocols including http, https, ftp, etc, whereas http.proxyHost only applies to http protocol?
System.getProperties().put( "proxyHost", "proxy host" );

or
System.getProperties().put( "http.proxyHost", "proxy host" );

3) Do we always need to do afterwards?
System.getProperties().put( "proxySet", "false" );
System.getProperties().put( "proxyHost", "" );
System.getProperties().put( "proxyPort", "" );

4) Where is the detailed and official documentation about doing proxy settings in Java?
Comment: http://docs.oracle.com/javase/6/docs/technotes/guides/net/proxies.html Java Networking and Proxies Documentation.
Comment: Yep, I used it as reference earlier. But it doesn't answer the first 3 questions above.
Answer:
No. There is no such property as proxySet. It was a feature of the long-defunct HotJava bean in 1997, and from there it has leaked into various 3rd-party books. There has never been such a property in the JDK, and I've looked at all of them since 1.1.2. For proof, set the other two and set proxySet to false and see what happens. NB this question is indeed answered by the documentation, as proxySet does not appear there.
(a) None, except that you shouldn't use proxyHost/Port because they are obsolete. (b) The documentation doesn't say so.
See (1) for proxySet. It would be more to the point to set the others to null rather than "" but I don't believe it has any effect: once the properties have been loaded they stick. If you need to control proxying dynamically you need to use java.net.Proxy.
This has been answered in @tostao's comment.

Proxy settings in Java


How to replace the values in a pandas dataframe with values looked up from a dictionary?

Question: I have a 2 dimensional dataframe, swap_dates, which looks as follows:

I also have a dataframe, proj_zcb, with a single column which looks like this:

I'm hoping to replace the dates in the first dataframe with the respective values from the second dataframe (or, equivalently, dictionary).
I have tried using pandas' replace function;
swap_dates.replace(proj_zcb.to_dict())

but for some reason this does not seem to work;

Can anyone see why this might not be working or, alternatively, suggest an approach that works?
Comment: Please don't use an image as a sample code. See: https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question
Answer: It turns out that the reason that the code
swap_dates.replace(proj_zcb.to_dict())

did not work is because proj_zcb.to_dict() returns a dictionary of dictionaries (i.e. a dictionary whose keys are the column names of proj_zcb and whose elements are dictionaries created from those columns).
The following code worked as hoped:
swap_dates.replace(proj_zcb.to_dict()['Proj ZCB'])

Answer: The replace function works on lists and dicts. So as long as you follow this it should be fine. (The only issue might be dates).
for lists:
import pandas as pd

df = pd.DataFrame({'A': [0, 1, 2, 3, 4],
                   'B': [5, 6, 7, 8, 9],
                   'C': ['a', 'b', 'c', 'd', 'e']})

print(df)
df.replace([0, 1, 2, 3], [4, 3, 2, 1])

print(df)

for dicts:
import pandas as pd

df = pd.DataFrame({'A': [0, 1, 2, 3, 4],
                   'B': [5, 6, 7, 8, 9],
                   'C': ['a', 'b', 'c', 'd', 'e']})

print(df)

# replace
df_new = df.replace({'A': 0, 'B': 5}, 100)

print(df_new)

Your question is of type dict.


Adding Regressors to Convolutional Neural Network

Question: I have an idea for working with geospatial rasters to predict housing prices.  I have done this before using mulitivariate linear regression.  I would like to try using a convolutional neural network.  I have a series of rasters that represent a surface of interpolated housing prices over time.  The convolutional neural network will learn from the price rasters, but I need to add in other explanatory variables. The most important is time.  I might add additional scalar values such as interest rate or stock market.  I might also want to add additional rasters as regressors, such as crime maps, or distance to transit.  I know that in a typical neural network regression there is one neuron per explanatory variable, and in a typical CNN there is a neuron per pixel on the input layer.  So I would like some regressors to be rasters, and some to be scalers.
My question is how do I add additional explanatory variables, both rasters and scalars, to a convolutional neural network?  I am using Keras and TensorFlow.
Answer: It seems like you could do this relatively easily using a model that has MLP and CNN parts.
Suppose that your time-series data is $A$. You compute some CNN output $c(A)$ that uses $A$ as the input; this can return a vector since you have, say, $i$ units in the final layer of this portion.
Suppose that your "tabular" data is $B$. You compute some MLP that has output $m(B)$; this can return a vector since you have, say, $j$ nodes in the final layer of this MLP.
Now you have two vectors which, in some sense, encode the data contained in the tabular and CNN components of your data. You can concatenate these vectors to make a new vector of length $i+j=k$. This is the input to another fully-connected layer in your network, or possibly more than one. Then the output is just whatever your usual output is.
The reason that I think this could work is that you process the CNN and tabular pieces with models which are appropriate for their respective types, and then combine the results in a way which permits both formats to be used together.
But this could be hard to train. This would not be my first choice of a model. Instead, I would prefer to try using either a tabular or a CNN model by itself, and making a determination of whether or not either simpler model is suitable.
Note that this structure trains all parts of the network, the MLP, the CNN and the "combiner" part, all at once. This does not require you to train three separate networks.
This is easy enough to do in most modern neural network software, such as Keras.


Técnicas para manter consistência dos dados no front-end

Question: Exemplo: Em um formulário, alguns campos (input) são carregados via ajax a partir de um select. A option selecionada será usada no back-end para validação desses campos.
Entretanto, o usuário pode carregar uma determinada opção, preencher seus campos e, intencionalmente, alterar o valor (no browser) da tag option selecionada para um outro valor válido, por exemplo, e encaminhar para o servidor.
Como garantir a consistência dos dados vindo de um formulário HTML? Quais técnicas/métodos são essenciais?

Compreendo que isso pode ser tratado com determinadas condições no back-end. Minha busca é por quais são as melhores práticas. Por exemplo, penso que para cada option, devo guardar um token identificador em um input[type=hidden], assim poderia checar facilmente se os dados são referentes à opção selecionada.
Comment: Esquece, náo tem nada que pissa garantir dados no cliente http://pt.stackoverflow.com/q/13298/101, http://pt.stackoverflow.com/q/67911/101
Comment: Não está claro para mim quais informações você quer garantir. Sua metodologia também não fala se você deseja tratar ataques de 'bots' ao formulario. Descreva melhor o fluxo de dados entre o get e o post. O que seria essa Option e quando ela é selecionada? É um parametro visivel para o usuário ou é uma variável de controle interna do sistema?
Answer: A forma correta é a que você ja está fazendo, tentando validar diretamente no browser e ainda assim ter uma outra validação no servidor antes de executar os comandos enviados pelo usuário.
Esse tipo de problema não é exclusivo de HTML mas qualquer aplicação que tenha um cliente e um servidor, onde nós fazemos a validação no cliente para evitar conexões desnecessárias com o servidor e ainda assim outra validação no servidor de qualquer dado que for enviado pelo cliente, aí sempre vai haver essa dupla validação.
O que eu fiz e recomendo pra evitar repetição de código foi colocar toda a validação no modelo de dados que era compartilhado entre ambos, então eu poderia chamar Pessoa.Validar que me retornaria true ou false indicando se passou, fora que teria também métodos para pegar listas de erros do objeto validado.


How to disable Apache http compression (mod_deflate) when SSL stream is compressed

Question: I found that Goggle Chrome supports ssl compression and Firefox should support it soon.
I'm trying to configure Apache to to disable http compression if the ssl compression is used to prevent CPU overhead with the configuration option:
SetEnvIf SSL_COMPRESS_METHOD DEFLATE no-gzip

While the custom log (using  %{SSL_COMPRESS_METHOD}x) shows that the ssl layer compression method is DEFLATE, the above option did not work and the http response content is still being compressed by Apache.
I had to use the option:
BrowserMatchNoCase ".*Chrome.*" no-gzip

I prefer if there is more general method in case other browsers support ssl compression in future or someone has a version of Chrome that does not have ssl compression.
Answer: Now after I got more information about the problem, I should answer my own question. This is a reported bug in Apache; Bug 49057 - setenvif should have access to SSL environment variables.
The bug is fixed in Apache 2.4.1 but this is not an option as I'm using CentOS 6.x.
I'll see if I can set no-gzip environment variable through the application instead of the Apache config.