Would requiring .Net 4.0 act as a bar to adopting our software in a corporate environment?

Question: We are developing a software product in .Net targeting large corporations. The product has both server and desktop client components. We anticipate that our product will be used by a small subset of workers in the corporation - probably those in the finance function. We currently require .Net 3.5 but are considering moving to .Net 4.0.
Could anyone with experience of managing IT in such an environment tell us whether requiring .Net 4.0 at this stage would be a bar to adopting our software? What attitudes prevail regarding the use of frameworks like .Net?
Answer: Think of it as a benefit vs. cost function, same as any other business decision.
If there's a cost to installing all the components required to support your software, can you minimise the cost? (e.g. do you just require a server with .net4 on it vs. all the workstations on a network needing it?). This principle also works against requiring the latest version of .net "just because you can", for example.
Can you demonstrate to the decision makers in a company that the benefit of the software will make up for the cost of installing it? It's really that simple.
I'm not going to say anything about .net 4 itself because I don't see that as relevant. Same question, same answer whether you're talking about an app that requires .net 4.0 on a Windows network, Safari 5 on an Apple network or Java on a Linux network.
Answer: Installing any extra software is always a concern for IT departments and network administrators. If your product is useful to a company they will buy and install it, but things like this are barriers you have to overcome by making your software that much better.
If you can, target the lowest version of the .NET framework you can get away with and point out the drawbacks with going to 4. The question becomes do the technical benefits you get from .NET 4 outweigh these drawbacks?
Answer: If it were deployed to all machines, that would certainly be a disincentive.  We currently target the 2.0 runtime for applications that have large installations, and press the envelope on adopting new runtime features (3.x/4.0) for projects that are not widely deployed.
If the server component is not dedicated, and IT would prefer it to run on an existing shared server, that may cause some anxiety.
Answer: In our organization the software we develop has been using the 2.0 framework. I suppose it would depend on the size of the organization. If they're a company of 30 than they may not have a problem with the upgrade. If they're a company of 500 then I would think there would be more resistance. If you need the 4.0 framework than you should write out your reasons. Perhaps you could present it in a way that makes it look very advantageous for them to upgrade (security, performance, features you're taking advantage of, etc).
Answer: Another consideration is the fact that the resistance may not necessarily be due to cost of installation and deployment of the framework but rather managing risk of braking existing mission critical enterprise applications. I am currently in that war at work with infrastructure team and are demanding for me to prove that deploying .net 4.0 framework will not break any existing apps. if anyone knows of such a majical tool that will do that I would be much in debt to you :).
Comment: The magical tool is called a "dev", "test", "qa", or "preprod" environment. Put a copy of the existing app(s) there, put in 4.0 and the new app, and confirm that they all still work. No magic at all.
Answer: From an IT perspective, I don't find it to be that big of a deal on the client side.  Microsoft patches, updates, and components have been decently stable for a few years now and I would think most don't have a problem pushing out .net 4.0.
Also,
What type of customers are they?  Customers that computers are a valued and important part of the business that they treat that way, with upgrades, etc?  If everyone is running Windows 7+ there doesn't seem to be a lot of disadvantages to going to .net 4.0.
I would be more hesitant on the server side, and it depends how your software installs.  Is it pretty large and usually has a dedicated VM, not that big a deal.  Or does it install in a small office where it shares the server with everything else?  Then it's a lot bigger deal because then they are calling you asking why your software broke their website.
To sum up... Look at it from the customers perspective.  Look at the use cases for your software.  And above all, don't be afraid to ask your current customers?


How to loop and extract items from Nested Json Array in Logic Apps

Question: I need to extract each element from nested json array. I am trying to find a way..
Schema:
{
    "id":"1",
    "name":"One",
    "child":[
        {

            "id":"2",
            "name":"two",
            "child":[]
        },
        {
            "id":"3",
            "name":"three",
            "child":[

                {
                    "id":"4",
                    "name":"four",
                    "child":[]
                },
                {
                    "id":"5",
                    "name":"five",
                    "child":[]
                }

                ]
        }

        ]

}

The resultant payload needs to be
{"id":"1","name":"one"},{"id":"2","name":"two"},{"id":"3","name":"three"}
Answer: You might need to write a recursive function. In python, it will look like:
def get_payload(obj):
  ret = [{'id':obj['id'], 'name':obj['name']}]
  for child in obj['child']:
    ret.extend(get_payload(child))

  return ret


Approximating best fit gradients using averages of ratios

Question: If I have a function $y=f(x)\approx ax+b$ where $a,b$ are constants that correlate to a set of $n$ points, could I use the following as an approximation of the gradient?
$$a\approx\frac1n\sum_{i=1}^n\frac{y_i}{x_i}$$
I'm not sure if my question is clear so please ask me if I need to clarify
Comment: No; at the very least you need to subtract off an estimate of $b$ from all the $y_i$ first. The right way to do this whole recipe is linear regression.
Answer: No. If you try to apply linear regression for $n$ distinct points, then you should choose $a,b$ such that$$\sum_{i=1}^{n}(y_i-ax_i-b)^2$$be a minimum. After a simple minimization, $a$ is obtained as follows:$$a={n\sum_{i=1}^n x_iy_i-\sum_{i=1}^n x_i\sum_{i=1}^n y_i\over n\sum_{i=1}^n x_i^2-\left(\sum_{i=1}^n x_i\right)^2}$$therefore$$f'(x)\approx {n\sum_{i=1}^n x_iy_i-\sum_{i=1}^n x_i\sum_{i=1}^n y_i\over n\sum_{i=1}^n x_i^2-\left(\sum_{i=1}^n x_i\right)^2}$$


Two questions about a CW-complex example

Question: Consider the CW-complex structure of X:  Delete the interiors of two disjoint subdiscs in the interior of $D^2$, and then identify all three resulting boundary circles via homeomorphisms preserving clockwise orientation of these circles.
I saw the structure below with boundary of 2-cell:  $aba^{−1}b^{−1}ca^{−1}$, and I am confused:
(1) why do we have the 1-cells b and c?(why can't we just have one 0-cell:x and one 1-cell a and a 2-cell u?) (2) Can I say the boundary is $ababca$? I am stuck on them, can you give me a explanation? Thank you!
Answer: First, it looks to me like you left off the final term in the attaching map of the boundary of the 2-cell: $a b a^{-1} b^{-1} c a^{-1} c^{-1}$.
To get to your questions, you cannot leave out $b$ and $c$ because then $u$ is not homeomorphic to the interior of $D^2$, as is required for a 2-cell. With the 1-cells $b$ and $c$ present, $u$ is indeed homeomorphic to the interior of $D^2$. Remember that in a 2-dimensional CW complex, each component of the complement of the 1-skeleton must be homeomorphic to the interior of $D^2$.
To describe the attaching map of the boundary of the 2-cell, it's best to have a good picture, which is too hard for me to reproduce here, but I'll try to describe how you can produce the required picture. Imagine that the interior of $u$ is filled out by concentric topological circles; of course, those circles will be distorted in the picture since the interior of $u$ is not literally round in the given picture, so this is going to take some visualization skill. Draw one of those circles which tracks close to the $1$-skeleton. Trace exactly one time around that circle, writing down the concatenation of 1-cells which that circle tracks close to. For example, if you start near $x$ going in the clockwise direction around the outer $a$ circle, but staying just inside that circle, and continue close to the 1-skeleton but never touching the 1-skeleton, then you will get
$$aba^{-1}b^{-1}ca^{-1}c^{-1}
$$
If you start at a different point you will get a cyclic permutation (e.g. $b a^{-1} b^{-1} c a^{-1} c^{-1} a$). If you go in the opposite direciton you will get the inverse (meaning $c a c^{-1} b c b^{-1} a^{-1}$), or a cyclic permutation of the inverse (e.g. $a c^{-1} b c b^{-1} a^{-1} c$).
Comment: Thank you, that makes sense.
Comment: Is it correct that with this structure the boundary map takes $U$ to $3a$?
Comment: It *seems* like you are asking about the boundary map of the CW-chain complex (with coefficients in, say, $\mathbb Z$)? In which case no, what you ask is not correct. The actual answer depends on which orientation one assigns to $U$. If $U$ is assigned the orientation described in my answer then its image under the boundary map is $a^{-1}$.


Save_and_open_page is blank in cucumber / capybara but not in rspec request spec

Question: I am baffled as to why my save_and_open_page works in my request spec, but not in this cucumber feature / web steps. It does work in other features / web steps files.
I'd love a pointer to where to begin looking for the root cause of this problem.
https://gist.github.com/2210420
ok, I think it may have something to do with this encoding error when I'm using pry?
<code>From: /Users/ivan/dev/c4c/features/step_definitions/licenses_steps.rb @ line 20:

15:     name: arg1,
16:     status: ExpressLicenseTechnology::PUBLISHED_STATUS)
17: end
18:
19: When /^I am on the license page for "([^"]*)"$/ do |arg1|
=> 20:   binding.pry
21:   visit(license_path(License.find_by_name(arg1)
22: ))
23: end
24:
25: Then /^I should see a form for licensee info$/ do

[1] pry(#<Cucumber::Rails::World>)> arg1
=> "test no fee license"
[2] pry(#<Cucumber::Rails::World>)> License.find_by_name(arg1)
=> #<License id: 3, name: "test no fee license", description: "license one description", status: "published", allow_edu: nil, allow_other: nil, allow_org: nil, allow_us_gov: nil, require_contact_info: nil, show_contact_info_form: nil, way: "clickthrough", express_license_technology_id: 1, created_at: "2012-03-27 16:39:41", updated_at: "2012-03-27 16:39:41", licensefile_file_name: "test-license.pdf", licensefile_content_type: "application/pdf", licensefile_file_size: 516650, licensefile_updated_at: "2012-03-27 16:39:41", fee: #<BigDecimal:7ffcb1310820,'0.154E3',9(18)>, allocation_rule_number: "66", fulfillment_email: nil>
[3] pry(#<Cucumber::Rails::World>)> ap License.find_by_name(arg1)

#<License:0x007ffcabf00b68> {
                               :id => 3,
                             :name => "test no fee license",
                      :description => "license one description",
                           :status => "published",
                        :allow_edu => nil,
                      :allow_other => nil,
                        :allow_org => nil,
                     :allow_us_gov => nil,
             :require_contact_info => nil,
           :show_contact_info_form => nil,
                              :way => "clickthrough",
    :express_license_technology_id => 1,
                       :created_at => Tue, 27 Mar 2012 16:39:41 UTC +00:00,
                       :updated_at => Tue, 27 Mar 2012 16:39:41 UTC +00:00,
            :licensefile_file_name => "test-license.pdf",
         :licensefile_content_type => "application/pdf",
            :licensefile_file_size => 516650,
           :licensefile_updated_at => Tue, 27 Mar 2012 16:39:41 UTC +00:00,
                              :fee => 154.0,
           :allocation_rule_number => "66",
                :fulfillment_email => nil
}
=> #<License id: 3, name: "test no fee license", description: "license one description", status: "published", allow_edu: nil, allow_other: nil, allow_org: nil, allow_us_gov: nil, require_contact_info: nil, show_contact_info_form: nil, way: "clickthrough", express_license_technology_id: 1, created_at: "2012-03-27 16:39:41", updated_at: "2012-03-27 16:39:41", licensefile_file_name: "test-license.pdf", licensefile_content_type: "application/pdf", licensefile_file_size: 516650, licensefile_updated_at: "2012-03-27 16:39:41", fee: #<BigDecimal:7ffcabf01428,'0.154E3',9(18)>, allocation_rule_number: "66", fulfillment_email: nil>
[4] pry(#<Cucumber::Rails::World>)> license_path(License.find_by_name(arg1))
=> "/licenses/3"
[5] pry(#<Cucumber::Rails::World>)> visit(license_path(License.find_by_name(arg1)))
=> nil
[6] pry(#<Cucumber::Rails::World>)> save_and_open_page
encoding error : output conversion failed due to conv error, bytes 0xA3 0xC3 0x8F 0xC3
I/O error : encoder error
=> #<Thread:0x007ffcb1280f40 sleep>
[7] pry(#<Cucumber::Rails::World>)>
</code>
encoding error : output conversion failed due to conv error, bytes 0xA3 0xC3 0x8F 0xC3
    I/O error : encoder error
Answer: Fixed by removing the pdf file from the license fixture.


How to make a custom menu on PHP?

Question: I am new to PHP, however, I have developed a membership frameworks for my website that is fully functional. There is one thing I would like to do before I begin designing, but I don't know how. I will provide my code so that I can use examples:
HTML/PHP

    Home

    <?php
    if($_SESSION['loggedin'] = false){
        echo 'Sign UpSign In';
        exit();
    }else if($_SESSION['loggedin'] = true){
        echo 'Sign Out';
        exit();
    }
    ?>

As you can see, So far I have a simple, mediocre menu in place. What I am looking to do is to make it respond to my PHP script, which I don't know how to properly structure. In my frameworks, when a user logs in, their $_SESSION['loggedin'] value is changed to true, and when they log out, the value is changed to false. So what I am looking for is to have my menu show only the appropriate hyperlinks for the user. For example, if a user is signed in, they don't want hyperlinks that will lead them to sign in or sign up, they will want the hyperlink to sign out. And when a user is not signed in and/or does not have an account, they will want the hyperlinks to sign in and sign up. My PHP above currently does not work. Is there any way to do what I am looking for? If so, please help! Thanks in advance!
Here is the Signin.php
<?php
// AJAX CALLS THIS LOGIN CODE TO EXECUTE
if(isset($_POST["e"])){
// CONNECT TO THE DATABASE
include_once("php_includes/db_conx.php");
// GATHER THE POSTED DATA INTO LOCAL VARIABLES AND SANITIZE
$e = mysqli_real_escape_string($db_conx, $_POST['e']);
$p = md5($_POST['p']);
// GET USER IP ADDRESS
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// FORM DATA ERROR HANDLING
if($e == "" || $p == ""){
    echo "signin_failed";
    exit();
} else {
// END FORM DATA ERROR HANDLING
    $sql = "SELECT id, username, password FROM users WHERE email='$e' AND activated='1' LIMIT 1";
    $query = mysqli_query($db_conx, $sql);
    $row = mysqli_fetch_row($query);
    $db_id = $row[0];
    $db_username = $row[1];
    $db_pass_str = $row[2];
    if($p != $db_pass_str){
        echo "signin_failed";
        $_SESSION['loggedin'] = "false";
        exit();
    } else {
        // CREATE THEIR SESSIONS AND COOKIES
        $_SESSION['userid'] = $db_id;
        $_SESSION['username'] = $db_username;
        $_SESSION['password'] = $db_pass_str;
        $_SESSION['loggedin'] = "true";
        setcookie("id", $db_id, strtotime( '+30 days' ), "/", "", "", TRUE);
        setcookie("user", $db_username, strtotime( '+30 days' ), "/", "", "", TRUE);
        setcookie("pass", $db_pass_str, strtotime( '+30 days' ), "/", "", "", TRUE);
        // UPDATE THEIR "IP" AND "LASTLOGIN" FIELDS
        $sql = "UPDATE users SET ip='$ip', lastlogin=now() WHERE username='$db_username' LIMIT 1";
        $query = mysqli_query($db_conx, $sql);
        echo $db_username;
        exit();
    }
}
exit();
}
?>

Comment: What exactly doesn't work?  Have you tried echoing the value of $_SESSION['loggedin'] to make sure it is being set correctly when they log in?
Comment: Here is a link to my site (http://www.codesrce.com) and Unless my IP is already signed in, you will also see on your computer that the menu just says "Home" and "Sign Out" when you are not even signed in @BarbaraLaird
Answer: Simply change = to ==. You're comparing, not assigning. Also, no need to put exit() because it will terminate the next operations, just what EternalHour said to his post that it will end the next echo.
  <?php
        if($_SESSION['loggedin'] == false){
            echo 'Sign UpSign In';
            //exit();
        }else if($_SESSION['loggedin'] == true){
            echo 'Sign Out';
           // exit();
        }
        ?>

EDIT
Add session_start() in your sign_up or sign_in code to address $_SESSION.
// END FORM DATA ERROR HANDLING
    session_start();
    $sql = "SELECT id, username, password FROM users WHERE email='$e' AND activated='1' LIMIT 1";
    $query = mysqli_query($db_conx, $sql);
    $row = mysqli_fetch_row($query);

Comment: For some reason, it only works for the not logged in feature. Maybe the else if statement is not allowing the logged in one to work?
Comment: When I am not logged on it displays only the Sign Up and Sign In hyperlinks, which is what I want, but when I am signed in, it still shows those 2, not the Sign Out hyperlink, which is what i want, for some reason @kimbarcelona
Comment: The first condition is if $_SESSION['loggedin'] is not set. If you set $_SESSION['loggedin'] upon sign in or sign up, else if will work.
Comment: Have you put value in $_SESSION['loggedin'] after sign in or sign up? It's like $_SESSION['loggedin'] = "true";
Comment: The Signin.php is what goes off when the user tries to sign in @kimbarcelona
Comment: That wasn't a solution @EternalHour
Comment: @EternalHour, sorry if my answer seems to have your answer as well but I've modified it i think after you've answered as well
Comment: Hi @user3761911, you need to add session_start(). See my edit
Comment: @user3761911 It wasn't a solution? "Okay the removing of the exit worked. Thanks :)"
Comment: My apologies, I just meant that it reminded me that I didn't need that. I should have reworded. English isn't my first language. @EternalHour
Comment: Well, it was not solution fully because it need session_start(); also. But I can't downvote because I don't have reputation of 15. Thank you for part of the solution. And don't feel bad. My site is just a silly old simple website that isn't going anywhere. @EternalHour It is just for educational purposes
Comment: Well, stackoverflow has edit functionality to modify the answer. Shame on you for being so rude for just an answer. You're greatly affected with this thinking that your answer solves OP's problem.
Answer: A bit cleaner code as an example where you also check that the session is set:
<?php
$notLoggedInMenu = 'Sign UpSign In';
$loggedInMenu = 'Sign Out';
echo isset($_SESSION['loggedin']) && $_SESSION['loggedin'] ? $loggedInMenu : $notLoggedInMenu;
?>

Comment: You'll always need to check if the session is set. Otherwise you might get a warning. It doesn't matter what values you use for the session.
Comment: This is better. Once I get it to work, I might use this. Thanks!
Comment: Remember to use session_start() at the top of your page. Can't find it in your example.
Answer: I see a couple of things that may be causing issues.
First of all, as @kimbarcelona mentioned, you need to use the == comparison operator instead of =.
Secondly, you need to remove the exit(); because that will kill your echo.
Comment: Nope. This is not a complete solution @EternalHour.
Comment: Hmm, I'll just mention you on my post
Comment: You know @EternalHour, your second answer regarding exit() is saying like it will disallow echo to work. In his code, echo was executed first before exit. It's not that clear. My answer simply says that exit will terminate next operations not only echo. It will end the execution of PHP itself. You're lack of reasoning mate.

How to make a custom menu on PHP?


Issue in taxonomy term with hyphen(-) in url drupal7

Question: I have a taxonomy called free-choices.But the contents are not listed when hyphen(-) in the taxonomy name.The pages with taxonomy name without hyphen is listing contents.How to solve this issue?I checked this validation criteria .But this is not working.How to solve this issue?

How to solve this issue in the same views?
Answer: If you want a taxonomy term to be recognized wholly, then you definitely do not want to divide it with spaces, so uncheck the Transform dashes in URL to spaces in term name filter values.
Also check on the Use path alias instead of internal path option and set the correct path component. It shows set to 1, but most probably it's different component in the taxonomy path alias.
Additionally, try to use term ID instead of term name.
Comment: If it is unchecked also it is not working.
Comment: Try `Use path alias instead of internal path` and set the correct path component.
Comment: Yes i checked the use path alias here.But not working
Comment: Change the path components, it is definitely not 1 in your case. Also I'd recommend you to register and start accepting asnwers as otherwise less people will want to help you with your questions.
Comment: Thanks.But all other categories are working except with hyphen.
Comment: Try to use term ID instead of term name in the `Filter value type` option, so then you won't deal with the hyphen issue at all.
Comment: Hyphen issue is solved by  passing Content: Has taxonomy term ID (with depth) to the views.But data from 3 taxonomies are missing.


Why are my clickCounts all adding on top of each other rather than counting separately?

Question:

<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Vote!</title>

<input type="button" value="VOTE" name="clickOnce" onclick="return countClicks();" />

<input type="button" value="VOTE" name="clickOnce" onclick="return countClicks1();" />

<input type="button" value="VOTE" name="clickOnce" onclick="return countClicks2();" />

Answer: ummm...
because x is a global variable and clickCount always using the same variable...
also, I'd suggest you to DRY your code, and make the function operate based on a parameter, you DON'T need 3 functions which all do exactly the same thing.
Answer: var x is a global variable. Once it has been declared, then your functions will use the same variable. So in both countClicks and countClicks1 they are using the same variable.
Change the second to use var x2 = 0


asp.net add html elements from static method

Question: I trying to add HTML  or image button which can call code behind method, from a static method(Web method), I am calling web method through AJAX. My code is:
AJAX Method
function dispData()
    {

        var text_data = document.getElementById("TextBox1").value;
        var text_count = text_data.length;

        if (text_count >= 4)
        {
            alert("Text box val = " + text_data + " :Count = " + text_count);

            $.ajax({
                type: "POST",
                url: "WebForm2.aspx/ajaxData",
                data: JSON.stringify({ data: text_data }),
                contentType: 'application/json; charset=utf-8',
                dataType: "JSON",
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
                },
                success: function (result) {
                    //alert("We returned: " + result.d);
                    $('#disp_ajax_data').html(result.d);<-- displaying result in div
                }
            })
            return false;//end of ajax

        }//end of if text_count.

    }//end of dispData.

[WebMethod(TransactionOption = TransactionOption.Supported)]
    public static string ajaxData(string data)
    {
       for (int loopCount = 0; loopCount < myCount; loopCount++)
            {
                string ele = oCompInfoSet[loopCount].Name + "Add" + "
";
                returnVal += ele;

            }//end for loop.
    }

I am displaying the names properly but not able to get the buttons. Can anyone please help
EDIT:
From deostroll's help, my changed code, Oh... silly me.... I missed 'Static' keyword. I am trying to pass value now
for (int loopCount = 0; loopCount < oCompInfoSet.ComponentCount; loopCount++)
            {
                //Debug.WriteLine("In for loop");
                string ele_name = oCompInfoSet[loopCount].Component.Name;
                string ele = ele_name + "Add
";
                returnVal += ele;

            }//end for loop.

[WebMethod(TransactionOption = TransactionOption.Supported)]
    public static void addToStream()
    {
        Debug.WriteLine("Add to stream here");
    }//end of addToStream

JS METHOD:
function add_ele(name)
    {
        alert("add ele called, "+name);
        //PageMethods.addToStream();

    }//end of add_ele.

I am not getting alert also now, getting "Unidentified Error"....
Comment: are you sure you are doing this (`"`) right?
Comment: @deostroll: Anchor is appearing but it is not calling the method.
Comment: A client js cannot call a server side method as-is? you probably would have encountered some error on your web page, because your js engine won't recognize `codeBehindMethod`!
Comment: I just want to add a button in front of each names, onClick of these buttons it should call code behind method. how can I do this, please help
Answer: Try looking at this: http://visualstudiomagazine.com/articles/2007/08/28/creating-and-consuming-aspnet-ajax-page-methods.aspx
The article above utilizes a concept called Page Methods. You have to enable it on the ScriptManager. Here is a simple example that is kind of in line with what you are doing:
Aspx page:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApp.PageMethods.WebForm1" %>

<!DOCTYPE html>

    <title>Page Methods</title>

    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server"></asp:ScriptManager>

        <input type="button" onclick="GenerateLinks(5)" value="Add Links" />

    </form>

Code behind:
using System;
using System.Collections.Generic;
using System.Web.Services;

namespace WebApp.PageMethods
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [WebMethod]
        public static string GenerateLinks(int number)
        {
            List<string> a = new List<string>();
            for (int i = 0; i < number; i++)
            {
                a.Add("Get Time " + (i + 1) + "");
            }

            return string.Join("
", a);
        }

        [WebMethod]
        public static string GetTime(string guid)
        {
            return guid + " / " + DateTime.Now.ToLongTimeString();
        }
    }
}


Is it a good idea to put shared files outside public_html / root?

Question: I just figured out that I can place files outside the domain root (outside public_html).
The benefit of placing functions outside the domain root is that I can use the same file on multiple domains. If I update my file in a single location, all my domains get updated.
Like this:
include __DIR__ . '/../../my-hidden-folder/functions.php';

My question is, now that it's possible, is it a good idea to work like this? Or are there reasons why this is not a good approach?
Not that it probably matters but I use PHP, Apache and Cpanel.
Answer: In general it is good practice to only store data that needs to be directly accessible by an URL in your web root and everything that is not should be stored outside the web root.

The benefit of placing functions outside the domain root is that I can use the same file on multiple domains.

That is not quite true. The include() function doesn't care if files are inside or outside a web root, or if logically that file-system directory used as the web root for a different site...
Comment: Yes, I agree. What do you think of the idea to share files (include functions) between domains in a folder below the public_html? Any pitfalls?
Comment: This is good practice (code-reuse). However, keep in mind that if you need to make a change to one of these functions while working with domain A, and you inadvertently change it in a way that domain B is now broken (such as you removed one of the function arguments, and updated domain A, but forgot all about domain B).


Geometrical interpretation of a diagram in Complex Analysis

Question: I am currently self-studying complex analysis in preparation for my course that will commence next year and I am stuck with this question as shown below:
In the complex plane, draw a picture of $$S=\{z \in \mathbb{C} : \vert z-1 \vert + \vert z+1 \vert = 2\}.$$
I was told that by squaring both sides, the curve is equivalent to $$\vert z^{2} \vert + \vert z^{2} -1 \vert = 1$$ but I cannot work out as such. Can anyone show me how the squaring of both sides resulted into the equation?
Comment: This seems to fit the definition of an ellipse with foci at $1$ and $-1$ (or if viewing $\mathbb{C}$ as $\mathbb{R}^2$, an ellipse with foci at $(1,0)$ and $(-1,0)$).
Answer: The trick is the identity $|z|^2 = z\bar z$. Squaring both sides of your equation,
$$|z-1|^2 + 2|z-1||z+1| + |z+1|^2 = 4.$$
Now rearrange this and use the identity above to get
$$(z-1)(\overline{z-1}) + (z+1)(\overline{z+1}) + 2|z^2-1| = 4.$$
But $\overline{z-1} = \bar z-1$, so $(z-1)(\overline{z-1}) = (z-1)(\bar z-1) = z\bar z-z-\bar z+1=|z|^2-z-\bar z+1.$ Similarly, $(z+1)(\overline{z+1}) = |z|^2+z+\bar z+1$, so our equation becomes
$$|z|^2-z-\bar z+1 + |z|^2+z+\bar z+1 + 2|z^2-1|=4.$$
Simplifying this gives you the result you're after.
Now, having said that, note that you don't actually need to do any of this. The original equation describes those points whose total distance from $z=1$ and $z=-1$ is equal to $2$. In other words, this is an ellipse with foci at $1$ and $-1$, and the distance is such that the ellipse is degenerate (i.e., it consists of the line segment between the foci).
Answer: Sum of distances is 2. And inter-focal distance $ 2 a $ also 2. So it is a degenerate ellipse (or parabola to a scale). If the latter is > 2 an ellipse can be formed with foci at $( \pm 1, 0 )$


Can I simply buy dedicated IP addresses from any website and assign them to my server?

Question: As the question suggests, is it possible for me to buy/get dedicated/static IP addresses and connect them to my OpenVPN server so I can assign each IP address to a client?
Comment: No it isn't....
Comment: You mean, like buying a phone number and just assigning it to your mobile phone, without telling the network operator?
Answer: You can't get provider independent IPv4 space unless you are buying at least a /24 worth (which will cost you at least $6000) and have your own autonomous system. You don't have your own AS; you aren't big enough.
You will need to obtain IP addresses from whoever hosts you, who does have their own AS. You won't be able to take these addresses with you to another provider; they remain with the provider who supplied them to you.
Comment: To elaborate, the reason is that you need to ensure that the whole world knows where to send data so that it arrives in "your" addresses; that's done by someone with multiple large IP ranges (the autonomous system/AS) advertising how to reach "their IP range" where they will know how to forward data to your specific hardware.
Comment: What is stopping you from getting your own AS? Your RIR rejecting your application?
Comment: Are you sure you need your own AS? I was under the impression that you could own provider independent space and get your provider to advertise it under their AS.
Comment: As with any such technical query, my suggestion is always to talk to several supplies - learning more from each one - until you find two or three both happy to take the time, and capable of explaining everything in a way you understand… it matters little whether the query is how to fuse a domestic appliance or cool a nuclear power station.

Once they've shown they're both willing and able to help, look at considerations like cost and service…
Comment: @gszavae Most likely, [policy](https://www.arin.net/participate/policy/nrpm/#5-as-numbers). He does not sound like he can currently meet these requirements.
Comment: As the question is not specific to IPv4, mentioning IPv6 might be worthwile?
Comment: @DoktorJ I'm aware of IPv6. I have been routing global IPv6 blocks over OpenVPN for years. I also understand people, which is why I am sure the OP had no thought of IPv6 whatsoever. Maybe he should have, but he gave no indication of it, and that is why it is not mentioned.
Comment: I can't imagine where one would find a seller for an entire class C at $6k in this day and age.
Comment: This is partly backwards. You need the IP space before you can apply for an AS number.
Comment: @PeterGreen To my knowledg the requirement of getting routed is 2 different uplinks - so 2 providers. Which means need an AS.
Comment: IPv6 addresses are *much* cheaper.
Comment: @PaŭloEbermann The question did not ask about IPv6.
Comment: @MichaelHampton No, but not about IPv4 as well. It was about IP addresses, which come in these two flavours.
Comment: @MichaelHampton glglgl is correct, IP addresses come in both flavors, and the question does not explicitly state or in any other way indicate a need for IPv4, so there's no reason not to use IPv6. OpenVPN most certainly supports it. Of course I have a hard time understanding why one might want to assign public IPs directly to VPN clients in the first place (it's less safe and will likely be more difficult to set up in OpenVPN and actually get working as expected)


Wordpress/Easy WP SMTP Error Sending TLS Secured Mail to Exchange 2016 On-Prem Server

Question: I have a non-domain joined Windows Server 2012R2 web server hosting Wordpress with the Easy WP SMTP plugin in our DMZ.  It is supposed to send email to our internal Exchange 2016 server for things like alerts, new sign-ups, etc.  It used to be using unsecured SMTP over port 25 but we are trying to configure it to use TLS on port 587.  But, I cannot get it to send as the Exchange Server keeps rejecting the connection:
<code>    2020-03-30T13:25:53.654Z,<Rcv Conn>,08D7D3F917D985E4,0,10.0.0.44:587,192.168.200.3:58156,+,,
    2020-03-30T13:25:53.654Z,<Rcv Conn>,08D7D3F917D985E4,1,10.0.0.44:587,192.168.200.3:58156,>,"220 mail.domain.com Microsoft ESMTP MAIL Service ready at Mon, 30 Mar 2020 08:25:53 -0500",
    2020-03-30T13:25:53.654Z,<Rcv Conn>,08D7D3F917D985E4,2,10.0.0.44:587,192.168.200.3:58156,<,EHLO www.domain.com,
    2020-03-30T13:25:53.654Z,<Rcv Conn>,08D7D3F917D985E4,3,10.0.0.44:587,192.168.200.3:58156,>,250  mail.domain.com Hello [192.168.200.3] SIZE 36700160 PIPELINING DSN ENHANCEDSTATUSCODES STARTTLS AUTH GSSAPI NTLM 8BITMIME BINARYMIME CHUNKING,
    2020-03-30T13:25:53.654Z,<Rcv Conn>,08D7D3F917D985E4,4,10.0.0.44:587,192.168.200.3:58156,<,STARTTLS,
    2020-03-30T13:25:53.654Z,<Rcv Conn>,08D7D3F917D985E4,5,10.0.0.44:587,192.168.200.3:58156,>,220 2.0.0 SMTP server ready,
    2020-03-30T13:25:53.654Z,<Rcv Conn>,08D7D3F917D985E4,6,10.0.0.44:587,192.168.200.3:58156,*," CN=*.domain.com CN=Sectigo RSA Domain Validation Secure Server CA, O=Sectigo Limited, L=Salford, S=Greater Manchester, C=GB 4F8D1253CAE6C3AA06ED0310EAA39158 827CCAB98B7AC22709CBC1408C74CCED89060C98 2020-03-17T19:00:00.000Z 2021-03-18T18:59:59.000Z *.domain.com;domain.com",Sending certificate Subject Issuer name Serial number Thumbprint Not before Not after Subject alternate names
    2020-03-30T13:26:08.998Z,<Rcv Conn>,08D7D3F917D985E4,7,10.0.0.44:587,192.168.200.3:58156,*,,TLS negotiation failed with error CertUnknown
    2020-03-30T13:26:08.998Z,<Rcv Conn>,08D7D3F917D985E4,8,10.0.0.44:587,192.168.200.3:58156,-,,Local
</code>
The certificate is fine because lots of other TLS connections on 587 work without any problemns.
Answer: Based on your error messages, this issue seems to be related with certificate.
What about other external users? All external emails cannot be received, or only external emails sent by this web server?
I suggest you check if you enable SMTP service in certificate, and run this below command to set RequireTLS to True, check if it works:
<code>Set-ReceiveConnector "<receive connector name>" -RequireTLS $true
</code>
Here's a similar thread for your reference. TLS negotiating failed
Comment: Thanks for your reply.  It was only external emails from our website that had an issue.  As it turns out, the problem was the SMTP plugin we were using.  I changed to a different plugin and all is working fine now.
Comment: Thanks for your sharing :)
Answer: The issue was the Easy WP SMTP plugin.  Switched to Postman SMTP and everything is working properly now.


Length of shortest path

Question: What is the length of shortest path that begins at the point (-1,1) , touches the x axis and then ends at point on the parabola $(x-y)^2 =2(x+y-4)$ .
I put $x=x-y$
$y=x+y-4$
then the starting point would be $(-4,-2)$ .
can I proceed by this methos of changing the coordinates
After that I got stuck. Can anybody help me?
Comment: If you'd like us to help you proceed from where you got stuck, you should show us your work up to that point. "this methos [sic] of changing the coordinates" doesn't really tell us anything.
Answer: Note that the parabola lies entirely in the first quadrant.
Let $P_1$ be the point $(-1,1)$ and $P_2$ be its reflectional image in the $x$-axis, i.e. $P_2=(-1,-1)$. Suppose that the path meets the $x$-axis at $Q$. The shortest path should consist of a line segment joining $P_1$, $Q$ and a line segment joining $Q$ and some point on the parabola. The two line segments are not in the same direction. But the line segment $P_1Q$ has the same length as $P_2Q$. So we can replace the starting point by $P_2$ and the path can be a line segment. So the shortest length is the shortest distance between $P_2$ and the parabola, which is equal to the distance between $P_2$ and the point $(2,2)$. So the length of the shortest path is $3\sqrt{2}$.
Comment: Why the ine segment P1Q have same length as of P2Q
Comment: $Q$ is on the $x$-axis. $P_1$ and $P_2$ are symmetric about the $x$-axis. So the line segments $P_1Q$ and $P_2Q$ are symmetric about the $x$-axis.
Comment: And how you got the point (2,2)
Comment: The parabola has the line $y=x$ as the axis of symmetry, which also passes through $P_2$. $(2,2)$ is the vertex of the parabola..
Comment: Or you can rotate the whole picture through $45^\circ$.
Comment: Is my method is not good . of changing the coordinates
Answer: Your transformation maps $(0,0)$ to $(0,-4)$ and $(-1,1)$ to $(-2,-4)$. It does not preserve distances.
Comment: I thought it like this answer     https://math.stackexchange.com/q/2256352
Comment: @user123733 Notice that in that answer, they used rotation transformation. The new coordinates, u, v were perpendicular to each other in that case.
Comment: @samjoe okay thanks

Length of shortest path


How to use a translated taxonomy in autocomplete term-reference fields?

Question: When I translate a taxonomy to other languages, I cannot use it in autocomplete term-reference fields.
The auto complete field will show items only in the default language; if I try to fill the form from another language, nothing shows up in the field when I type.
It happens only when I use the autocomplete widget.
I am using Drupal 7.15.
Answer: Are you using 'Entity Translation' or the core 'Content translation'?
I think the sub-module Multilingual select (from Internationalization) should handle this for 'Content translation' (didn't test it, though).
But for Entity Translation, this doesn't seem to work (yet): see Entity translation and the Multilingual select i18n submodule interactions and Language aware edit form and autocomplete.
Answer: read this  "Localize terms show always the default language" . but I personally suggest you don't translate terms, you can add both terms in you vocab . terms_data table impproved  in Drupal7 and  handle very much terms charmly.


How to simplify $\sin(x-y)\cos(y)+\cos(x-y)\sin(y)$

Question: the question
How to simplify $\sin(x-y)\cos(y)+\cos(x-y)\sin(y)$
my steps
I tried to use trig identities on the $\sin(x-y)$ and $\cos(x-y)$ and tried to distribute the others in but it didn't work. Any ideas?
Comment: Use the identity the other way around: sin(a+ b)= sin(a)cos(b)+ cos(a)sin(a+ b) with a= x- y, b= y.
Comment: Your question is very easy. Another way, use a plotter with slider control for the curve $\sin(x-a)\cos(a)+\cos(x-a)\sin(a)$ and see that the curve shown is not altered with the variation of $a$. What do you suggest?
Answer: Let's do the (harder) method attempted by the OP, "but it didn't work".
$$
\sin(x-y)\cos(y)+\cos(x-y)\sin(y)
\\ =
\big[\sin(x)\cos(y)-\cos(x)\sin(y)\big]\cos(y)+\big[\cos(x)\cos(y)+\sin(x)\sin(y)\big]\sin(y)
\\ =
\sin(x)\cos(y)\cos(y)-\cos(x)\sin(y)\cos(y)+\cos(x)\cos(y)\sin(y)+\sin(x)\sin(y)\sin(y)
\\=
\sin(x)\cos^2(y)+\sin(x)\sin^2(y)
\\=
\sin(x)\big[\cos^2(y)+\sin^2(y)\big]
\\= \sin(x)\big[ 1 \big]
\\=\sin(x)
$$
Answer: HINT:
Recall that $\sin(a+b)=\sin(a)\cos(b)+\sin(b)\cos(a)$.  Now, let $a=x-y$ and $b=y$.
Answer: Knowing the solution (using methods posted by others) suggests an alternate solution. Apply $\frac{\partial}{\partial y}$ to your expression and you get:
$$-\cos(x-y)\cos(y)-\sin(x-y)\sin(y)+\sin(x-y)\sin(y)+\cos(x-y)\cos(y)=0$$
So the expression is actually constant in $y$. It takes on the same value for all values of $y$ as for when $y=0$:
$$\begin{align}
&\sin(x - 0)\cos(0)+\cos(x-0)\sin(0)\\
&=\sin(x)\end{align}$$
Comment: Good one, +1. Shouldn't it be a $\partial$ instead of $\mathrm d$, though?
Comment: @YoTengoUnLCD Sure, good suggestion.
Answer: by using well known identity we get

$$\\ \sin { x=\sin { \left( x-y+y \right) = }  } \sin  (x-y)\cos  (y)+\cos  (x-y)\sin  (y)$$


How to load absolute CSS and JS assets

Question: I would like to load CSS and JS from https://static.example.com . The typical page contains:
<link rel="stylesheet" href="/sites/default/files/css/css__wBfhyL83sORKzo__AgHv4HOGuOoSbIzIaa4clq9PXs.css?pik02l" media="all" />

and contains similar entries for JS.  I would like to add https://static.example.com to the front of the href="URL" for both CSS and JS.
I'm am aware that this can be done with a contrib module.  I would like to find a hook or some other way to add this to my custom module.
Comment: Dis you try adding to your libraries.yml?
Answer: Even though you don't want to use a contrib module I will recommend the CDN module anyways. It does what you want, but if you don't want to use it you can still look at how they do it.
They define a lot of services, but the most interesting one is this one:
cdn.file_url_generator:
    class: Drupal\cdn\File\FileUrlGenerator
    arguments: ['@app.root', '@file_system', '@stream_wrapper_manager', '@request_stack', '@private_key', '@cdn.settings']

The class FileUrlGenerator then does checks for files to determine if they should be rewritten and rewrites them.
Answer: These are aggregated assets, so you need to find out how they get added there in the first place. Then you can alter them most likely via hook_page_attachments_alter. Similar to Make canonical URL in document HEAD absolute.
Problematic about this approach is that these assets should are aggregated with that cryptic hash in their name per environment. So you need to switch off your custom module everywhere else except on the live instance.

How to load absolute CSS and JS assets


Uncaught Error: Method load does not exist on jQuery.tabs

Question: I'm using JQuery tabs. Every tab loads a different file.
In one of the tabs, there's a form that is ajax - submitted. After the form is successfully submitted, a message appears in that tab: "successful!!" and I have a link for reloading the original form, in case you want to make another form submission.
I need to re-load that tab, not just "relocate", because on the load method some things are initialized, like a JS date-picker.
This is how the tabs are created:

title 1

title 2

title 3

This is the code for the tabs loading. If "theCalendar()" function is not invoked, then the date-picker that uses this form is not available, so it has to be there:
    $('#tabs').tabs({
        cache: true,
        load: function(event, ui) {
        var active = $('#tabs').tabs( "option", "active" );
            if (active == 2){
                $('#amstart').addClass('selectedRadio');
                $( "input[type=submit]" ).button();
                theCalendar();
            }
        }
    });

The form I'm talking about is in the 3rd tab (createMeeting.jsp) and then the submit code is:
    $('#ui-tabs-3').on('click', '#submitBtn', function(event) {
    event.preventDefault();

    ... //many validations...

    myData =  $("#formMeeting").serialize();

    $.ajax({
        url: './meeting_details.jsp',
        type: 'POST',
        data: myData,
        success: function(data){
            $('#ui-tabs-3').html(data);
        },
        error: function (request, status, error) {
        alert(request.responseText);

    }
    });

});

So far, everything works fine, the form is submitted and the resulting html is shown on that very same tab.
Finally, in that resulting html there's a link for loading the form again in case you want to add another record:
Add another one

And is handled like this from the main file:
    $("#ui-tabs-3").on("click", "#createAnotherMeeting", function(e){
    e.preventDefault();
    $("#tabs").tabs("load",2); // option 1
    $("#tabs").tabs("load",$(this).attr('href')); // option 2
    $(this).parent().tabs("load",2); // option 3

    });

There's an "option 1,2 and 3" comments because I've tried all of those (one at the time), however I keep getting this error:
Uncaught Error: Method load does not exist on jQuery.tabs
at Function.error (jquery-3.2.1.min.js?_=1675464032676:2:1979)
at jQuery.fn.<computed> [as tabs] (materialize.min.js?_=1675464032678:6:13237)
at HTMLAnchorElement.<anonymous> (videoConferencias.jsp:242:20)
at HTMLDivElement.dispatch (jquery-1.8.3.js:3058:9)
at HTMLDivElement.eventHandle (jquery-1.8.3.js:2676:28)
...
...

I was able to change the location of the tab so the createMeeting.jsp file is shown, however, that didn't solve my problem since the date-picker function wasn't loaded, and the submit button wasn't recognized by JQuery (these things are done when the tab is loaded)
All I need is to reload that tab when the link is clicked.
Any help will be really appreciated.
Answer: it turns out that I had a reference to another version of jQuery and materialize at the bottom of 'hidden' in another page (createMeeting.jsp):

I deleted them and the error disappeared ;)
In order to re-load the tab using that link, I did another ajax submit, so I could invoke the date-picker and the other stuff:
$("#ui-tabs-3").on("click", "#createAnotherMeeting", function(e){
    e.preventDefault();
    $.ajax({
        url: './crearMeeting.jsp',
        type: 'POST',
        data: '',
        success: function(data){
            $('#ui-tabs-3').html(data);
            $('#amstart').addClass('selectedRadio');
            $( "input[type=submit]" ).button();
            theCalendar();
        },
        error: function (request, status, error) {
        alert(request.responseText);
    }
    });

});

Maybe it's not the cleanest solution, but it works.


SQL server - extract and run queries on 20GB data

Question: I do have a BKS file which contains 15GB+ size. How do I extract the data and run queries on this? I was told that this is SQL Server data. Should I try to upload this to SQL Azure? Any ideas.
Answer: You must use any edition of SQL Server, restore database and run your queries.
SQL Express not able to work with such amount data - there is limitation on 4GB (ver2010).
Comment: ok, will try and get an SQL server. But will that read the BKS file directly?
Comment: 2008 R2 has 10GB limit but probably still not enough storage for this situation
Answer: download sql server 2008 express edition from microsoft (free), and restore the backup on your dev machine..
Comment: #will that take 20gb data?

No - you'll need to download the free trial of the enterprise edition
Comment: #"Also how about extracting that BKS file"... BKS is a windows backup file format.  Try using "restore" option in control panel.  There should be a BKF file in there (the sql  backup file) - use SQL Server management studio to restore this.
Comment: Also how about extracting that BKS file?
Comment: @bob: SQL Server Express works only on 4GB (maximum) databases.
Comment: Thanks Bob, I use windows xp. Any ideas on how I can extract the BKS file? I cant find any option that takes this BKS file as input.
Comment: perhaps NTBackup? http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/ntbackup_command.mspx?mfr=true
Comment: still no luck, i cant figure out how to extract sql from the bks file
Comment: a bks file is a system restore backup file, from what I read, so I'd imagine you;d have to extract a BKF (sql backup) file from the BKS (nt backup) file.  -- Assuming the BKS file is a NTBackup file.  Maybe ask the person who provided the BKS file?
Comment: Thanks Bob.

I tried to open the BKS file in ntbackup and no idea how to get the BKF or SQl out of it. The person who provided the BKS cant not be reached unfortunately.
Comment: Still they don't have a way to take bks file as input on that. So still can't get anything out of the bks unfortunately.
Answer: It was actually a BAK file. Just run the standard restore database and point to the bks file.


chown during rsync from windows to unix

Question:
rsync: --groupmap=*:www-data: unknown option

I am trying to add an option to my rsync line to set the group of the files transfered to have www-data as their group.
When i add the option i get the above message.
Here is the rsync line i am trying:
rsync -avz --delete  --chmod=ug=rwX,o=rX  --groupmap=*:www-data ' -e "ssh -p 48"  /cygdrive/e/test  firstname.lastname@example.com:/var/vhost/locals/test

Without the -groupmap flag the files are landing as john:john instead of the desired  jonh:www-data.
This is from windows to ubuntu.
Does anyone have any ideas?
it is the same when i try to use --chown:
rsync: --chown=john:www-data: unknown option

ref: http://rsync.samba.org/ftp/rsync/rsync.html
Answer: The options you reference were included in Version 3.1.0 of rsync, but it looks like you are using cygwin on Windows, which may not have had this version until June-2014.
Given the proximity to your question, you are likely using an older version of rsync.  Perhaps you just need to upgrade to the latest cygwin/rsync?
rsync --version

Answer: The quickest way to solve this is to reverse into Windows.  If you rsync on Ubuntu from Windows you should be able to set permissions there.
Comment: The permissions are fine, it is the owner:group aka the chown which is wrong. The files are going in as john:john instead of john:www-data  i need to be able to do this via the rsync command and not have to chown the directory after each rsync as this is for a development build.
Comment: as in, the dev hits save, this rsync is run, the dev checks new file on dev server... if the dev has to log in all the time to chown the files that would get irritating
Answer: I gave up. A work around was to run apache as john:www-data. The rsync copies new files to the destination as john, but apache can read them fine as running as john:www-data.
[...]
<IfModule mpm_itk_module>
AssignUserId john www-data
</IfModule>
[...]

Answer: rsync  version 3.1.2
I mostly use windows in local, so this is the command line i use to sync files with the server (debian) :
user@user-PC /cygdrive/c/wamp64/www/projects

$ rsync -rptgoDvhP --chown=www-data:www-data --exclude=.env --exclude=vendor --exclude=node_modules --exclude=.git --exclude=tests --exclude=.phpintel --exclude=storage ./website/ username@hostname:/var/www/html/website

I hope this will be helpful for you
Comment: :) at the time of writing this i was on windows and the chown option did not work. I have long since ditched windows and moved to linux.
Comment: @John for me it work just fine!!
Comment: cygwin must have upgraded the version of rsync since then.
Comment: John, i came from a google research, so i put the answer for future users that may have the same problem.

chown during rsync from windows to unix


No closest point to the subspace in $L_1([0,1])$

Question: Define $S_1=\{f\in L_1([0,1]),\int_{0}^1 xf(x) dx=0      \}$ . I want to show for every $\epsilon>0$, there exist $f$ in $S_1$ with $\lVert f-1\rVert_1 \leq1/2+\epsilon$, but there's no $f$ with $\lVert f-1\rVert_1 =1/2$. I got $\lVert f-1\rVert_1 \geq1/2$ from Holder's inequality, but not able to move further. Any help or hint is appreciated.
Comment: Is $p=1$? ${}{}$
Comment: @copper.hat Yes, I corrected this now.
Answer: The inequality $\|f-1\|_1>1/2$ is immediate once you think about when the equality holds in Holder's inequality. That is
$$\frac12=\left|\int_0^1x(f(x)-1)dx\right|\le\int_0^1x|f(x)-1|dx\le\int_0^1|f(x)-1|dx$$
with the equality if and only if $f(x)=1$ a.e.. If you are feeling unsure about this, we may consider the integral of non-negative function $(1-x)|f(x)-1|$, which is zero, implying $(1-x)|f(x)-1|=0$ a.e. and hence our claim.
But if $f(x)=1$ a.e., then $f\not\in S_1$ as $\int_0^1 f=1/2$. So there's no $f\in S_1$ such that $\|f-1\|=1/2$.
Example for the other direction can be constructed from our argument above. Define
$$f_n(x)=\begin{cases}
n^2/(n-1)^2,\quad &x\in[0,1-1/n]\\
-n/(2x),\quad&x\in(1-1/n,1]
\end{cases}$$
It's straight-forward to verify $f_n\in S_1$. On the other hand,
$$\|f_n-1\|_1=\left(1-\frac1n\right)\frac{2n-1}{(n-1)^2}+\frac1n+\frac n2\ln\frac n{n-1}$$
tends to $1/2$ as $n\to\infty$. In other words, for sufficiently large $n$ we have $\|f_n-1\|_1<1/2+\epsilon$, as is desired.


MLE and Bayesian methods

Question: I saw in some lecture the fact that as the number of data points N goes to infinity, the prediction of the Bayesian method goes to the prediction of the MLE. Can someone explain what exactly this sentence means, and why is it true?
Thanks!
Comment: I strongly suggest [the short review by Suhashis Ghosal on Bayesian consistency](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=5&ved=0CEEQFjAEahUKEwjXpMOLr4_HAhXCK4gKHeBgBDY&url=http%3A%2F%2Fwww4.stat.ncsu.edu%2F~ghosal%2Fpapers%2Fbhurev.pdf&ei=3afAVZfCM8LXoATgwZGwAw&usg=AFQjCNHYi85F0w0V5Z-0OlRXttLf5u7AMw&sig2=3LlU_N7DdfYMCfR9ZNw4zQ&bvm=bv.99261572,d.cGU)
Answer: The MLE is known to be consistent under specific conditions, that means that the estimate converges (either in probability or almost surely) to the true value of the parameter $\theta_0$.
Bayesian parameter estimation updates the posterior of $f(\theta)$ and makes it narrower and narrower around $\theta_0$. In the end, you obtain a Dirac on $\theta_0$. The only assumption is that prior $f(\theta)$ was not zero for $\theta_0$.
Thus, you can see that both methods converge under specific conditions to the real value $\theta_0$. Therefore, they converge to the same results.
Comment: A famous reference for counterexamples in Bayesian consistency is [Diaconis and Freedman (1986)](https://projecteuclid.org/euclid.aos/1176349830).

MLE and Bayesian methods


Is vector $w$ in the span of $\{v_1,v_2,v_3\}$?

Question: Let $v_1 = (1,0,-1)^T$, $v_2 = (2, 1, 3)^T$, $v_3 = (4,2,6)^T$ and $w = (7,4,7)^T$
From what I understand, if I set up an augment matrix in the form
\begin{pmatrix}1&2&4&7\\
0&1&2&4\\
-1&3&6&7\\
\end{pmatrix}
And reduce it using Gaussian elimination, if it is consistent, $w$ is in fact in the span of $\{v_1,v_2,v_3\}$. Else, if it is inconsistent, $w$ does not span $\{v_1,v_2,v_3\}$
This, $w$ does not span $\{v_1,v_2,v_3\}$. Is this true?
Answer: You are correct. If $w$ were an element of $\operatorname{span}(v_1, v_2, v_3)$, then we could represent $w$ as $w=xv_1 + yv_2 + zv_3$.  Thus there'd be a solution to the matrix equation $$\pmatrix{1&2&4\\0&1&2\\-1&3&6}\pmatrix{x \\ y \\ z} = \pmatrix{7 \\ 4 \\ 7}$$
Solving this, we see that
$$RREF\left(\begin{array}{ccc|c}1&2&4&7\\
0&1&2&4\\
-1&3&6&7
\end{array}\right) = \left(\begin{array}{ccc|c}1 & 0 & 0 & 0\\ 0 & 1 & 2 & 0 \\ 0 & 0 & 0 & 1\end{array}\right) \\ \iff \begin{cases} x=0 \\ y+2z=0 \\ 0=1\end{cases}$$ but that last equation is never true so this system of equations has no solution.
Thus $w \not\in \operatorname{span}(v_1, v_2, v_3)$.
In other words, @tommy is wrong: $w$ is NOT a linear combination of those $3$ vectors.
Answer: yes as it is a linear combination of those 3 vectors


Why can mathematicians pick and choose axioms?

Question: Obviously, there need to be some 'self-evident' truths that we can't prove, but on which we base certain theorems; e.g. the axiom of choice lead to the well-ordering theorem (which could well be an axiom).
Essentially, what I'm asking is how do mathematicians know what is "so trivially true, that it is assumed to be true"?
For example, Playfair's axiom/the parallel postulate does not seem to be trivially true (at least to me, and from what I gather, many mathematicians tried to prove it), so why did was this axiomatised?
I understand that we can construct useful things from these unproved assumptions, like, for example, the reals, from the axiom of completeness, but, unless it is a defining property, how can one say for certain "statement  $X$ is unequivocally true"?
Finally, are there axioms yet to be discovered, and, if so, who determines their validity?
Comment: An axiom is not something which is true, but something which is assumed to be true and from which you derive conclusions. For a consistent theory you usually need several axioms. As soon as you need more than one you are faced with the question whether they are independent of each other and do not contradict each other. The challenge is to formulate a set of axioms as small as possible which implies results which correspond to our intuition.
Comment: To answer your title, mathematicians pick and choose axioms to simplify and define concepts elegantly. Also, it would be helpful to define "trivially true".
Answer: Since by definition no axiom can be proved using only the other axioms, the choice of axioms is somewhat arbitrary as you can always decide to work within a system with less or more axioms. Mathematicians therefore choose axioms based on how useful the results based on those axioms can be.
For instance, if we chose not to use the axiom of choice, we could not assume that a given vector space has a basis. Since a basis for a vector space is a very useful thing, assuming the axiom of choice whenever we deal with vector spaces is a common decision. You could still have a vector space without it, but it's properties would be far less useful than vector spaces axiomatized with  axiom of choice.
The same goes for the parallel postulate - thousands of years of mathematics used this as a basis for Euclidean geometry, trigonometry and so on. When a use case was found for non-Euclidean geometry, this postulate was removed from those use cases.
Ultimately, mathematics is all about creating structures that can be used - either to model real world problems, to further our understanding of existing structures, or to create new and interesting structures. The choice of axioms is just a means to an end, not a representation of some deeper truth.
Answer: A formalist perspective is that if something didn't satisfy the axioms of Euclidean geometry, then we wouldn't call it a Euclidean plane. If something doesn't satisfy Peano's axioms, then we won't call it a collection of natural numbers. And so forth.
Answer: Alternative idea of axiom: property verified by the structure we are interested in.


Comparing two dependent intra-class correlations (ICCs)

Question: We are measuring two waves from a biological signal.  As an example consider the ECG $P$ wave and $T$ wave.  From a single trace, the amplitude of both of these waves is measured.  We want to compare the inter-session reliability of the two waves; doing a second measurement a week later.  So in this example we have $P_1$, $P_2$, $T_1$ and $T_2$.  We expect, and have found, correlations between ($P_1$, $P_2$) ($P_1$, $T_1$) and all of the combinations.  $ICC_{2,1}$ for the $P$ wave ($P_1$, $P_2$) was $0.8$ and for the $T$ wave was $0.6$.  Confidence intervals for each ICC can be computed by bootstrap but how can we compare the test-retest reliabilities of the two waves?
Comment: Do $P_1$, $P_2$, $T_1$ and $T_2$ all refer to vectors of *exchangeable* values (exchangeable within a vector)? Or is there, for example, some sensible a priori pairing between the values in $P_1$ and $T_1$, so that the ordering of the values in each vector is *not* arbitrary?
Answer: Lu L, Shara NM. Reliability analysis: calculate and compare intra-class correlation coefficients (ICC) in SAS. Northeast SAS Users Group; 2007.
illustrate a method to compare 2 independent ICCs
In a similar fashion ou could calculate bootstrapped ICCs differences of paired observations and use a one sample t test.
This can easily be implemented in R using the boot and ICC packages
Also try reading this.


How to flush headers in Flask before sending HTTP 204?

Question: I have a Flask REST service where one POST action may take a long time (for instance thirty seconds) before returning an HTTP 204 No Content.
The service is hosted on two servers acting as a failover, with Nginx deciding which server should be used, Nginx configuration being:
upstream demo-failover {
    server http-demo-primary.example.com weight=1000 max_fails=0;
    server http-demo-failover.example.com backup;
}

server {
    server_name demo.example.com;
    proxy_next_upstream error timeout invalid_header;
    proxy_connect_timeout 2;
    proxy_redirect off;
    proxy_read_timeout 240s;
}

When doing the concerned POST request, Nginx transmits it to http-demo-primary, and since it doesn't receive any response within the two seconds, abandons and does another request to http-demo-failover. Obviously, this is not suitable: since the first machine is up and running, Nginx should not failover to the second machine.
I imagine that sending headers—actually any header will do the trick—from the service will be enough for Nginx to understand that the machine is active and that it shouldn't failover to another one.
I know how to do it in PHP and ASP.NET. On the other hand, the only similar thing I can find in Flask is Streaming Contents section of the official documentation, which seems unsuitable in my case, where the response is HTTP 204.
How should I flush some headers in a context where the entity-body returned by the server is empty?
Answer: Having long-running HTTP requests is generally a bad idea.  Instead, consider quickly returning an HTTP 202 Accepted response and then performing the long-running processing asynchronously.  If the client needs to know when the request has completed, you can return a Location header with a URL that the client can poll for the status of the task.


how to prove the integral converges

Question: Suppose $$I=\lim_{x\rightarrow\infty}\lim_{b\searrow0}\int_{b}^{x}{g(y)dy}$$ exists and is finite, where $g$ is a continuous function from $\mathbb{R}^{+}$ to $\mathbb{R}$. Prove $$\lim_{x\rightarrow\infty,b\searrow 0}{\int_{b}^{x}{g(y)dy}}$$ exists and equals $I$.
Can someone give me hints? I do not know where to start it.
Comment: Your two limits of integrals appear to be them same.
Comment: I guess the OP asks to prove that taking the limit for $(x,b)\to(\infty,0^+)$ *jointly* is the same as taking it first wrt $b$ and then wrt $x$.
Answer: EDIT: Usually one likes to see "why" something is true intuitively and then translate that understanding into a proof. Here I just followed the definitions and found I was done - never did understand "why" it was so. Until now: It's a special case of the following obvious fact:
Obvious Fact If $\lim_{x\to a}\left(\lim_{y\to b}(F(x)+G(y))\right)=I$ then $\lim_{(x,y)\to(a,b)}(F(x)+G(y))=I$.

Original:
Inserting some parentheses to make things absolutely clear: You're assuming that
$$I=\lim_{x\rightarrow\infty}\left(\lim_{b\searrow0}\int_{b}^{x}{g(y)dy}\right),$$
and you want to show that $$\lim_{(x,b)\to(\infty,0^+)}{\int_{b}^{x}{g(y)dy}}=I,$$right?
My first reaction was to say this does not follow. The corresponding implication with a function $F(x,b)$ in place of $\int_b^x g$ is not true. But of course, as I realized quickly when I started to construct a counterexample,  $\int_b^x g$ cannot be an arbitrary function of $x$ and $b$.
Suppose $I=0$ for simplicity and assume $\epsilon>0$. There exists $A$ so that
$$\left|\lim_{b\to0}\int_b^xg\right|<\epsilon\quad(x\ge A).$$It follows that
$$\left|\int_x^yg\right|<2\epsilon\quad(A\le x\le y).$$(Given $x,y\ge A$, choose $b$ so that $|\int_b^x|<\epsilon$ and $|\int_b^y|<\epsilon$.)
Now choose $\delta>0$ so that $$\left|\int_b^Ag\right|<\epsilon\quad(0<b<\delta).$$(There exists such a $\delta$ because the above implies that $|\lim_{b\to0}\int_b^A|<\epsilon$.)
If $x\ge A$ and $0<b<\delta$ then $$\left|\int_b^xg\right|\le\left|\int_b^Ag\right|+\left|\int_A^xg\right|<\epsilon+2\epsilon=3\epsilon.$$
Comment: Hint: If $|\lim_{b\to0}\int_b^x|<\epsilon$ then $|\int_b^x|<\epsilon$ if $b$ is small enough. Similarly for $y$. Now if $b$ is small enough that both of those integrals are less than $\epsilon$ in absolute value their difference is less than $2\epsilon$.
Comment: So for my problem, I can define $f(y)=g(y)-\frac{I}{x-b}$?
Comment: @81235 I have no idea what you're talking about, sorry...
Comment: My question is what if $I\neq 0$
Comment: Another question is how you have $|\int_{b}^{x}|<\varepsilon$? From $|\lim_{b\rightarrow 0}\int_{b}^{x}{g}|<\varepsilon$? It is kind of weird that the integral $|\int_{x}^{y}{g}|$ can be very small if $x$  and $y$ goes to infinity.
Comment: Let $h$ be any function with $\int h=I$ and such that $h$ vanishes on $(0,1)$ and vanishes on $(2,\infty)$. The proof I gave applies to $g-h$ in place of $g$, and then the conclusion for $g-h$ implies the conclusion for $g$.

how to prove the integral converges


How do I find a rhythm that goes under a melodic line?

Question: I have to accompany a singer on guitar for a wedding and I am having trouble finding a good rhythmic pattern that fit nicely under the melody.
What should I pay attention to regarding the melodic line to figure out what I could play ? How do you determine what beat should be emphasize, and what beat should not ?
For reference the song is "Oh happy day" and I'm using this music sheet.
Answer: There is no one 'correct' or 'best' rhythm pattern here. Start by simply strumming 4 down strums in each bar, as the song is in 4/4, and then try various little changes to that. Such as catching the strings, or at least the top 3 or 4, as you move the pick back after each down strum.
That gives several options. D,D,D,D is the original. Then you could get really busy with DU,DU,DU,DU, which is too much - and doesn't allow much time for any chord changes. D,DU,DU,D works well, but by trying out the options, you'll find two or three that work well for you. By keeping the basic 4 downstrums in each bar, changing on the fly will not interrupt the flow of your strumming arm. Good luck - and practise with the singer before, if poss!
Comment: Yes, consider that, and try it out. Not all the time, but experiment. Bear in mind that the anacrucis will generally come on an upstrum; don't do it with a down, as it'll interrupt the arm pattern. Doing that will cut your chord changing time by half, though. Unless you're already a really good rhythm player, whereby you can swap the pattern around. But then, you probably wouldn't be asking...!
Comment: Is sticking to the "one bar, one chord" bit required ? Or should I consider changing chords in a more "syncopated" way ? like changing from C to G on the last off-beat of the  bar labelled C ?


Script abrir somente após tempo determinado

Question: Eu tenho um script, porém ele abre assim que é carregado. Eu gostaria de fazer com que ele executasse após 10 segundos e abrisse juntamente com minha div, ela está assim:

    CONTEUDO

Existe algum método dele não executar na hora após o carregamento do site e esperar esses 10 segundos? Obrigado
Comment: Podes explicar melhor "e abrisse juntamente com minha div"?
Answer: Bem olhei aqui está tudo correto, funciona corretamente seu código testei no Chorme mais novo e no IE 11, talvez o resto dos códigos de sua página esteja interferindo. Porém eu tenho ressalvas para seu código que seriam:
1) Acredito que a propriedade do CSS que 'esconde' sua DIV deveria estar no próprio elemento, digo isso porque dependendo do tempo de execução do navegador, até começar a carregar o JS o conteúdo pode aparecer, e estando no próprio elemento a chance disso ocorrer é mínima. Então ficaria assim:

CONTEUDO

2) Dependendo do tanto de conteúdo que existe na sua página fora esse códigos pode ser que o conteúdo da DIV seja ou não mostrado no tempo correto, sendo assim eu verificaria se todo o conteúdo foi executado e após isso disparava o evento de 10 segundos.
Somando essas duas observações seu código ficaria assim:

CONTEUDO

Comment: Acho que me expressei mal na pergunta. O script que eu quero que abra apos 10 segundos não é esse dai nao..
Comment: Opa amigo. Então minha div está funcionando corretamente, só coloquei ela pra exemplificar mesmo. rs
Comment: @SK15, perfeito sua resposta, estava com dúvidas quanto a isso!
Answer: Uma solução é adicionar o JS dinamicamente à página.
Clique em "Executar" logo abaixo, e veja uma demonstração funcional deste código:

var delayedScript =document.createElement('script');

delayedScript.setAttribute( 'type','text/javascript');
delayedScript.setAttribute( 'src','http://codepen.io/tholman/pen/EpfLs.js' );

window.onload = function() {
  var minhaDiv = document.getElementById("mame");
  window.setTimeout( function() {
    minhaDiv .style.display = 'block';
    document.getElementsByTagName("head")[0].appendChild( delayedScript );
  }, 5 * 1000 )
}
Aguarde o Timer...

    <canvas id="canvas"></canvas>

O JS externo é executado somente quando o timer completa. Se precisar de algo mais específico, compensa ajustar o JS para ter maior controle, em vez de "atrasar" ele.
Créditos do JS externo: Tim Holman


Get GCM registration id of already registered device

Question: I am using GCM with my application. It is working fine. I am storing it in database also. But now as per my requirement, I want GCM registration id of already registered device at later time. So Is there any way to get this ? I don't want to store it in Cookies or in Session.
Answer: Yes, implementing your remote server (as this infrastructure requires) in your favorite language and storing it somewhere: your MySQL database, a file, or whatever you want.
Resuming, you need to implement a web-service that will store any registered GCM ids somewhere (for instance, a local MySQL database), so it can later retrieve it. Doing it this way, you also need to care about timeouts (for instance, if a client doesn't send a keepalive within X time, just delete it from the database).
Comment: sorry to say, but this is not my solution. Is there any way by which I get same id again from GCM ?
Comment: I'm sorry to say, but this is the way it works. And yes, you can get the same ID again using the same device. Usually Google will grant the same ID for the same device for an undefined amount of time (which might be days, weeks or months).
Comment: `String regid = gcm.register("YOUR-SENDER-ID");`. This will return you the GCM id.
Answer: Calling gcm.register multiple times (without calling gcm.unregister) will return the same registration ID. However, there is no reason to do that - it causes an unnecessary communication of your app with the GCM server.
You can store the registration ID in the app's shared preferences, as is shown in the official GCM demo app :
/**
 * Stores the registration ID and the app versionCode in the application's
 * {@code SharedPreferences}.
 *
 * @param context application's context.
 * @param regId registration ID
 */
private void storeRegistrationId(Context context, String regId) {
    final SharedPreferences prefs = getGcmPreferences(context);
    int appVersion = getAppVersion(context);
    Log.i(TAG, "Saving regId on app version " + appVersion);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(PROPERTY_REG_ID, regId);
    editor.putInt(PROPERTY_APP_VERSION, appVersion);
    editor.commit();
}

Whenever you need it in your app, you get it from the shared preferences (unless a new version of your app is installed, in which case Google recommend to invalidate the stored registration ID and call gcm.register again) :
/**
 * Gets the current registration ID for application on GCM service, if there is one.
 *

 * If result is empty, the app needs to register.
 *
 * @return registration ID, or empty string if there is no existing
 *         registration ID.
 */
private String getRegistrationId(Context context) {
    final SharedPreferences prefs = getGcmPreferences(context);
    String registrationId = prefs.getString(PROPERTY_REG_ID, "");
    if (registrationId.isEmpty()) {
        Log.i(TAG, "Registration not found.");
        return "";
    }
    // Check if app was updated; if so, it must clear the registration ID
    // since the existing regID is not guaranteed to work with the new
    // app version.
    int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
    int currentVersion = getAppVersion(context);
    if (registeredVersion != currentVersion) {
        Log.i(TAG, "App version changed.");
        return "";
    }
    return registrationId;
}


UPDATE from SELECT statement

Question: Sorry, I know nothing of SQL.
Please can somebody give me the SQL command to perform the following:

UPDATE field "difficulty"
of TABLE "data"
with the value in field "rank" form the table "prime"
WHERE the value of field "field2" of table "prime" = value of the field "english" of table "data"

I am using Sqlite.
Thanks for the help.
Comment: This is not a "we do the work for you" site. Show some effort.
Comment: http://www.w3schools.com/sql/ everything you need to know about sql, it isn't that hard to do this simple query.
Comment: Update with a subselect "too localized" ?  You gotta be kidding... I'll vote to reopen *sigh*
Answer: This untested (obviously, because I don't have your schema), but something like this:
<code>UPDATE data SET difficulty = (SELECT rank FROM prime WHERE field2 = data.english);
</code>

UPDATE from SELECT statement


Can I use a different dilimter other than EOF or EOL when reading a file

Question: I want to parse a file and use 2 'new line' (\n) as a dilimiter instead of EOL and add that into a string object.
Here is the algorithm -
1. While end of file is not reached
2. Read a file until you hit 2 \n's or eof is reached
  put that contents as a string to a List object.
3. go to 1.

Answer: You can use Scanner.useDelimiter() method.
public Scanner useDelimiter(String pattern)

Sets this scanner's delimiting pattern to a pattern constructed from
  the specified String.

According to JLS new line is

LineTerminator:
the ASCII LF character, also known as "newline"

the ASCII CR character, also known as "return"

the ASCII CR character followed by the ASCII LF character

Answer: You can use any delimiter you want.  If you use Scanner you can set the delimiter.
Note: a new line is usually (\r\n|\r|\n) to support three variations of a new line.
In your case the simplest solution may be to do
String[] paragraphs = FileUtils.readFileAsString(filename)
                               .split("(\r\n|\r|\n){2}");


Check for any values in set

Question: Suppose I have the following set:
things = {'foo', 'bar', 'baz'}

I would like to find out if either foo or bar exists in the set. I've tried:
>>> 'foo' in things or 'bar' in things
True

This works, but is there not a more Pythonic way of doing this check without having multiple or statements? I can't find anything in the standard Python set operations that can achieve this. Using  {'foo', 'bar'} <= things checks for both, but I want to check for either of them.
Answer: As long as you're using sets, you could use:
if {'foo','bar'} & things:
    ...

& indicates set intersection, and the intersection will be truthy whenever it is nonempty.
Answer: Talking sets, what you actually want to know is if the intersection is nonempty:
if things & {'foo', 'bar'}:
    # At least one of them is in

And there is always any():
any(t in things for t in ['foo', 'bar'])

Which is nice in case you have a long list of things to check. But for just two things, I prefer the simple or.
Answer: You are looking for the intersection of the sets:
things = {'foo', 'bar', 'baz'}

things.intersection({'foo', 'other'})
# {'foo'}

things.intersection('none', 'here')
#set

So, as empty sets are falsy in boolean context, you can do:
if things.intersection({'foo', 'other'}):
    print("some common value")
else:
    print('no one here')

Answer: You can use set.isdisjoint:
if not things.isdisjoint({'foo', 'bar'}):
    ...

Or set.intersection:
if things.intersection({'foo', 'bar'}):
    ...

Or any:
if any(thing in things for thing in ['foo', 'bar']):
    ...

Or stick with or, because very often that's actually the most readable solution:
if 'foo' in things or 'bar' in things:
    ...

Answer: things = {'foo', 'bar', 'baz'}
any([i in things for i in ['foo', 'bar']])

Check for any values in set


Is there a db migration tool in spring without sql query?

Question: I'm a python backend developer, but this time I have to use java, spring.
There is a migration tool in python, called alembic, doesn't demand knowledge of sql query, because it can be migrated without any sql query.
So, I'm finding a migration tool in spring, java, but I haven't found it yet.
Of course, I've been known flyway migration tool, but as I know, it works with sql query.
Is there a migration tool using without sql query?
Answer: An alternative to flyway is liquibase. It can take in class or yml files. Here's a basic tutorial from Baeldung https://www.baeldung.com/liquibase-refactor-schema-of-java-app


CDN Module and Image Styles

Question: Yesterday I installed the CDN Module using Amazon Cloudfront and magically everything worked as expected. I was quite happy.
This morning I was showing off my new improved CDN enabled website to a colleague and most (not all) of the image style generated images were broken! And to confuse things even further, when I opened a broken image in a browser window the file was actually Drupal's Access Denied Page.
Digging into this further, I found that the /sites/default/files/styles/STYLE folder was empty. This seems strange to me since it was not empty yesterday when all of these files were uploaded to Amazon. What could be deleting the styles/STYLE folder?
So, I installed the Image Style Flush Module and flushed the style in question. Still nothing, but it makes sense since the CDN module is re-writting all of the links to static content and Drupal doesn't actually get hit to re-create the missing image. How the Access Denied page was uploaded is a mystery as well.
Next, I disabled the CDN module and cleared the cache. Reloading the page recreated all of the images and everything works as expected. But, I need to use the CDN as it's a requirement of the project.
Drupal 7.27, CDN module latest version.
I could blacklist the /sites/default/files/styles/STYLE folder, but that represents almost 30 images that are loaded on every page.
Any advice would be greatly appreciated.
Comment: It's a setting in CloudFront.  You need to tick a checkbox related to query parameters.  If you figure it out, write it up as an answer.
Comment: Do you see the inbound request in your Apache logs?  I had a CloudFront problem a few months ago where I was getting malformed headers, and my Apache was denying the request.  I think an Apache upgrade fixed it (I think that server was on the Apache 2.2 tree).
Comment: There are access denied errors in the dblog and 403 errors in the apache log. The access denied errors in the dblog are missing the image style token...I'll look into that.
Comment: setting updated, waiting....I'll let you know if that takes care of it.
Comment: Good call MPD - everything is working now! I'll write that up as an answer
Answer: AD MPD noted in the comments, the issue is how Amazon Cloudfront handles the image style URL, specifically the ?itok query string.
So, when creating your distribution in Cloudfront, make sure you set "Forward Query Strings" to "Yes". See screenshot:
Comment: Confirmed that this was the solution for me. The only reason to add anything here is to note that the option to forward query strings is now labeled **Query String Forwarding and Caching**. The default is none. I chose **Forward all, cache based on all**. The alternative was **Forward all, cache based on whitelist**.

CDN Module and Image Styles


How to display data using FlatList and webView in react native?

Question: I have created flatList and I am passing array of objects. Each object has title and data array. In renderItem of FlatList I am trying to display text which is title and  but it gives error as null. How can I display data using flatList i.e I want to display title and data key from each array of objects.
Example data:

Code:
<FlatList
                    data={specificationsData}
                    showsVerticalScrollIndicator={false}
                    renderItem={({item}) =>
                    <View style={styles.flatview}>
                        <Text style={styles.name}>{item.title}</Text>
                        <WebView originWhitelist={['*']}
                        source={{ html: item.data }}/>  <--- gives error
                    </View>
                    }
                    />

I want to display html data from each object and title so it displays item.title as text properly but item.data doesn't work if I pass item.data in WebView how can I display the HTML content using webView and FlatList ?
Comment: Are you sure you need a webview? this seems like it might be unnecessarily complicated
Comment: @kai Yes without webView how can I display html content ? If I use ` {item.data}` then it displays ` ......` on the screen?
Answer: Instead of a webView, I suggest you try https://github.com/archriss/react-native-render-html library to display HTML content.
Maybe something like this:
...
import HTML from 'react-native-render-html';
...
<FlatList
    data={specificationsData}
    showsVerticalScrollIndicator={false}
    renderItem={({item}) =>
    <View style={styles.flatview}>
        <Text style={styles.name}>{item.title}</Text>

    </View>
    }
/>

Comment: I have tried it on ios but it is breaking some content
Comment: Can you share the screenshot of the app and the console.log of your item.data? It should work, I use it in my projects. Lets see what you're getting and I'll help you fix that.


PHP add another array

Question: I'm trying to render a Highcharts column drilldown with dynamic values retrieved from database.
And I have a php query like this:
$query = mssql_query("SELECT count(create_at) as create,  month(create_at) as month, year(create_at) as year
                FROM tblCrew
                WHERE create_at >=  '01 JUL 2011' AND create_at <=  '31 JUL 2013'
                GROUP BY  month(create_at), year(create_at)
                ORDER BY  year(create_at) ASC, month(create_at) ASC ");

And to get the result I looped it like this:
while ($data = mssql_fetch_array($query))
            {
                if (!isset($case[$data['year']])) {
                                $case[$data['year']] = array(
                                    'name' => $data['year'],
                                    'data' => array()
                                );
                    }

                    $case[$data['year']]['data'][] = array(
                        $data['month'],
                        $data['create']
                    );

            }

And this is the results:
$case = Array([2011] => Array
    (
        [name] => 2011
        [data] => Array
            (
                [0] => Array ( [0] => JUL [1] => 166 )
                [1] => Array ( [0] => AUG [1] => 144 )
                ........
                .......
                [5] => Array ( [0] => DEC [1] => 124 )
            )
    )

[2012] => Array
    (
        [name] => 2012
        [data] => Array
            (
                [0] => Array ( [0] => JAN [1] => 143 )
                [1] => Array ( [0] => FEB [1] => 177 )
                ........
                .......
                [5] => Array ( [0] => DEC [1] => 132 )
            )
    )

[2013] => Array
    (
        [name] => 2013
        [data] => Array
            (
                [0] => Array ( [0] => JAN [1] => 166 )
                ........
                .......
                [5] => Array ( [0] => JUL [1] => 124 )
            )
    )

)
And now I am trying to add another array where I will sum up the data per year and put it in another array. Like the example below.
$total[] = Array[{name: '2011', total: '1520'}, {name: '2012', total: '2241'}, {name: '2013', total: '1864'}]

Answer: You can add another array, initialize it the same time you initialize $case[$data['year']] and add values while looping the results :
$total = array();
while ($data = mssql_fetch_array($query))
        {
            if (!isset($case[$data['year']])) {
                            $case[$data['year']] = array(
                                'name' => $data['year'],
                                'data' => array()
                            );
                            $total[$data['year']] = array(
                                'name' => $data['year'],
                                'total' => 0
                            );
                }

                $case[$data['year']]['data'][] = array(
                    $data['month'],
                    $data['create']
                );
                $total[$data['year']]['total'] += $data['create'];

        }
print_r($total);

PHP add another array


Imagem quebrada - Laravel 4

Question: Tenho uma imagem em uma página, inseri da seguinte forma:

A imagem aparece normalmente em páginas com endereço

/pagina

.
Porém quando a URL está no formato

/pagina/subpagina

a imagem aparece quebrada.
Como posso resolver isso?
Comment: melhor explicar o que seria esse "imagem quebrada".
Entenda que ao usar img/logo.png significa que em /pagina ele ira buscar a imagem em /pagina/img e quando a url for /pagina/subpagina em /pagina/subpagina/img a menos que existam regras de reescrita que forcem urls /img para outro caminho.
Tente usar `` ou use alguma função de Path do Lavarel para gerar a url certa para a imagem.
Comment: Obrigada. `` funcionou
Answer: O certo seria você usar um método do Laravel para imagens.
Tem duas formas:
{{ HTML::image('img/logo.png') }}

Ou

Dessas maneiras funcionam em qualquer página, visto que esses métodos levam em conta a pasta public como padrão para imagens, scripts e styles.
Comment: Ninguém deu +1. É exatamente isso. Boa resposta.

Imagem quebrada - Laravel 4


How can I exclude a specific child category post from a parent category?

Question: I'm trying to display related post by category, but I wanted to exclude a specific category, but it's not working and I don't know how to tackle it.
<?php
    $terms = get_the_terms( $post->ID, 'category' );

    if ( empty( $terms ) ) {

        $terms = array();
    }

    $term_list = wp_list_pluck( $terms, 'slug' );

    $related_args = array(
        'post_type' => 'post',
        'posts_per_page' => 5,
        'post_status' => 'publish',
        'post__not_in' => array( $post->ID ),
        'orderby' => 'rand',
        'exclude' => 9,
        'tax_query' => array(
            array(
                'taxonomy' => 'category',
                'field' => 'slug',
                'terms' => $term_list
            )
        )
    );

    $my_query = new WP_Query($related_args);

    if( $my_query->have_posts() ) {

        while ($my_query->have_posts()) :

            $my_query->the_post();
            the_title();
            echo "
";

        endwhile;
    }
    wp_reset_query();
?>

Answer: Let's assume that you want to exclude category ID 9. then just add the follows tax query in your $related_args -
'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'category',
            'field'    => 'slug',
            'terms'    => $term_list,
        ),
        array(
            'taxonomy' => 'category',
            'field'    => 'term_id',
            'terms'    => array( 9 ),
            'operator' => 'NOT IN',
        ),
    ),

Comment: This works even for where the post is in a child category of the category id
Answer: Use minus (-) sign with cat id that you want to exclude
$related_args = array(
    'post_type' => 'post',
    'posts_per_page' => 5,
    'post_status' => 'publish',
    'post__not_in' => array( $post->ID ),
    'orderby' => 'rand',
    'cat' => '-9'
);

Check this link:
https://codex.wordpress.org/Class_Reference/WP_Query
Find: Exclude Posts Belonging to Category
See Screenshot


values of variables to add in an array after I click the submit button

Question: how can I place the value of a variable in an array after I click the submit button? The submit button will the one to trigger the arrayholder.push().
Variables that should be added to the array are those buttons that is clicked.
JAVASCRIPT
qty1=0;
qty2=0;
qty3=0;
qty4=0;
arrayholder=new Array();

$("#id1").click(function(){
qty1=qty1+1;
$("#status").html(qty1);
});

$("#id2").click(function(){
qty2=qty2+1;
$("#status").html(qty2);
});

$("#id3").click(function(){
qty3=qty3+1;
$("#status").html(qty3);
});

$("#id4").click(function(){
qty4=qty4+1;
$("#status").html(qty4);
});

HTML CODE
    <button id="id1">ADD 1 QUANTITY FROM id1</button>
    <button id="id2">ADD 1 QUANTITY FROM id2</button>
    <button id="id3">ADD 1 QUANTITY FROM id3</button>
    <button id="id4">ADD 1 QUANTITY FROM id4</button>

<input type="submit" />

Comment: Do you only want to add to the array if the Variable Value has changed? For example only if qty1 is not 0 any more?
Comment: Instead of using `qty1=qty1+1;`, use `qty1++;`. It means "Increment `qt1` with 1".
Comment: @GeenHenk, but how can I add it to an array but first I must determine if the button was clicked. And the result will be added to the array after I clicked the submit button.
Comment: @SajunaFernando. YES!!
Comment: I need to check if the qty value is not 0 anymore. that's the time that I will add it to the array, after I clicked the submit button.
Comment: Check my answer. Is that what you mean?
Comment: I it possible that, I can determine the sequence of clicks before I add it to the array? for instance, I first clicked the qty4 before qty3. So, I need to add qty4 to the array first then followed by qty3. And another scenario. I first clicked the qty4 before qty3. So, I need to add qty4 to the array first then followed by qty3.And I clicked the qty4 again. But previously qty4 was clicked first before qty3, so qty4 must come in the array first.
Answer: Instead of having input of type "submit", change it to type "button" and then:
<input id="abc" type="button" click="pushMe" />

function pushMe()
{
  arrayholder.push(qty1);
  document.getElementById("form1").submit();
}

Comment: I need determine the sequence of clicks before I add it to the array? for instance, I first clicked the qty4 before qty3. So, I need to add qty4 to the array first then followed by qty3. And another scenario. I first clicked the qty4 before qty3. So, I need to add qty4 to the array first then followed by qty3.And I clicked the qty4 again. But previously qty4 was clicked first before qty3, so qty4 must come in the array first. @GregOks
Comment: So the first click is what counts? if you click 4 and then 3 and then 4 again and then 3 again. it will still be 4 and then 3 in the array? Meaning, only the first click counts?
Answer: Try this,
$('input[type="submit"]').on('click',function(){
    arrayholder.push(qty1,qty2,qty3,qty4);
    console.log(arrayholder);
    return false;
});

Demo 1
To distinguish the button count you can push key-value pairs like
$('input[type="submit"]').on('click', function () {
    arrayholder.push({'qty1':qty1,'qty2':qty2,'qty3':qty3,'qty4':qty4});
    console.log(arrayholder);
    return false;
});

Demo 2
Comment: But how can I determine if the button was clicked? And the buttons that I clicked are the only one that should be added to the array, not the whole variables.
Answer: Why dont you do this?
$("#id1").click(function(){
    arrayholder.push(qty1++)
});

This will push the value to array when you click the button.
Comment: The solution that i've given will add the values sequentially but not on submit. If you want to do so, you've to maintain an array to get the sequence of buttons and on submit you have to loop the array and get the values of the variables and push it to the result array
Comment: But i need to push it after I click the submit button. SO that I can determine which button is clicked. And only the clicked button iwll be added to the array.
Comment: Do you want to find which button was clicked?
Comment: Do you want to do like @sajuna Fernando did?
Comment: yes sir.. and also, I need to determine the sequence of clicks.
Comment: And can I determine the sequence of clicks before I add it to the array? for instance, I first clicked the qty4 before qty3. So, I need to add qty4 to the array first then followed by qty3. And another scenario. I first clicked the qty4 before qty3. So, I need to add qty4 to the array first then followed by qty3.And I clicked the qty4 again. But previously qty4 was clicked first before qty3, so qty4 must come in the array first.
Comment: @marikkaniChelladurai.. Can you show me how. Coz, I'm been trying to do that, even before I posted this question. And I still failed to do so.
Answer: I guess check if the variable value has changed?
<input id="submitButton" type="button" click="submitForm" />

function submitForm()
{

  if(qty1 != 0){ arrayholder.push(qty1); }
  if(qty2 != 0){ arrayholder.push(qty2); }
  if(qty3 != 0){ arrayholder.push(qty3); }
  if(qty4 != 0){ arrayholder.push(qty4); }

  document.getElementById("form1").submit();
}

Comment: Sorry but i dont think thats possible my friend. I confused my self thinking you wanted the one thats clicked the most to appear on top in which case you just need to sort the array.. To do what you say you will need to add to the array at the point of click. Javascript does not allow Variables to hold Variable names so i cannot think of a proper way to do this
Comment: I think this must be the answer. I need to check first if the value is already change. But can I determine the sequence of clicks before I add it to the array? for instance, I first clicked the qty4 before qty3. So, I need to add qty4 to the array first then followed by qty3.
Comment: And another scenario. I first clicked the qty4 before qty3. So, I need to add qty4 to the array first then followed by qty3.And I clicked the qty4 again. But previously qty4 was clicked first before qty3, so qty4 must come in the array first.
Comment: Ohh I see.. But still, your idea helps me a bit.
Answer: look at this fiddle
http://jsfiddle.net/GWAw4/2/
$(".TheBtn").click(function() {
   $(this).find("span").text(+$(this).find("span").text()+1);
});

$("#submit").click(function() {
     var arrayholder = [];
     $.each($(".TheBtn"),function() {
           arrayholder.push(+$(this).find("span").text());
     });
    console.log(arrayholder);
});

hope it does what you want :)
check console for your array result!
Comment: let me check it first.. :)
Comment: its awesome but it's not what I'm looking for.
Comment: I need determine the sequence of clicks before I add it to the array? for instance, I first clicked the qty4 before qty3. So, I need to add qty4 to the array first then followed by qty3. And another scenario. I first clicked the qty4 before qty3. So, I need to add qty4 to the array first then followed by qty3.And I clicked the qty4 again. But previously qty4 was clicked first before qty3, so qty4 must come in the array first.
Answer: Change type="submit" to type="button" and add to it a click listener.
Push the value in the array and then submit the form with submit() function.
$("#submitButton").click(function(){
    //YOUR CODE HERE
    ....
    document.getElementById("yourform").submit();
});

Comment: But I need to click the submit button first before I add it to the array.
Comment: Submit or button doesnt matter if you want to submit a form. Submit is beter IMO.
Comment: Tell me please why the negative votes when all the people are posting my same answer....
Comment: Your explaining how to submit the form on a click event handler. Not the question that is asked. The question is how to push the values on to the array if the specific variables have been set or in other words only if the button was clicked.
Comment: @Sajuna Fernando to me the question is about how to push values before form is submitted, not how to push the values in the array, however it's ok, thank for the explanation