How to get the username of a logged in user and compare it to get the id

Question: I want to be able to get the username of the logged in user in my C# ASP.net application so I can get the ID of that user. I then want to perform an edit so they can apply to be part of an appointment.
With my current code, I click the link and I just get a HTTP 400 error. I have debugged this and the ID is coming through as the correct value. Is there any reason that its not being attached to the url?
// GET:
    public ActionResult VolunteerCeremony(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        string userName = string.Empty;

        //if (System.Web.HttpContext.Current != null &&
        //    System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
        //{
        //    System.Web.Security.MembershipUser usr = System.Web.Security.Membership.GetUser();
        //    if (usr != null)
        //    {
        //        userName = usr.UserName;
        //    }
        //}

        var getVolunteerId = (from u in db.Volunteers
                              where WebSecurity.CurrentUserName == u.Username
                              select u.VolunteerId).FirstOrDefault();

        Volunteer volunteer = db.Volunteers
            .Include(p => p.Appointments)
            .Where(i => getVolunteerId == id)
            .FirstOrDefault();

        if (volunteer == null)
        {
            return HttpNotFound();
        }
        PopulateAssignedCeremonyData(volunteer);
        return View(volunteer);
    }

    // POST: /Player/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult VolunteerCeremony(int? id, string[] selectedOptions)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        var getVolunteerId = (from u in db.Volunteers
                              where WebSecurity.CurrentUserName == u.Username
                              select u.VolunteerId).FirstOrDefault();

        var updateVolunteerWithCeremony = db.Volunteers
            .Include(p => p.Appointments)
            .Where(i => getVolunteerId == id)
            .Single();

        try
        {
            UpdateVolunteerCeremonies(selectedOptions, updateVolunteerWithCeremony);

            db.Entry(updateVolunteerWithCeremony).State = EntityState.Modified;
            db.SaveChanges();

            return RedirectToAction("Index");
        }
        catch (RetryLimitExceededException /* dex */)
        {
            //Log the error (uncomment dex variable name and add a line here to write a log.
            ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
        }

        PopulateAssignedCeremonyData(updateVolunteerWithCeremony);
        return View(updateVolunteerWithCeremony);
    }

EDIT This is where I'm calling the method
else if(Request.IsAuthenticated && HttpContext.Current.User.IsInRole("Volunteer"))
                    {

@Html.ActionLink("Appointments", "Create", "Appointments")

@Html.ActionLink("Join Ceremony", "VolunteerCeremony", "Volunteers")

                    }

EDIT 2 Here's my ViewModel that I used for the many to many relationship I have:
public class VolunteerCeremonyVM
{
    public int AppointmentId { get; set; }
    public string DetailsOfAppointment { get; set; }
    public bool Assigned { get; set; }

    public VolunteerCeremonyVM()
    {
        this.AppointmentId = AppointmentId;
        this.DetailsOfAppointment = DetailsOfAppointment;
        this.Assigned = Assigned;
    }

}

Comment: "so I can the ID of that user" what you mean there ?
Comment: what type of authentication is use for eample for windows authentication you can use Request.LogonUserIdentity.Name.Split('\\')[1]
Comment: @dimmik sorry I mean get the id
Comment: "It isn't getting the ID from my LINQ query even though I debugged it and the ID is coming through" - this is a rather confusing sentence. You seem to be saying the ID isn't coming through but that when you debug it is - can you be more clear on this? Does it work when you debug but not when you don't? Also you say "Is there any reason that its not being attached to the url?" but I am unclear on what part of your code is actually trying to put this ID in any kind of url....
Comment: @Chris I just edited my question as it was very confusing. I essentially copied the edit method and modified as they were similar. When I press a button, I want the volunteer to get to this method but its not going onto the url like it would when I press edit
Comment: @AnnaDoe I'm assuming the problem is in your POST method, is that correct?

Can you include the code where you generate the POST form and/or the call to the POST action? Depending on the setup, it's most likely not passing the ID through correctly.
Comment: Hi @ScottBaldric please find the edit updated with the details requested
Comment: @AnnaDoe Thanks for the followup. ActionLink generates a GET request. If you want access to the POST version of VolunteerCeremony you will need to have an Html.BeginForm() somewhere that starts a form for submitting the form with its selected options. Do you have code showing that? Also, just to clarify, is the problem with the first method, the second method, or both?
Comment: @ScottBaldric both methods work fine, when I click the link, it brings me a 400 error. I then put the ID of the current user in and it takes me to that page, VolunteerCeremony, and allows me to view and mess around with the data
Comment: @ScottBaldric I have been getting a null pointer with the links also
Comment: @AnnaDoe Check my answer and let me know how it works. The most likely issue is that you have not told the ActionLink's or the Forms the ID that you're passing along.

Without knowing more about where the Null Reference Exception is occurring, I can't help with that. I would recommend opening a new question if you can't find it detailing your reproduction steps. I would also encourage you to read the following link: https://stackoverflow.com/help/how-to-ask
Answer: Based on further clarification, you will want to update your ViewModel to include a VolunteerId. So it should look something like:
public class VolunteerCeremonyVM
{
    public int AppointmentId { get; set; }
    public string DetailsOfAppointment { get; set; }
    public bool Assigned { get; set; }
    public int VolunteerId { get; set; }
}

Notice that I removed the default constructor as it wasn't doing anything. When you construct the object you can use code like the following:
var model = new VolunteerCeremonyVM {
    AppointmentId = 10,
    VolunteerId = 50,
    //etc
};

As this will set all of the properties after the basic object is constructed.
Then, you will want to pass this view model into the view that is generating your action links like so: return View(model); in whatever controller action you're using.
Inside the view, you will make use of this new information. Specifically, the Html.ActionLink method requires that any extra parameters are passed to it in a route dictionary. It uses this route dictionary to build the URL that is generated for the anchor tag. You can call Html.ActionLink with an anonymous object for its fourth parameter to specify the route dictionary. The id will be the name of the parameter and Model.VolunteerId will be the value of the current volunteer.
Change the Html.ActionLink call to the following to pass an id:
@Html.ActionLink("Join Ceremony",
    "VolunteerCeremony",
    "Volunteers",
    new { id = Model.VolunteerId },
    null)

This should fill in the id parameter of the ActionLink with the currently logged in user's userId which should generate the following link: /Volunteers/VolunteerCeremony/3 or whatever the ID actually is.
For the form side, you will also need a hidden field on the form so the correct id is sent along with the request. You will need to add a VolunteerId to the form ViewModel that you create when generating the form page. Once you've done that, inside the form itself, you will need to add the following:
Html.Hidden("id", Model.VolunteerId)

This creates an <input type="hidden" name="id" value="3" /> tag that will be sent with the form on post back to the server. Since the tag's name is id this will match with the id that's defined in your controller action.
Comment: Might as well tell you here! Your code gets rid of the null pointer but I'm still getting the 400 error
Comment: When you debug are you seeing the id come through? Or do you see it in the URL when you click the link after making the above change?
Comment: When I click the link I get the following on the url: "http://localhost:9755/Volunteers/VolunteerCeremony"
Comment: Would also be handy for me to mention that in my code, I don't want to use the user id generated by the registering, I have my own volunteer id that I want to use. They will be different
Comment: Okay. In that case, you will need to pass the id to the View as a property on a ViewModel. Do you have a ViewModel for the page that these links are being generated on?
Comment: Updated my answer there Scott, maybe I need to have the VolunteerId in the ViewModel also?
Comment: Correct you will want to include the VolunteerId. I will update my answer showing some examples.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/164993/discussion-between-scott-baldric-and-anna-doe).


Mean Estimation from 1 Sample that gives Mean and Standard Deviation

Question: The title didn't feel right to me either, but here is my problem: I am attempting to estimate the mean of lead concentration using a handheld x-ray gun, which takes a measurement at a point on the wall, and outputs a mean and standard deviation (example: mean=1.1mg/cm^2, sigma = 0.2). If the device takes several samples, it doesn't specify how many, so I can't use it for, say, a T distribution, unless I multiple samples of the same substrate, which kills the batteries and takes more time than I am given.
The product spec sheet states that it detects lead at 0.1 mg/cm^2 with 2 sigma confidence.
How can I interpret these results to determine the confidence intervals for a = 0.01 and 0.05, assuming a Normal distribution?
Comment: The spec sheet seems unhelpful, except possibly to let you know the lower limit of lead the device can detect.  You may or may not get a straightforward answer if you ontact the manufacturer to see whether several measurements are used to get a result such as mean 1.1mg${}^2$ and SD  0.2. If no useful answer, you could do multiple runs at a few spots to get some idea with what precision the SD is measured Then you might have a basis for making CIs for future single measurements.
Answer: As you know, the $t$-distribution tends towards the normal distribution as the sample size increases. Therefore, if you are willing to assume that the underling distribution is normal -- which is a requirement for your $t$-distribution argument anyway -- you might also assume that the sample size is large enough, such that the normal and the $t$-distribution are very similar [my guess is that this is save to assume]. Hence, I would just use the 68-95-99.7% rule to obtain the confidence bounds of your measurements. Using your data above, I would state that you are 95% confident that the averaged lead concentration lies within the interval $\bar x \pm 2\sigma = (1.1 \pm 0.4)mg/cm^2$.
If you like to check this assumption, you stated the solution already. First take many measurements from the same sample. Then use the central limit theorem. If the assumption is correct we expect that approx. 68% of the $\pm 1 \sigma$ confidence intervals contain the grand sample average and approx. 95% of the $\pm 2 \sigma$ confidence intervals contain the grand sample average.


A simply/path-connected set that is not star-shaped

Question: I come across this definition while studying complex analysis:

An (open) set $U \subset \mathbb C$ is star-shaped  there exists a point $a_0$ such that for all $w\in U$ the line segment connecting $w$ and $a_0$ lies completely inside $U$.

With this definition, we proceed to prove the Cauchy-Goursat Theorem of Integrals for Star Domains:

If in a star-shaped domain $U$, we have a holomorphic function $f$ and a piecewise smooth closed curve $\gamma$, then $\int_\gamma f(z) dz = 0$.

And when I continue my studying, most of the application (such as solving integrals) relies on the fact that $U$ is a simply connected set. By reading this post, I also found that $U$ is star-shaped $\Rightarrow$ $U$ is simply connected $\Rightarrow$ $U$ is path-connected.
I also heard from others that the Cauchy-Goursat Theorem of Integrals for Star Domains is a theorem stronger than required. So does there exists a set such that

$U$ is simply connected but not star-shaped?
$U$ is path-connected but not star-shaped?

Thank you!
Comment: I do not understand the question. You already found that a star-shaped domain is simply connected.
Comment: Thank you Gerry. I originally thought that they are no difference but I am just too careless. The definition is edited. Thanks.
Comment: With other words, since $A\Rightarrow B$ is logically equivalent to $\neg B\Rightarrow\neg A$, such a star-shaped set can not exist. Also it might be worth to mention that open balls are star-shaped, so it is quite common.
Comment: Note that to be path connected, you need to be able to connect every point to every other with a path.  To be star shaped,  you need a single point that has a straight line path to every other point.  So if you are star shaped, you can always create a path between any 2 points by just travelling from one point to the star point to the other point
Comment: My bad, I should ask the question in its converse form as edited. Thank you all for pointing it out.
Comment: The definition of star-shaped can't be right. It must be "there exists $a_0$ such that for every $w$," not the other way around.
Answer: Half of an annulus will do the job. In terms of an equation,
$$\{(x, y) \in \Bbb R^2 : 1 \leqslant x^2 + y^2 \leqslant 2, \ x \geqslant 0\}.$$
Do you see why this satisfies both your conditions?


Changing System.Drawing.Bitmap.Palette

Question: I have a TIFF file in memory, which I obtained by a variant of the following code:
Image myImage = Image.FromFile("somefile.tiff");

Currently, myImage.Palette only returns two colors, black and white.  I would like to expand this to include the entire color spectrum. However, myImage.Palette does not have a function to add additional colors.
Can someone help give my TIFFs some color?  Thanks.
Answer: You can try to use the Clone method to clone the bitmap to Format8bppIndexed

Changing System.Drawing.Bitmap.Palette


Trying to print JSON value

Question: I have JSON output from the dell website and I'm trying to access the values but really having a hard time accessing the values.
For example, I have the following JSON being retrieved:
    {
    "GetAssetWarrantyResponse": {
        "GetAssetWarrantyResult": {
            "Faults": null,
            "Response": {
                "DellAsset": {
                    "MachineDescription": "T350, New Balance",
                    "ShipDate": "2010-05-04",
                    "ServiceTag": "89M1",
                    "OrderNumber": 518,
                    "LocalChannel": 25,
                    "AssetParts": {
                        "@nil": "true"
                    },
                    "CountryLookupCode": 11,
                    "ItemClassCode": "V02",
                    "IsDuplicate": "false",
                    "ParentServiceTag": {
                        "@nil": "true"
                    },
                    "CustomerNumber": 1121,
                    "Warranties": {
                        "Warranty": [
                            {
                                "StartDate": "2011-05-05",
                                "EndDate": "2013-05-04",
                                "ServiceProvider": "U",
                                "ServiceLevelCode": "D",
                                "ItemNumber": "992-82",
                                "EntitlementType": "EXTENDED",
                                "ServiceLevelDescription": "Next Business Day Support",
                                "ServiceLevelGroup": 5
                            },
                            {
                                "StartDate": "2010-05-04",
                                "EndDate": "2011-05-04",
                                "ServiceProvider": "U",
                                "ServiceLevelCode": "N",
                                "ItemNumber": "993-0",
                                "EntitlementType": "INITIAL",
                                "ServiceLevelDescription": "Next Business Day Support",
                                "ServiceLevelGroup": 5
                            }
                        ]
                    }
                }
            }
        }
    }
}

So for example, if I wanted to retrieve the value of "ServiceTag" how would I go about getting that in python? For some reason when I try to do things like:
raw_data = urllib2.urlopen('https://json.url')
djson = raw_data.read()
djdata = (json.dumps(json.loads(djson), indent=4))
print djdata['GetAssetWarrantyResponse']['GetAssetWarrantyResult']['Faults']['Response']['DellAsset'][0]['ServiceTag']

I'm getting:
    Traceback (most recent call last):
  File "./warranty.py", line 35, in <module>
    print djdata['GetAssetWarrantyResponse']['GetAssetWarrantyResult']['Faults']['Response']['DellAsset'][0]['ServiceTag']
TypeError: string indices must be integers, not str

Comment: Are you coming from a XML background ? I'm not sure where all those `a:` prefixes come from but more importantly, I don't get how it does not raise a `KeyError` with the structure you showed us.

*In short, please post more actual code and a minimal sample that we can execute to reproduce the problem. As it stands, this question lacks too much information.*
Comment: have you looked at json library https://docs.python.org/2/library/json.html
Comment: Why are you calling `json.dumps`?  That transforms a python dict into a JSON string, which seems like the opposite of what you want to do.
Answer: Use json.loads to create a python dict containing the JSON information.
Then, access it just like any python dict.
import json

mydict = json.loads(json_response)

print mydict['GetAssetWarrantyResponse']['GetAssetWarrantyResult']['Response']['DellAsset']['ServiceTag']

Comment: Why do I have the feeling that giving the OP a copy-pastable answer won't really help him to solve such problems in the future ? (That being said, it's a good answer)

Trying to print JSON value


How do I get raw urls with contextual filters to work with views in Drupal 7, when i'm using panels, and panels everywhere?

Question: I've scoured the site for solutions, and I have no idea what's going on. I have drupal 7 running off a local installation (mamp), and my site is structured with Panels and Panels Everywhere. I have a view that is in the sidebar, and I want it to pull up anything tagged with the name of the page. (for example walldamp/drupal/architecture would pull up architecture, or walldamp/drupal/acoustics would pull up all nodes tagged with acoustics).
The preview works just fine when I type in a tag, but it just won't work with the sites. If anyone could help, I'd really appreciate it.
I'll post a picture as soon as I get more reputation, but currently my settings are as follows for the contextual filter.

Configure contextual filter: Content: Has taxonomy term ID
Provide Default Value
Raw Value form URL
Path Component: 3
Exception Value: All
Specify Validation Criteria
Validator: Taxonomy Term
Filter Value Type: Term Name converted to Term ID
Transform dashes in url to spaces in term name filter values
Action to take if filter value does not validate: Display a summary.

It's just displaying the summary in my sidebar, no actual blog posts or images like in the preview. Any help would be appreciated.
Answer: Try using argument 2 (URL arguments start at 0 not 1) as opposed to argument 3. A Failing that, disable the validation, oftentimes the validation is screwy and excludes valid content.  Start with as little filtering, validation, exclusion, etc. to make sure you're getting data and tighten the parameters from there.
Comment: I tried both of those to no avail. When I take away the contextual filter, and just use a regular taxonomy filter, it works fine, but when i use the contextual filter, nothing.
Comment: Maybe there's a better way to be doing this? Would it be easier to just put a taxonomy field on each node, and have it call from that? (For example, any nodes having to with acoustics would call all other nodes having to with acoustics into that sidebar.)
Comment: Yeah, that would be easier. Much easier.
Comment: I could use some pointers, my brain melted trying to think about it.
Comment: I guess I need to know where I would find the setting for the view to read what the taxonomy for the node is. It's in a separate panel, and I'm not sure if that would work because of it.
Comment: http://scito.ch/content/show-related-nodes-block-based-taxonomy-terms-views-3-and-drupal-7  Should be a good starting point.
Comment: It turns out the problem is it's reading the original URL for the node instead of the path alias. I think the view is reading the url as walldamp/drupal/node/59 instead of walldamp/drupal/acoustics. Any ideas on how to fix that?
Comment: Not really, node ids are considered better since pathalias could change and nids don't.  I'd still go with the vocab tagging on nodes.  You should be able to use ajax autocomplete, which makes tagging really really easy.
Comment: But the node id's are just numbers, do I have to just create a side by side legend for it? (If you want to tag related to acoustics, enter 59 in the tag field)
Comment: To explain better, I want all blog posts, product types and content related to this page to pop up next to it. Since the page is called acoustics, I thought it would be best to have the tag be called acoustics.
Comment: Figured it out, I had to add it as a block instead of a master view. I'm just using taxonomy terms like the tutorial you sent. Thank you!
Answer: If the preview works when you type in the tag, then you may need to switch the Filter Value Type to Term ID rather than use the term name. This is often because Pathauto settings are not the same as Drupal's internal path. Try the above change to the filter value and then check Devel on your pages, you should have a 'tid' variable that is populated with the appropriate term ID.


android:headerBackground having no effect

Question: I'm currently working on creating a custom theme for a datePicker and I'm having some difficulty with setting the headerBackground and the circle around the selected date separately. I've set my theme up like this:

App theme looks like this:

And last but not least, State0BaseTheme looks like this:

I had thought that overriding colorAccent, and setting headerBackground would work just fine, but I guess not? Here's what it looks like with all these styles:

If I set android:headerBackground in the xml of the datePicker, everything works great. However, I want to be able to change the theme for all screens of the app based on user input. Thoughts as to why this isn't working?
Comment: maybe this will help you http://stackoverflow.com/a/29014475/5873832
Answer: I read the link posted by @DasserBasyouni and found that making the parent of my datePickerTheme @android:style/Widget.Material.Light.DatePicker and setting android:datePickerStyle to @style/State0DatePickerTheme in State0BaseTheme worked perfectly


Using JQuery to add class to and image

Question: I have a logo and had to split it into a top and bottom section to try and achieve a  spinning effect on the bottom portion of the logo.
Main goal is to take the bottom saw blade part of my logo and make it spin/rotate on hover.
I can make it spin/rotate, but since the logo is spit into two sections. I have to use z-index to stack the image and the bottom logo will not spin when it is lower than the top image because the top image is blocking the bottom image.
I tried using Jquery to solve the problem, but not to familiar with the coding yet.
Could someone please take a look at this CodePen and help me out.
Here is the link to the Pen / Code: http://codepen.io/daugaard47/pen/yKrdD
If you reverse the z-index you can see the spinning effect.
Thank you.
-Chris
Comment: Can you create a demo fiddle?
Comment: Not on a computer to hover, but why not make the bottom half of the top image transparent?
Answer: Neat design!
heres a working version
http://codepen.io/patrickkettner/pen/byFIl
You were really close - just a couple tweaks.
Add the :hover listener to the wrapper, that way you don't need to worry about the stacking.
Secondly, add a gpu hack (I used translateZ) to the animated element to prevent any flicker from the element jumping to the gpu to be animated and then back to the cpu to its resting state (check out http://www.youtube.com/watch?v=8uAYE5G1gSs for waaaay more information than you need to know on that topic).
Comment: Thank you so much! Been trying to figure this one out all night. Really appreciate it.
Comment: Checked out that video to. Understood about a 1/3 of what the hell they were talking about, (lol) but very interesting none the less. Thanks again.
Comment: @ Patrick one more question, different topic hope I don't get flagged for changing topics, but I've been struggling with creating fallback .png's for my .svg's . How would you go about doing this? You can use the same address for the images, just add the .png extension instead of .svg
Comment: My first instinct would be to check out modernizer

Using JQuery to add class to and image


How to pull out a specific value from a python pandas data frame?

Question: I'm a newbie of pandas, and have a quick and stupid question about Python Panda package: How to pull out a specific value from a data frame?
The structure of data frame likes:
           id           ba_ntr
0           1            PRF
1           2            PUF
.....
3898     3444       PRF

I then use the code likes the following to pull out a specific value:
list(df[df['id'] == 25]['ba_ntr']) == ['PUF']

In the code above, I am trying to:

Find the line in which the value of column id is 25. All the
values in id are unique but not continuous - one of the reason
that I did not use index.
Because all the values in id are unique, df[df['id'] == 25] should
return one row, and I then need to know the value of column ba_ntr
in that line.
Because df[df['id'] == 25]['ba_ntr'] will return a pandas Series, I
use list() to convert the Series to list, and compare with another
list ['PUF'].
I believe converting series to list is unnecessary and
time-consuming - I have 5 million lines of records to iterate...

So thank you for saving my time and life!
Comment: if you want just the scalar value then `df.loc[df['id'] == 25,'ba_ntr'].values[0]` will return the scalar value
Comment: will this faster than I use list()?
Comment: probably but not by much as the main thing is the indexing part, converting the series to a list will add some minor overhead but I expect just accessing the np array will be faster
Comment: Also what are you trying to do here? It looks like you're trying to match your id values against a list? are you just wanting to test for membership of a list of values?
Comment: I want to compare the value of ba_ntr in a specific row, whether it is PUF or PRF. Any better strategy?
Comment: You mean compare against a string? Are these matches pre-defined? you'd better first to filter the df `matches = df[df['id'].isin(my_list_of_ids)]` then you can match the str values. The PUF/PRF are these values matched already against a list of ids or are you just wanting to count the different values?
Answer: If your id column is indeed unique, why not just use it as the index? (there is no requirement that the index be continuous)
df.set_index('id', drop=True, inplace=True)
# or, if you don't want to mangle the existing data frame
# df_reindexed = df.set_index('id', drop=True)
is_puf = df.loc[25, 'ba_ntr'] == 'PUF'

Comment: This being said, I hope you have a good reason for element-wise iteration! What is your end goal?


AngularJS - remover itens selecionados de acordo com checkbox

Question: Como faço para pegar os ids dos itens selecionados do(s) checkbox(es) para enviar para o backend e posteriormente remover?

            **O QUE PASSO POR PARAMETRO PARA A FUNÇÃO? **
            delete

                ** OQUE EU PASSO NO MODEL DO CHECKBOX ?**
                <input ng-model="???????" type="checkbox"
                 id="item-">

            {{entry.value}}
            {{entry.type}}
            {{entry.date}}
            {{entry.category}}
            {{entry.description}}

Comment: qual é o `entry`? tem o exemplo que possa colocar ?
Comment: Opa Virgilio, entry é o objeto de todos os lançamentos da grid.

Vamos supor que tenho dois lançamentos na grid e quero deletá-los de uma vez só. Quero que os ids dos lançamentos sejam enviados para  a função removeEntry, mas não sei como passar no html.
Comment: você quer excluir e qual desse itens é a id, até fiz uma resposta mas, tem bastante informação faltando! Qual é o elemento que identifica cada entrada? "para que eu faça a edição", outro ponto tem que fazer o cadastro desse objeto adicionando um item a mais para definir o seu status true para excluir false para manter até isso eu já o fiz.
Answer:

angular.module("app", [])
  .controller("ctrl", ["$scope",
    function($scope) {
      $scope.allEntries = [{
        'value': 1,
        'type': 2,
        'date': '01/01/1999',
        'category': 3,
        'description': 'd1'
      }, {
        'value': 10,
        'type': 20,
        'date': '20/01/1999',
        'category': 30,
        'description': 'd20'
      }, {
        'value': 40,
        'type': 50,
        'date': '25/01/1999',
        'category': 60,
        'description': 'd60'
      }];
      $scope.removeEntry = function() {
        angular.forEach($scope.allEntries,
          function(a, b) {
            if (!(typeof a.status == "undefined") &&
              a.status) {
              console.log(a.status);
            }
          });
      };
      $scope.isHas = function() {
        for (let i = 0; i < $scope.allEntries.length; i++) {
          var a = $scope.allEntries[i];
          if (!(typeof a.status == "undefined")) {
            if (a.status)
            {
              return true;
            }
          }
        }
        return false;
      };
    }
  ]);

    delete

        <input ng-model="entry.status" type="checkbox">

      {{entry.value}}
      {{entry.type}}
      {{entry.date}}
      {{entry.category}}
      {{entry.description}}

Comment: Deu certo cara, muito obrigado! :D


Inequality in triangle involving medians

Question: Let $ABC$ be a triangle and $M$ a point on $(BC)$, $N$ a point on $(CA)$ and $P$ a point on $(AB)$ such that the triangles $ABC$ and $MNP$ have the same centroid.
Does the following inequality hold: $$AM^2+BN^2+CP^2\ge AA'^2+BB'^2+CC'^2 ?$$ where $A',B'$ and $C'$ are the midpoints of $(BC), (AC)$ and $(AB)$.
EDIT: $AA'^2+BB'^2+CC'^2=3/4(AB^2+BC^2+CA^2)$ and from MB/MC=NC/NA=PA/PB follows that the triangles ABC and MNP have the same centroid, by Pappus Theorem.
Comment: The left hand side of your inequality should be $AM^2+BN^2+CP^2$.
Comment: Is there some reason for this question?
Comment: @mathlove Now it's ok!
Answer: If $MNP$ has the same centroid than $ABC$ then $$\frac{M+N+P}3=\frac{A+B+C}3$$ (if seen each point as a vector in $\mathbb R$.)
Also, as $M$ is in $BC$ then $$M=mB+(1-m)C$$ for some $0\le m\le1$.  Analogous:
$$N=nC+(1-n)A,$$
$$P=pA+(1-p)B.$$
This means that:
$$N+M+P=(1+p-n)A+(1+m-p)B+(1+n-m)C$$
Where $A+B+C=N+M+P$, therefor
$$0=(p-n)A+(m-p)B+(n-m)C$$
Having $\lambda=p-n$ and $\mu=m-p$, then $n-m=-(\lambda+\mu)$, and we get
$$0=\lambda(A-C)+\mu(B-C).$$
Unless $ABC$ are colinear, this only happens when $\lambda=\mu=0$ which means $m=n=p$.
So:
\begin{align}
M &= mB+(1-m)C \\
M-A &= mB+C-mC-A \\
M-A &= m(B-C)+(C-A) \\
AM^2=(M-A)(M-A) &= m^2(B-C)(B-C)+m(B-C)(C-A)\\&\qquad+m(C-A)(B-C)+(C-A)(C-A)^2 \\
&= m^2CB^2-2mCB\,AC\cos C+AC^2
\end{align}
By law of cosins: $AB^2=AC^2+CB^2-2CB\,AC\cos C$, therefor $2CB\,AC\cos C = AC^2+CB^2-AB^2$, replacing we have:
\begin{align}
AM^2&=m^2CB^2-m(AC^2+CB^2-AB^2)+AC^2
\\&= mAB^2 + (m^2-m)CB^2 + (1-m)AC^2
\\\text{analogously}\\
BN^2&= mBC^2 + (m^2-m)AC^2 + (1-m)BA^2\\
CP^2&= mCA^2 + (m^2-m)BA^2 + (1-m)CB^2\\
AM^2+BN^2+CP^2 &= (1-m+m^2)(AB^2 + BC^2 + CA^2)
\end{align}
Where the minimum value of $1-m+m^2$ is where $m=\frac12$ as can be prove with a little calculus.  And $m=\frac12$ is the value for $M=A',N=B',P=C'$.


update glib-1.2 project to use glib2

Question: I'm resurrecting an old open source project that uses glib-1.2. I figure one of the things I should do is update it to use glib2-2.34, but I can't find any documentation on doing that. In particular, I would like to know the changes I need to make to my autoconf setup, currently
configure.ac:AM_PATH_GLIB(1.2.0)

src/Makefile.am:AM_CPPFLAGS = @GLIB_CFLAGS@
src/Makefile.am:arccc_LDADD = @GLIB_LIBS@

Answer: Found after looking through open source projects for examples: replace the above lines with
configure.ac:PKG_CHECK_MODULES([DEPS], [glib-2.0 >= 2.34.3])

src/Makefile.am:AM_CPPFLAGS = @DEPS_CFLAGS@
src/Makefile.am:arccc_LDADD = @DEPS_LIBS@

Also, I decided to move the entire project to cmake, and can recommend that route.
Comment: The whole GNOME stack is one of the better Autotools-based projects and I experienced a lot of pain using CMake for a GLib/GObject project I am working on. So, although initially it might be easier to go CMake, I cannot recommend it once you incorporate things like gtk-doc, GObject Introspection and the like.
Comment: this is not a gnome- or even gobject-based project, it just happens to be using glib as a datastructure library.

update glib-1.2 project to use glib2


Disable cache a custom block for anonymous user

Question: I have a custom block, it displays in every pages with dynamic data calculates in every refresh, How can I disable cache for this block for anonymous users?
I try with:
<code>public function build() {
  return [
    '#markup' => time(),
    '#cache' => [
      'max-age' => 0,
    ],
  ];
}
</code>
It won't work.
Edit:
I don't want to disable the cache for the entire page, I just need a specific block not to be cache.
Comment: Possible duplicate of [How can I prevent a particular page being cached?](https://drupal.stackexchange.com/questions/151254/how-can-i-prevent-a-particular-page-being-cached)
Comment: See https://drupal.stackexchange.com/questions/228485/caching-of-blocks-for-anonymous-user
Answer: If you want to completely disable caching for the block, use this function in your block class:
<code>  public function getCacheMaxAge() {
    return 0;
  }
</code>
I've never found in the documentation why
<code>'#cache' => [
      'max-age' => 0,
    ],
</code>
doesn't work with blocks but, like you discovered, it doesn't seem to.


Função de verificação só retorna vazia

Question: Fiz essas duas funções bem simples pra limitar os caracteres e pra ver se a coluna no banco ta vazia, por algum motivo só retorna vazia mesmo tendo resultados.
public function limite_texto($texto, $limite, $complemento) {
    return mb_strimwidth(utf8_encode($texto), 0, $limite, $complemento);
}

public function vazio($texto, $limite, $complemento, $aviso) {
    if (empty($texto)) :
        return $aviso;
    else :
        return $this->limite_texto($texto, $limite, $complemento);
    endif;
}

$ctlr->vazio("oooooi", 3, "...", "O campo está vazio")

Por algum motivo ta retornando apenas os "...", quando o esperado seria "ooo..." ou se a variavel $texto fosse vazia retornasse O campo está vazio, acho que errei na logica
Answer: Você definiu que a função deve retornar 3 caracteres, você obteve 3 caracteres, mas achou estranho porque não vieram 6? Estranho.
Talvez faltou mais atenção ao ler a documentação das funções que está utilizando:

mb_strimwidth
Valor retornado: The truncated string. If trimmarker is set, trimmarker replaces the last chars to match the width.

É retornada a string truncada, mas se o valor de trimmarker for definido, trimmarker irá substituir os últimos caracteres da string até atingir o tamanho limite.
Ou seja, você passa a string "oooooi", que truncada seria "ooo", mas como definiu o valor de trimmarker, ele substituirá os últimos caracteres até ter no máximo 3 caracteres (limite que você definiu).
Portanto, a saída sempre será "...", pois apenas o valor de trimmarker já atinge o limite de caracteres que você definiu.
Se o objetivo era obter "ooo...", você deveria ter definido o limite como 6, visto que você quer ter 6 caracteres na saída.
Comment: A intenção era fazer essa função adicionar os "3 pontinhos" limitando a número de caracteres somente da variavel `$texto`

Função de verificação só retorna vazia


How can I differentiate this?

Question: I was trying to differentiate this: $\frac{1}{2} \sin^{-1} \frac{2x}{1+x^2}$ but I am really stuck.I obtained an answer that does not match with the one given in the book.Your help is appreciated.[Edit: I used the formula $\frac{d}{dx} \sin^{-1}x=\frac{1}{\sqrt{1-x^2}}$ to get $\frac{1+x^2}{2(1-x^2)}$]
Thank you.
Comment: Could you show your attempt to apply the chain rule, so that we can debug properly?
Comment: Look up derivative of $\arcsin(x)$, compute derivative of $\frac{2x}{1+x^2}$, then use [chain rule](http://en.wikipedia.org/wiki/Chain_rule).
Comment: @SabyasachiMukherjee: Two errors: (i) You forgot to apply the Chain Rule (the whole thing should be multiplied by the derivative of $\frac{2x}{1+x^2}$; and (ii) you simplified $\sqrt{(1-x^2)^2}$ as $1-x^2$; that's only true if $-1\leq x \leq 1$. In general, $\sqrt{a^2}=|a|$.
Comment: Do you mean $\frac{d}{dx}\sin^{-1}(x) = \frac{1}{\sqrt{1-x^2}}$? Because $\frac{d}{dx}\tan^{-1}(x) = \frac{1}{1+x^2}$. Also, you need to have an argument after "$\tan^{-1}$"; otherwise, it's not really sensical.
Comment: I had made careless typos...I believe I edited it a minute before you commented.
Comment: Sure..$\frac{d}{dx}( \frac{1}{2} sin^{-1} \frac{2x}{1+x^2})=\frac{1}{2} \frac{d}{dx} (sin^{-1} \frac{2x}{1+x^2})=\frac{1+x^2}{2(1-x^2)}$
Answer: The derivative of the arcsine function is
$$\frac{d}{du}\arcsin(u) = \frac{1}{\sqrt{1-u^2}}.$$
So, using the Chain Rule, you would have
$$\frac{d}{dx}\frac{1}{2}\arcsin\left(\frac{2x}{1+x^2}\right) = \frac{1}{2}\left(\frac{1}{\sqrt{1 - \left(\frac{2x}{1+x^2}\right)^2}}\right)\left(\frac{2x}{1+x^2}\right)'.$$
The derivative of $\frac{2x}{1+x^2}$ is a simple application of either the Quotient Rule or the Product, Power, and Chain Rules:\
$$\begin{align*}
\frac{d}{dx}\left(\frac{2x}{1+x^2}\right) &= \frac{(1+x^2)(2x)' - 2x(1+x^2)'}{(1+x^2)^2}\\
&= \frac{2(1+x^2) - 2x(2x)}{(1+x^2)^2}\\
&= \frac{2 + 2x^2 - 4x^2}{(1+x^2)^2}\\
&= \frac{2(1-x^2)}{(1+x^2)^2}.
\end{align*}$$
The expression obtained from the derivative of $\arcsin(u)$ can use a bit of simplification too:
$$\begin{align*}
\frac{1}{\sqrt{1 - \left(\frac{2x}{1+x^2}\right)^2}} &= \frac{1}{\sqrt{1 - \frac{4x^2}{(1+x^2)^2}}}\\
&=\frac{1}{\sqrt{\frac{(1+x^2)^2 -4x^2}{(1+x^2)^2}}}\\
&= \frac{1}{\frac{\sqrt{1+2x^2+x^4 - 4x^2}}{|1+x^2|}}\\
&= \frac{|1+x^2|}{\sqrt{1-2x^2+x^4}}\\
&= \frac{1+x^2}{\sqrt{(1-x^2)^2}}\\
&= \frac{1+x^2}{|1-x^2|}.
\end{align*}$$
(Remember that $\sqrt{a^2}=|a|$, not $a$; we can get rid of the absolute value bars around $1+x^2$ because it is always positive; the same is not true with $1-x^2$).
Putting it all together, we have:
$$\begin{align*}
\frac{d}{dx}\frac{1}{2}\arcsin\left(\frac{2x}{1+x^2}\right) &= \frac{1}{2}\left(\frac{1}{\sqrt{1 - \left(\frac{2x}{1+x^2}\right)^2}}\right)\left(\frac{2x}{1+x^2}\right)'\\
&= \frac{1}{2}\left(\frac{1+x^2}{|1-x^2|}\right)\left(\frac{2(1-x^2)}{(1+x^2)^2}\right)\\
&= \frac{1-x^2}{(1+x^2)|1-x^2|}.
\end{align*}$$
This can be rewritten with the "sign function",
$$\mathrm{sgn}(u) = \left\{\begin{array}{ll}
1 & \text{if }u\gt 0;\\
-1 &\text{if }u\lt 0.
\end{array}\right.$$
as
$$\frac{d}{dx}\frac{1}{2}\arcsin\left(\frac{2x}{1+x^2}\right) = \frac{\mathrm{sgn}(1-x^2)}{1+x^2}.$$
It's also possible your book was not careful with the square root of the square, so that the answer given is just
$$\frac{1}{1+x^2}.$$
Comment: @AndréNicolas: Oops, quite right. Thank you!
Comment: Thank you very much,Mr Magidin.I learnt of the loopholes in my technique.
Answer: $y=\sin(x)\Rightarrow\frac{\mathrm{d}y}{\mathrm{d}x}=\cos(x)=\sqrt{1-y^2}\therefore\frac{1}{\sqrt{1-y^2}}=\frac{\mathrm{d}x}{\mathrm{d}y}=\frac{\mathrm{d}}{\mathrm{d}y}\sin^{-1}(y)$
The rest is the chain-rule:
$$
\begin{align}
\frac{\mathrm{d}}{\mathrm{d}x}\frac{1}{2}\sin^{-1}\left(\frac{2x}{1+x^2}\right)
&=\frac{1}{2}\frac{1}{\sqrt{1-\left(\frac{2x}{1+x^2}\right)^2}}\frac{\mathrm{d}}{\mathrm{d}x}\frac{2x}{1+x^2}\\
&=\frac{1}{2}\frac{1+x^2}{|1-x^2|}\frac{2(1+x^2)-2x(2x)}{(1+x^2)^2}\\
&=\frac{1}{2}\frac{1+x^2}{|1-x^2|}\frac{2(1-x^2)}{(1+x^2)^2}\\
&=\frac{\operatorname{sgn}(1-x^2)}{1+x^2}\tag{1}
\end{align}
$$
Let $x=\tan(\theta)$, then $\frac{2x}{1+x^2}=\sin(2\theta)$. When $|\theta|<\frac{\pi}{4}$, $|x|<1$, so $\operatorname{sgn}(1-x^2)=1$. Then, equation $(1)$ is the reciprocal of
$$
\frac{\mathrm{d}}{\mathrm{d}\theta}\tan(\theta)=\sec^2(\theta)
$$
When $|\theta|\in(\frac{\pi}{4},\frac{\pi}{2})$, $|x|>1$, so $\operatorname{sgn}(1-x^2)=-1$, but $\sin^{-1}(\sin(2\theta))=\pi\operatorname{sgn}(\theta)-2\theta$. Then, equation $(1)$ is the reciprocal of
$$
\frac{\mathrm{d}}{\mathrm{d}\theta}(-\tan(\theta))=-\sec^2(\theta)
$$
Comment: As the argument to $\sin^{-1}$, $\frac{2x}{1+x^2}$ should be in $[-1,1]$. Thus, $x$ would be in $[-1,1]$ as well.
Comment: If $x=2$, then $\frac{2x}{1+x^2} = \frac{4}{5}$, which lies in $[-1,1]$, so I don't see how you are getting that $x$ must be restricted to $[-1,1]$. Note that for $x\gt 0$, $\frac{2x}{1+x^2}\leq 1$ if and only if $1+x^2-2x\geq 0$, if and only if $(1-x)^2\geq 0$, which always holds; symmetrically for $x\lt 0$ and $\frac{2x}{1+x^2}\geq -1$. So $x$ can be any real number, not just restricted to $[-1,1]$.
Comment: @Arturo: I don't know what I was thinking. Of course, $\frac{2x}{1+x^2}$ reaches a maximum at $x=1$ and  minimum at $x=-1$, but yes, for all $x\in\mathbb{R}$, $\frac{2x}{1+x^2}\in[-1,1]$. I have to correct my answer to account for this.
Answer: Another approach would first prove the trigonometric identity
$$
\frac12 \arcsin\frac{2x}{1+x^2} = \arctan x \text{ if } -1 \le x \le 1.
$$
Then you have to figure out separately what to do when $x>1$ or $x<-1$.  If I'm not mistaken, you get
$$
\frac12 \arcsin\frac{2x}{1+x^2} = \frac\pi2 -\arctan x \text{ if } x>1
$$
and
$$
\frac12 \arcsin\frac{2x}{1+x^2} = -\frac\pi2 -\arctan x \text{ if } x<-1.
$$
Then you just need to remember how to differentiate the arctangent function.
Answer: Shortest way around:
Put $x= tan \theta $ to simplify the expression inside the arcsin function to $sin 2\theta$ .
The value of the given function is then just $\theta$ which is equal to arctan $x$
 , which on differentiating gives $\frac {1}{1+x^2}$

How can I differentiate this?


Prove the positive sequence $a_{n+1} = \sqrt{1+\frac{a^2_n}{4}} $ is strictly increasing for $0 \leq a_0<\frac{2}{\sqrt{3}}$

Question: My attempt:
$a_{n+1} - a_n=  \sqrt{1+\frac{a^2_n}{4}} -a_n > \frac{a_n}{2}-a_n = -\frac{1}{2}a_n$, which doesn't tell me any thing. How do I prove that this sequence is strickly increasing? Thank you!
Comment: $a^2 + b^2 \ge 2ab$
Comment: The sequence is strictly increasing if and only if the starting point (not sure where your sequence starts) lies in the interval $\left(-\frac{2}{\sqrt 3},+\frac2{\sqrt{3}}\right)$.  If the sequence start with $a_0$, then this means $|a_0|<\frac{2}{\sqrt 3}$.  If the sequence starts with $a_1$, then this means $|a_1|<\frac{2}{\sqrt 3}$.  On the other hand, if the starting point is greater than $+\frac{2}{\sqrt 3}$, then the sequence is strictly decreasing.  If the starting point is less than $-\frac{2}{\sqrt{3}}$, then the sequence is strictly decreasing after one term.
Comment: My hint is to show that the function $f:[0,\infty)\to[0,\infty)$ defined by $f(x)=\sqrt{1+\frac{x^2}{4}}$ for all $x\geq 0$ satisfies $f(x)>x$ for $x$ in the interval $\left[0,\frac{2}{\sqrt{3}}\right)$.  Furthermore, show that $f$ maps the interval $\left[0,\frac{2}{\sqrt{3}}\right)$ into itself.
Comment: You have showed that it is decreasing
Comment: @TitoEliatron It was a type-o. I have corrected it.
Comment: So if $a_n=10$, then $a_{n+1}=\sqrt{26}>10$.  Is there some condition missing?
Comment: @soobster so, yo have to prove that the sequence is decreasing?
Comment: @OscarLanzi Yes, the range of the initial value was missing. I have added it on the title. Thank you so much for pointing out.
Comment: @Batominovski Thank you so much for pointing out. It was stated in the question and I missed it. I am so sorry for the confusion.
Answer: HINT:
It remains to show that
$$
\forall n\, a_n<\frac2{\sqrt{3}}.
$$
For $n=1$ it is in comments.
Answer: $a_n^2=1+\frac{a_{n-1}^2}{4}=\frac{1}{4}\left(4+a_{n-1}^2\right)=\frac{1}{4^2}\left(4^2+1\cdot4+a_{n-2}^2\right)=\frac{1}{4^3}\left(4^3+4^2+4+a_{n-3}^2\right)$
Hence, a recursive formula can be written as follows: $$ a_{n+1}^2=\frac{1}{4^n}\left(4^n+4^{n-1}+...4+a_1\right)=\frac{4}{3}\cdot\frac{4^n-1}{4^n}+\frac{a_1^2}{4^n}$$.
$\therefore\lim\limits_{n\to\infty}a_n=\frac{2}{\sqrt3}$ irrespective of the choice of $a_1$.
Also $a_{n+1}^2-a_n^2=\frac{4-3a_n^2}{4}>0 \forall a_n<\frac{2}{\sqrt3}$.
Can you do the rest?


How can I be sure configuration is never changed on live system?

Question: The documentation for the Drupal 8 configuration manager says:

Making configuration changes on a live site is not recommended.

When managing a site used by dozens of content managers, how can I make sure that this really never happens? Is there a way to prevent this with permission settings? For me it's still not really clear which permissions to set, to make sure those users are never able to change the configuration.
Comment: this is too broad and cannot be answered.
Answer: One option is to use https://www.drupal.org/project/config_readonly, it enforces that config writes can not happen on production.
So far, I haven't built/maintained a D8 site where that approach was practical. Most of our sites rely quite heavily on contact forms for example, with workflows where content managers create contact forms as well. And sometimes quick changes are necessary, e.g. for services and integrations.
One option to deal with that is to use a project like https://www.drupal.org/project/config_split, which allows to keep a part of configuration outside of git and not have it overwritten by deployments. So far, we just do a config export on production, commit that to the production branch and then merge the feature branches that we want to deploy. There's some risk for conflicts, but that doesn't happen often.
But sure, there are sites where it is critical that every change is reviewed and approved first, before it can be deployed, then something like config_readonly is useful. I wouldn't enforce it just because some d.o page says so, you need to figure out what works best for your site and workflows.
Answer: I can speak for developing with Drupal 7 but I'm sure the concept can be translated.
Content Contributor Role
To answer your question about controlling permissions, just take a look at this documentation on Drupal 8 permissions. Create a specific role for content contributors and give them only the specific permissions you want them to have, e.g. nothing with configurations. You can bulk reassign all your content contributors to the new role you created, if you don't already have it.
Prevent users from logging into the admin account by protecting the password and making sure there is only one admin account on production. All content contributors should only have access to functions which build data, such as adding or editing nodes and editing the menu.
Development Workflow
Rarely log into production as an admin and use git and features to push everything up into it after testing the code and data in a staging environment. I work on a local environment and push the code up to staging while I import the database from prod to staging. If everything checks out in staging, I push the code into production. No configurations need to happen in production because they can all be featurized in development. Thus, preventing access to making configuration changes on production works just fine.
All developers develop locally and the staging environment is where the design team approves things before they are deployed. This article on Drupal development with Git is my bible.


jQuery Dialog, passing html to dialog

Question: I am looking for a method to pass html to jquery dialog. Without success.
I try:
Drupal.jqui_dialog.html(messages);

And
        Drupal.jqui_dialog.open({
              data : messages
        });

But it doesn't work.
Answer: If you have the jQuery UI library with dialog activated on your site, you should be able to do
$('
' + message + '
').dialog();

jQuery Dialog, passing html to dialog


wkhtmltopdf segfault when ran from python

Question: I have to run wkhtmltopdf from python with subprocess.call(...). From the command line, I can generate the pdf without problem but when its run from python, it fail with a segfault.
I have no idea what is causing wkhtmltopdf to segfault.
I even tried sending my terminal env attributes but it still segfaults. I sent stderr, stdin, stdout but nothing works. What's worrying me is that it runs from a terminal but not from python.
Also, calling the process from a different process in python also makes it segfault. For exemple, I added a script in between to call this application and the script written in python also receive a segfault from wkhtmltopdf.
#!/bin/env python
import subprocess
import sys
import pdb
import os

sys.argv[0] = "/usr/local/bin/wkhtmltopdf.b"

sys.argv.remove('--quiet')

status = subprocess.call(sys.argv,
    env=env,
    stdin=sys.stdin,
    stdout=open("/tmp/stdout.w", "w"),
    stderr=open("/tmp/stderr.w", "w"))

cmd = " ".join(sys.argv)

pdb.set_trace()

Right now I'm doing this to get me time to execute the command in an external terminal. OpenErp is checking for the content of the pdf file. wkhtmltopdf.b is the original binary. I removed the quiet parameter as I wanted to see what's going on.
It apparently segfaults at this moment:
Loading pages (1/6)
[======>                                                     ] 10%

And nothing else
My version of wkhtmltopdf amd64 static from the website wkhtmltopdf.org
$ wkhtmltopdf -V
wkhtmltopdf 0.12.1 (with patched qt)

I'm running one of the ubuntu amd64 binary package on my gentoo box. It's kind of hard/long to get wkhtmltopdf compiled with patched qt on gentoo it doesn't seems to be supported by default. Yet, since it's running from the command line, it should also run from python.
I'm running it from zsh but even if inside my python program I would instead call something like this:
'/bin/sh -c "%s"' % command

It would also segfault.
Comment: Python's subprocess starts a new shell, which probably doesn't inherit a few shell settings & environment variables. For example, you could have a `LD_LIBRARY_PATH` on your command line pointing to a newer library that `wkhtmltopdf` uses, while that path is lacking when started through `subprocess`, and thus `wkhtmltopdf` falls back to an older library, which causes the segfault. Try searching for one or more shell/environment variables that cause `wkhtmltopdf` to run properly on the command line.
Comment: @Evert I thought of that. I updated the `env` dict with the result of `env` from my terminal. I stripped it out because it's pretty big. But the env is the same as in my terminal.
Comment: Just to double check, print out your environment when run from the cmdline or when run from subprocess.
Comment: Can you list your Python version, OS, shell type & version, and wkhtmltopdf version?
Answer: I had the exact same issue as yours but running through a different stack (Apache & PHP) but I'm not 100% sure how you launch your python in fact. Anyway, it crashed exactly at the same place as yours and it was working fine from command line so I guess it may be worth sharing in case that helps anyone ;)
I found out my issue was an ulimit set differently when ran through apache then shell. Specifically my "virtual memory" ulimit -v was pretty low. I end up doing $cmd = "ulimit -v 1073741824; {$this->wkhtmltopdf_path}...." and that solves my issue! (You can check with running ulimit -a and compare the values from the same command on the shell!)
Comment: Okay, can't say it's 100% right in my case because ulimit won't have any effect in odoo... but I changed the parameters that control memory usage and setting a ulimit to over 1gb of ram kind of fix the issue.
Comment: I'll have to try this.
Answer: Try passing the HTML string via stdin. Here's an example followed by a download response.
from subprocess import Popen, PIPE, STDOUT
from django.core.files.temp import NamedTemporaryFile
from django.template.loader import render_to_string
from django.http import HttpResponse

tmp = NamedTemporaryFile()
html = render_to_string('your-template.html', context)
p = Popen(['wkhtmltopdf', '-', tmp.name], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
out, err = p.communicate(input=(html + u'\n').encode('utf-8'))
# check for errors in 'out' and 'err' -- print out, err
with open(tmp.name, 'r') as pdf:
    pdfcontent = pdf.read()
response = HttpResponse(pdfcontent, content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename=print.pdf'
response['Content-Length'] = len(pdfcontent)
return response

You'll have to use full static URLs in your templates to prevent wkhtmltopdf from not finding the static CSS and JS files.


Set security on pattern of sub folders (Server 2003)

Question: I have a folder structure similar to the one shown below these paragraphs.  How do I change security on every 'Photos' folder without clicking through each individually in Windows Explorer?  There are about 50 top level folders (Bob, Jim, Eva, etc, etc) which have the same layout of folders inside.
I am keen for any suggestions, either scripting or GUI.  I am on Windows Server 2003.  Cheap/free method would be good, as the company is part of a registered charity.  Ideally I would like to do this via DFS path.  E.G. \\mycompany.local\Shared\Staff\Bob\
Thanks for reading.  Thanks for any info.  Mark

Bob

Review
Profile

Photos

Jim

Review
Profile

Photos

Eva

Review
Profile

Photos
Answer: The following little PowerShell script could do the trick for you.  It would start in the root of the c drive and recurse through finding all the directories named Photos.
Then the correctacl variable gets the permissions you want to apply from an existing folder.  (I assume you could also set up your own ACL object but that would be more difficult it seems.)
Finally, for each folder found it sets the ACL to match the ACL in correctacl.  Might take a while depending on the size of the server, but should work.
<code>$folders = Get-ChildItem -Path "\\someserver\c$" -Filter "Photos" -Recurse|Where-Object { $_.PSIsContainer }
$correctacl=Get-Acl -Path "\\someserver\c$\somefoldertogetaclobjectfrom"
foreach ($folder in $folders)
{
Set-Acl -AclObject $correctacl -Path $folder.PSPath
}
</code>
Comment: Thanks, Christopher.  This looks very promising.  I had not heard of an 'ACL object' and that sounds like a useful thing too.  Thank you.
Answer: @Christopher's powershell method will work.  If you are more comfortable with the legacy comand line try this
<code>For /D %i in (*) do cacls %i\profile\Photos .......
</code>
Run cacls ? at the command line to figure out the remainder of the command for your settings
The for /d will match against directories of the pattern "*" (so everything) so you'll run this from the top level of the directory structure.
Note - you might change the patterns to " bo *" to restrict the match set for testing
Comment: Thanks very much for the info, uSlackr.  It was a tough call which answer to choose!  Thank you.


Regression: is it wrong to bin a continuous variable to overcome overfitting?

Question: Would statisticians hang me for doing the following?
I have a heterogeneous dataset of elderly subjects. Thus, I have model with 7 predictors, including 4 categorical ones, of which some have many levels. I am doing a regional analysis, which means that some regions have fewer subjects on certain reference levels of different categorical variables.
Subjects are mostly aged 70-90 years. Age variable, ranging from 50-100, is causing clear overfitting while comparing it to the plots explanatory data analysis. I found out that there are not enough subjects at mean age at some regions to make meaningful predictions. When I bin the age variable into 10-year bins and use the bin with the largest number of subjects as a reference, the results of the regression are in line with the explanatory data analysis.
Would the binning of age variable will be okay if I publish both: plots on raw data + adjusted analysis? Thus, both analysis confirm the main outcome - regional variablity.
Comment: Could you add some plots of the "overfit" and some scatter plot of your variables? I feel like in binning the data you're losing (potentially important) information. The results could also be sensitive to the number and width of bins!
Comment: binning is fine, forget statisticians
Comment: Note that @Aksakal means that as a joke.
Answer: Binning a continuous variable is not a good idea. You're unlikely to be physically assaulted by statisticians for doing that, but you would probably get a lot of hard stares and frowns and muttering under the breath.
There's a much better approach to deal with this type of problem, which would turn the frowns into smiles: use a mixed model. That allows you to combine information usefully among individuals in different regions without having to cover all combinations of predictors within each region. Depending on the purpose of your study that could be done with a multi-level model that treats both individuals and regions as random effects.  This recent answer provides a nice description of the advantages of such modeling.
With respect to age as a continuous predictor, you might find it useful to model with a spline that can discover nonlinear relationships between age and outcome as part of a linear modeling process. That can be incorporated within a mixed model via standard software packages.
Comment: Thank you so much! This multilevel model still overestimates y-values, thus I used splines to overcome the problem: y ~ s(age) + ... + (1 | region). Splines model was slightly better and gave believable conditional y values.
Comment: Thank you so much! I am actually running a multilevel model: y ~ age + ... + (1 | region). Median age slightly differs between regions. Where should I place "age" variable to adjust this between the regions? Adding this as a free slope - (age | region) - would not adjust subject's ages between regions?
Comment: @st4co4 it doesn't matter that median age differs among regions. An `age` fixed effect could handle that directly. A (1|region) term represents random intercepts. If you centered the `age` variable about its median and used `age` as a fixed effect, the random intercepts would be for a (hypothetical) situation in which all subjects had the median age, thus correcting for differences in median age among regions. An (age|region) random slope is only needed if you are looking for _associations of age with outcome_ that differ among regions.


CASE WHEN not working for some values with incorrect syntax

Question: I am trying to do a case when update statement but I keep getting a Incorrect syntax near ''. error. I don't get it because the second query below runs just fine but the first one doesn't. Only difference is I am setting memrvam to 1.24 instead 8.48.
UPDATE a
SET memslam = CASE detseqno
                 WHEN 1923 THEN 338.63
                 WHEN 43 THEN 355.56
              END,
    memrvam = CASE detseqno
                 WHEN 1923 THEN 8.48
                 WHEN 43 THEN 8.89
              END
FROM slst1consl a
LEFT JOIN wprsbatchxref b ON b.batchnum = a.batchid
                          AND b.recdate = a.recdt
                          AND b.supplier_date = a.supdt
WHERE b.batch_id IN(2058708, 2058709)
  AND memid = 922269
  AND detseqno IN (1043, 43);

UPDATE a
SET memslam = CASE detseqno
                 WHEN 1923 THEN 338.63
                 WHEN 43 THEN 355.56
              END,
    memrvam = CASE detseqno
                 WHEN 1923 THEN 1.24
                 WHEN 43 THEN 8.89
              END
FROM slst1consl a
LEFT JOIN wprsbatchxref b ON b.batchnum = a.batchid
                          AND b.recdate = a.recdt
                          AND b.supplier_date = a.supdt
WHERE b.batch_id IN (2058708, 2058709)
  AND memid = 922269
  AND detseqno IN (1043, 43);

Answer: There are hidden special characters there:
                THEN 8.48

When copying this line to my editor I see
                THEN ?8.48?

So, just remove the line and write it anew.
Comment: I'm glad I saved you from doing so :D


Choosing the number of components of a linear model via cross-validation

Question: Background
I have a series of Principal Components which I'm regressing on some data (it's a Blind Source Separation problem; I assume that my data is a linear combination of signals which I obtained via PCA), and I have to decide on the number of components for the model; I chose to do this via $K$-fold Cross-Validation.
The problem
I'm having problems because the number of components chosen via CV is highly sensitive to the choice of $K$, the number of folds of the CV procedure. I have $n=40$ datapoints and a maximum of 8 components to regress the data on. Here's an example of a $10$-fold Cross-Validation procedure:

In this case, the minimum CV error occurs using 8 components, but the value 1-SE away from this value is 3, so I might be tempted to use 3 components in this case. However, in this case the validation folds are too small, and that explains the high variance on the CV-error. If I instead use, e.g., $5$-fold CV, then the value 1-SE away from the minimum is 7 components; this number oscillates for each value of $K$ and so does the number of components where the global minimum is.
My approach
After looking at several CV plots for different $K$'s, I noted that there is always a local minimum at 4 components, followed by an increase in the CV-error on components $>4$, followed by a global minimum on components $7-8$. Considering that I'm using principal components, it seems reasonable to me to use this number as the 'optimal' number of components because this is the first minimum I encounter counting from the lowest to the highest number of components (considering that the number of components are ordered in terms of their eigenvalues). I find that this reasoning, however, is by no means 'clean' or an 'elegant' solution/explaination to the problem at hand; it just seems intuitive to me...do you have any advice on expanding this solution or proposing another one?
Comment: In case you are still interested in that: can you describe how exactly you did the cross-validation? How was the CV error computed? One has to be careful to do it correctly for PCA, and I suspect you might have done it wrong.
Comment: In addition to my previous question: are you doing CV to find an optimal number of PCA components (independent of what you are doing with these components afterwards)? Or are you using your components for something else, and the CV includes this other stuff as well?
Answer:
Does your data have a structure that allows interpretation of the loadings? That is, can you check the loadings and see whether they can possibly carry information?
Where do the error bars come from? Different folds or different repetitions/iterations of the complete cross validation?
You observe that the CV results oscillate depending on the number of folds. How much is this "oscillation" compared to the variation you observe for iterations of CV with the same K (that is, new random assignments of the cases to the K folds)?
The concern with 4 components is that it may already be one component too much, and this could lead to overfitting/unstable models  and thus to worse predictions. How does the training (resubstitution) error evolve? Is it lower than the cross validation results? Where does it start to show differences?
(Remember that you need a separate test set or independent outer cross validation to measure the predictive ability of the final model you build)
Comment: Hi, answering your questions; (1) It's really hard to tell. The structure of the loadings is complex enough to not be anything like I would expect them to be. (2) The error bars come from different folds. I take the model with $p$ components and fit it to the $k$-th fold, from $k=1$ to $k=K$. Each of these fits gives me a mean cv-error, which I then average over all the folds; from there I obtain the standard errors.
Comment: (3) It's pretty stable, although for smaller $K$ it tends to select 7 to 8 components, which is way too many components for my application. (4) I didn't get this part, what do you mean by 'how does the training (resubstitution) error EVOLVE'?
Comment: @Néstor: I think you should do several runs of the randomly split CV for 1 to 8 components and plot the differences between those runs (disregarding the recommendations of the CV). As each run of the CV tests each case exactly once, the variation between the runs tells you whether the models are unstable, which is another indicator of too many components.
Comment: @Néstor: pretty stable, but differences in the error bars depending on $k$ is weird (unless there is really a systematic dependency on k - which would be a rather alarming situation [leave one out is known to show such behaviour in certain cases, though]). With (4) I mean, plot resubstitution error in the same graph. Is it much different, does it get more different (more overoptimistic) with more components?
Comment: (you do take into account for the standard error that the total no. of cases is the same independent of K, i.e. that you calculate standard error for a mean of means, right?)
Comment: I didn't get your final comment, can you elaborate on that? What I'm currently doing for each model is the following: for each fold I get a mean cv-error. That gives me $K$ samples of the cv-error. My final cv-error for a given model is the mean of those values, and to get the standard error, I get the sample standard deviation of those values and divide it by the square root of the number of folds (i.e., $\sqrt{K}$).
Comment: @Néstor: let's say you have values of 40 independent cases. a) 8-fold CV: In a first step, you take the mean of each 5 of them, reducing the results to 8 values. In a second step, you average those 8 means of 5 values into 1 value. b) 5-fold CV: You first average blocks of 8 values, and then average the resulting 5 values. If the original 40 values are the same, the standard error of the mean must be the same: it is independent of any intermediate averaging steps. In other words, you need to take into account that the 5 results of 5-fold CV are more precise because 8 values were averaged than
Comment: ... the 8 results of 8-fold CV. In a first approximation, the sample size for the SE calculation should be the whole 40 in all cases. In reality, the variance between the folds can be larger than what is due to the fact that $\frac{N}{K}$ cases were averaged during each CV fold: the K "surrogate" models may differ from each other (instability), which is a new source of variance.


Read a list and add them to curl with different domains

Question: I have a list of URLs which I want to test some headers on in sequence. For example, I have the following headers:
X-Forwarded-For:
X-Forwarded-Host:

And there are the following URLs:
https://example.com/
https://target.com/
https://redacted.com/

I want to add the first header X-Forwarded-For: to curl and run it over all URLs in sequence, then add the second header X-Forwarded-Host: to curl and run curl over URLs and so on and so forth.
curl --silent -I --max-time 10 --url https://example.com/ -H "X-Forwarded-For: myserver.com"
curl --silent -I --max-time 10 --url https://target.com/ -H "X-Forwarded-For: myserver.com"
curl --silent -I --max-time 10 --url https://redacted.com/ -H "X-Forwarded-For: myserver.com"

curl --silent -I --max-time 10 --url https://example.com/ -H "X-Forwarded-Host: myserver.com"
curl --silent -I --max-time 10 --url https://target.com/ -H "X-Forwarded-Host: myserver.com"
curl --silent -I --max-time 10 --url https://redacted.com/ -H "X-Forwarded-Host: myserver.com"

I wrote the following code:
function myfunc {

    if [[ -f "allurls.txt" ]]; then

        headers_list=("X-Forwarded-For: "
                    "X-Forwarded-Host: "
                    )

        for headers in $(cat "allurls.txt"); do

            for curlme in ${headers_list[@]}; do
                (
                curl --silent -I --max-time 10 --url "$headers" -H "$curlme myserver.com"
                )
            done

        done
    fi
}
myfunc

The problem with my code is that it executes curl like this:
curl --silent -I --max-time 10 --url https://example.com/ -H "X-Forwarded-For: myserver.com"
curl --silent -I --max-time 10 --url https://example.com/ -H "X-Forwarded-Host: myserver.com"

curl --silent -I --max-time 10 --url https://target.com/ -H "X-Forwarded-For: myserver.com"
curl --silent -I --max-time 10 --url https://target.com/ -H "X-Forwarded-Host: myserver.com"

curl --silent -I --max-time 10 --url https://redacted.com/ -H "X-Forwarded-For: myserver.com"
curl --silent -I --max-time 10 --url https://redacted.com/ -H "X-Forwarded-Host: myserver.com"

Comment: swap the `for` loops. make the inner the outer and the outer the inner
Answer: Swap the for loops making the inner loop the outer and vice-versa
...
        # swap these 2 lines
        for curlme in ${headers_list[@]}; do

            for headers in $(cat "allurls.txt"); do
...

PS: I believe the variable names got mixed and this might be more readable and what you expect
...
        # swap these 2 lines
        for header in ${headers_list[@]}; do

            for curlme in $(cat "allurls.txt"); do
                curl --silent -I --max-time 10 --url "$curlme" -H "$header myserver.com"
...

Making an addition for a more natural *nix script
aka pro-moves
...
            # it's common to use while-read loops with files
            while read curlme; do
                curl --silent -I --max-time 10 --url "$curlme" -H "$header myserver.com"
            done < allurls.txt
...

Comment: Great, Thank You!
Comment: @sof31 take a look at the addition made. always good to know an additional technique it two :)


Sql Procedimento

Question: Boa tarde, alguém me pode ajudar a criar um procedimento na base de dados em SQL ?
Para fazer uma reserva de um quarto, eu tenho que selecionar um quarto e declarar a DataEntrada  e a DataSaida.
O que pretendo, é se fizer uma reserva no quarto 1 entres os dias 13/06/2018 e 14/06/2018, e depois se alguém quiser fazer outra reserva nesse mesmo quarto entre os dias 13/06/2018 e 14/06/2018, dado que esse quarto já possui uma reserva nesse dia, eu quero que apareça uma mensagem a dizer ocupado. Alguém me consegue ajudar?
Tabela reserva
 public partial class Reserva
    {
        public int ID_Reserva { get; set; }
        public int ID_Cliente { get; set; }
        public int ID_Quarto { get; set; }
        public System.DateTime DataEntrada { get; set; }
        public Nullable<System.DateTime> DataSaida { get; set; }
        public int NumeroPessoas { get; set; }
        public Nullable<int> NumeroNoites { get; set; }
        public Nullable<decimal> Preço { get; set; }
        public string Observaçoes { get; set; }

        public virtual Cliente Cliente { get; set; }
        public virtual Quarto Quarto { get; set; }
    }

Tabela Quarto
public partial class Quarto
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Quarto()
    {
        this.Reserva = new HashSet<Reserva>();
    }

    public int ID_Quarto { get; set; }
    public string TipoQuarto { get; set; }
    public string EstadoQuarto { get; set; }
    public Nullable<decimal> PreçoQuarto { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Reserva> Reserva { get; set; }
}

Comment: Você precisa fornecer algumas informações a mais para que possamos ajudar. A primeira é qual o `SGBD` que você está utilizando. `SQL Server`? A segunda é informar quais tabelas estão envolvidas nessa reserva.
Comment: Tu precisa utilizar a cláusula BETWEEN e informar a data de saída e entrada, considerando que esteja usando SQL. Já existem preguntas respondidas sobre isso.
Comment: @Sorack obrigado pela resposta. Estou a usar SQL Server . Editei a pergunta e pode ver as tabelas, cumprimentos.
Comment: Alguma das resposta lhe foi útil? Não esqueça de escolher uma e marcar o ✅ para que possa ser utilizada caso alguém tenha uma dúvida similar!
Answer: Você pode utilizar um procedimento como o exemplificado a seguir:
CREATE PROCEDURE reservar(@id_quarto    INT,
                          @data_entrada DATE,
                          @data_saida   DATE)
AS
BEGIN
  DECLARE @dias TABLE(dia DATE);

  -- Gera um registro para cada dia dentro do período de datas escolhido
  WITH dias AS (
    SELECT @data_entrada AS dia
     UNION ALL
    SELECT DATEADD(DAY, 1, d.dia)
      FROM dias d
     WHERE d.dia < @data_saida
  )
  INSERT INTO @dias(dia)
  SELECT d.dia
    FROM dias d;

  -- Verifica se existe uma reserva para algum dos dias que foi informado
  IF EXISTS(SELECT 1
              FROM reserva r
             INNER JOIN @dias d ON d.dia BETWEEN r.data_entrada AND r.data_saida
             WHERE r.id_quarto = @id_quarto)
  BEGIN
    RAISERROR('Já existe uma reserva para a data informada no quarto desejado', 16, 1);
    RETURN;
  END;

  INSERT INTO reserva(id_quarto, data_entrada, data_saida)
               VALUES(@id_quarto, @data_entrada, @data_saida);
END;
GO

No procedimento acima geramos uma lista de dias dentro do intervalo informado e buscamos uma reserva que tenha conflito com a data e quarto escolhido. Caso não ocorra conflito nestes termos, um registro é inserido na tabela reserva.
Comment: muito obrigado pela ajuda! está-me a dar erro no parêntese daqui  `RAISERROR('Já existe uma reserva para a data informada no quarto desejado');` a datas estão no formato "dd/MM/yyyy hh:mm:ss" e em nada irá atrapalhar certo?
Comment: @Heftysilva havia esquecido alguns parâmetros. Tente dessa forma
Comment: executei sem qualquer erro. Agora para implementar esse procedimento, tenho que atualizar o modelo, carregar o procedimento e associa-lo a tabela reserva? estou a usar MVC

Sql Procedimento


Solving differential equation with $y^{'}y^{''}$

Question: How can this differential equation be solved?
$$y'y'' - t = 0$$
I can't figure this out and the $y'y''$ is giving me trouble since they are attached together.
Comment: Hint: What happens when you differentiate $(y')^2$?
Comment: Is $t$ a variable or a constant? What is $y$ a function of?
Answer: Here's a more pedestrian idea than what I've seen suggested in answers and comments so far: Let $u=y'$, so that $u'=y''$.  Then you have
$$
uu'-t=0
$$
$$
u\frac{du}{dt} - t =0
$$
$$
u \, du = t\,dt
$$
$$
\frac{u^2}2 = \frac{t^2}2 + \text{constant.}
$$
Postscript in response to a comment below:
$$
y' = \pm\sqrt{t^2+C}.
$$
If $y'(1)=1$ then we have
$$
y' = \sqrt{t^2+C}, \text{ so }1 = \sqrt{1^2+C},\text{ and so }C=0.
$$
Now
$$
y' = \sqrt{t^2} = t \text{ (if $t>0$)}.
$$
Comment: What if I have initial conditions y(1)=2 and y'(1)=1? This gets confusing with the + or - before the square root… y' = +- sqrt(t^2 + 2C).  When 1 = +- sqrt(1+2C), then C = 0, and then y' = +- sqrt(t^2 + 0) = +- sqrt(t^2) = +- t… When we go to solve y = +- t^2/2 + D, D can vary based on the +-… Any idea how to solve this with initial condition? @Michael Hardy
Comment: How did you get the +- 2 on the outside of the square root?  Shouldn't it be +-sqrt((t^2) + 2C)?? @Michael Hardy
Comment: Sorry, I made it too complicated.  If $y'(1)$ had been any number besides $1$, those complications would have been needed, but as it is, they were not.  I've edited accordingly.
Answer: Hint: The expression that is giving trouble is the derivative of $\frac{1}{2}(y')^2$.
Answer: Make $z = y'$. So your equation becomes $zz' = t$. Integrating w.r.t $t$, you get: $$\frac{z^2}{2} = \frac{t^2}{2} + c_1, \quad c_1 \in \Bbb R$$
That means: $$y' = \sqrt{t^2 + c_1}\quad c_1 \in \Bbb R$$
(this $c_1$ is twice the old one).
Hence: $$y = \int \sqrt{t^2 + c_1} \ \mathrm{d}t + c_2, \quad c_1, c_2 \in \Bbb R.$$


How to call Groovy or Scala UDF to update Oracle, using Java?

Question: I have a JDBC connection to an Oracle DB. I also have some function f(x) written in Groovy or Scala. For example, f(x) simply returns 2x.
Now my question is: how should I call this f(x) in my Java code, to apply f(x) to all values in a column, and update this column to 2x in the above example?
Answer: You can use withColumn api to update the column's values.
If your function is returning a constant lit should be a good choice. You can find a lot of functions too.
You can use udf function too as
def func = udf((column: Int)=> 2*column)
dataframe.withColumn("column1", func(dataframe("column1")))

but udf function would need serialization and deserialization column values. So if other functions should be preferred.
Comment: Thank you! But this is using Spark, right? My problem is that the majority of my code is in Java. I'm using JDBC to connect to Oracle, and hope to be able to call functions written in other languages such as Groovy/Scala etc.
Comment: Yes thats right. The solution is for spark. but you can use udf for other cases too as udf was originally created for hive.


Lua table - When a lower index is removed the higher index all moved down 1 place to fill the spot

Question: Using Lua used is 5.1
I'm trying to get a dictionary table and store it in a table where i have a key index and the value being the data, something like:
tParams = {
    {1st table data...}  -- this one is key index 1
    {2nd table data...}  -- 2nd index
    ...
}

I'm using this code to store it:
tParams[index] = i     --i being a dictionary table

I can add the code in the right index and the table is output if called, so all fine
1   table: 0xa4a2fc0
2   table: 0x9f7c4c0

Now the problem is if I remove for example the first index data, i DON'T want the 2nd index data to move to the 1st position just because it's empty it just takes it place and becomes index 1... how can I avoid that?
Or if you have another solution in general, what i wanna do is store dictionary table data i'm getting, and if called, to be able to get the data and work with it and if i don't need them anymore to remove them.
There can be many multiple dictionaries depending on how many of the instances are created so i can't just pre make them.
They will be dynamic basically... and every time they have a specific id they come with so 2 dictionaries will not have the same id.
If a dictionary is removed, the other dictionaries should not move and stay in the same index/id so they can be called and be the right data.
I hope i was clear, also please don't suggest any supplementary modules.
Thanks!
Answer: You're not providing all the relevant code, but the basic way to remove an item from a table is tParams[index] = nil. That should not cause the problem you're describing.
It sounds as if you're using table.remove. That function is used for maintaining a proper sequence, so that the # operator and some standard library functions can be meaningful for it.
Comment: Perfect, exactly what i needed!
I was indeed using the table.remove, adding the nil did the trick! :D
Thanks!!!


Calculate Time Difference Between Two Pandas Columns in Hours and Minutes

Question: I have two columns, fromdate and todate, in a dataframe.
import pandas as pd

data = {'todate': [pd.Timestamp('2014-01-24 13:03:12.050000'), pd.Timestamp('2014-01-27 11:57:18.240000'), pd.Timestamp('2014-01-23 10:07:47.660000')],
        'fromdate': [pd.Timestamp('2014-01-26 23:41:21.870000'), pd.Timestamp('2014-01-27 15:38:22.540000'), pd.Timestamp('2014-01-23 18:50:41.420000')]}

df = pd.DataFrame(data)

I add a new column, diff, to find the difference between the two dates using
df['diff'] = df['fromdate'] - df['todate']

I get the diff column, but it contains days, when there's more than 24 hours.
                   todate                 fromdate                    diff
0 2014-01-24 13:03:12.050  2014-01-26 23:41:21.870  2 days 10:38:09.820000
1 2014-01-27 11:57:18.240  2014-01-27 15:38:22.540  0 days 03:41:04.300000
2 2014-01-23 10:07:47.660  2014-01-23 18:50:41.420  0 days 08:42:53.760000

How do I convert my results to only hours and minutes (i.e. days are converted to hours)?
Answer: Pandas timestamp differences returns a datetime.timedelta object. This can easily be converted into hours by using the *as_type* method, like so
import pandas
df = pandas.DataFrame(columns=['to','fr','ans'])
df.to = [pandas.Timestamp('2014-01-24 13:03:12.050000'), pandas.Timestamp('2014-01-27 11:57:18.240000'), pandas.Timestamp('2014-01-23 10:07:47.660000')]
df.fr = [pandas.Timestamp('2014-01-26 23:41:21.870000'), pandas.Timestamp('2014-01-27 15:38:22.540000'), pandas.Timestamp('2014-01-23 18:50:41.420000')]
(df.fr-df.to).astype('timedelta64[h]')

to yield,
0    58
1     3
2     8
dtype: float64

Comment: The astype workaround works, but it is too slow for large (0.5 Million rows) files. Any other suggestions?
Comment: I get the error Cannot convert from timedelta64[ns] to timedelta64[h]. Supported resolutions are 's', 'ms', 'us', 'ns'
Answer: This was driving me bonkers as the .astype() solution above didn't work for me.  But I found another way.  Haven't timed it or anything, but might work for others out there:
t1 = pd.to_datetime('1/1/2015 01:00')
t2 = pd.to_datetime('1/1/2015 03:30')

print pd.Timedelta(t2 - t1).seconds / 3600.0

...if you want hours.  Or:
print pd.Timedelta(t2 - t1).seconds / 60.0

...if you want minutes.
UPDATE: There used to be a helpful comment here that mentioned using .total_seconds() for time periods spanning multiple days. Since it's gone, I've updated the answer.
Answer:
How do I convert my results to only hours and minutes?

The accepted answer only returns days + hours. Minutes are not included.

To provide a column that has hours and minutes as hh:mm or x hours y minutes, would require additional calculations and string formatting.
This answer shows how to get either total hours or total minutes as a float, using timedelta math, and is faster than using .astype('timedelta64[h]').

As per pandas v2.0.0, .astype('timedelta64[h]') is not allowed.

Pandas Time Deltas User Guide
Pandas Time series / date functionality User Guide
python timedelta objects: See supported operations.
The following sample data is already a datetime64[ns] dtype. It is required that all relevant columns are converted using pandas.to_datetime().
Tested in python 3.11.2, pandas 2.0.1, numpy 1.24.3

import pandas as pd

# test data from OP, with values already in a datetime format
data = {'to_date': [pd.Timestamp('2014-01-24 13:03:12.050000'), pd.Timestamp('2014-01-27 11:57:18.240000'), pd.Timestamp('2014-01-23 10:07:47.660000')],
        'from_date': [pd.Timestamp('2014-01-26 23:41:21.870000'), pd.Timestamp('2014-01-27 15:38:22.540000'), pd.Timestamp('2014-01-23 18:50:41.420000')]}

# test dataframe; the columns must be in a datetime format; use pandas.to_datetime if needed
df = pd.DataFrame(data)

# add a timedelta column if wanted. It's added here for information only
# df['time_delta_with_sub'] = df.from_date.sub(df.to_date)  # also works
df['time_delta'] = (df.from_date - df.to_date)

# create a column with timedelta as total hours, as a float type
df['tot_hour_diff'] = (df.from_date - df.to_date) / pd.Timedelta(hours=1)

# create a colume with timedelta as total minutes, as a float type
df['tot_mins_diff'] = (df.from_date - df.to_date) / pd.Timedelta(minutes=1)

# display(df)
                  to_date               from_date             time_delta  tot_hour_diff  tot_mins_diff
0 2014-01-24 13:03:12.050 2014-01-26 23:41:21.870 2 days 10:38:09.820000      58.636061    3518.163667
1 2014-01-27 11:57:18.240 2014-01-27 15:38:22.540 0 days 03:41:04.300000       3.684528     221.071667
2 2014-01-23 10:07:47.660 2014-01-23 18:50:41.420 0 days 08:42:53.760000       8.714933     522.896000

Other methods

An item of note from the podcast in Other Resources, .total_seconds() was added and merged when the core developer was on vacation, and would not have been approved.

This is also why there aren't other .total_xx methods.

# convert the entire timedelta to seconds
# this is the same as td / timedelta(seconds=1)
(df.from_date - df.to_date).dt.total_seconds()
[out]:
0    211089.82
1     13264.30
2     31373.76
dtype: float64

# get the number of days
(df.from_date - df.to_date).dt.days
[out]:
0    2
1    0
2    0
dtype: int64

# get the seconds for hours + minutes + seconds, but not days
# note the difference from total_seconds
(df.from_date - df.to_date).dt.seconds
[out]:
0    38289
1    13264
2    31373
dtype: int64

Other Resources

Talk Python to Me: Episode #271: Unlock the mysteries of time, Python's datetime that is!

Timedelta begins at 31 minutes
As per Python core developer Paul Ganssle and python dateutil maintainer:

Use (df.from_date - df.to_date) / pd.Timedelta(hours=1)
Don't use (df.from_date - df.to_date).dt.total_seconds() / 3600

pandas.Series.dt.total_seconds
.dt accessor

Real Python: Using Python datetime to Work With Dates and Times
The dateutil module provides powerful extensions to the standard datetime module.

%%timeit test
import pandas as pd

# dataframe with 2M rows
data = {'to_date': [pd.Timestamp('2014-01-24 13:03:12.050000'), pd.Timestamp('2014-01-27 11:57:18.240000')], 'from_date': [pd.Timestamp('2014-01-26 23:41:21.870000'), pd.Timestamp('2014-01-27 15:38:22.540000')]}
df = pd.DataFrame(data)
df = pd.concat([df] * 1000000).reset_index(drop=True)

%timeit (df.from_date - df.to_date) / pd.Timedelta(hours=1)
[out]:
24.2 ms ± 2.6 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit (df.from_date - df.to_date).astype('timedelta64[h]')
[out]:
ValueError: Cannot convert from timedelta64[ns] to timedelta64[D]. Supported resolutions are 's', 'ms', 'us', 'ns'

Answer: By default, time difference in pandas is in nanosecond resolution, i.e. timedelta64[ns], so one way to convert it into seconds/minutes/hours/etc. is to divide its nanosecond representation by 10**9 to convert to seconds, by 60*10**9 for minutes etc. This method is at least 3 times faster than other methods suggested on this page.1
df['diff_in_seconds'] = df['from_date'].sub(df['to_date']).view('int64') // 10**9
df['diff_in_minutes'] = df['from_date'].sub(df['to_date']).view('int64') // (60*10**9)
df['diff_in_hours'] = df['from_date'].sub(df['to_date']).view('int64') // (3600*10**9)

PS: The above code assumes that you want the difference in whole seconds, minutes, hours etc. so it uses integer division (//) but if you want the fractions as well, then use true division (/) instead. That said, if you want the exact difference, then instead of fractional seconds/minutes/hours, consider converting the difference into higher resolution (milliseconds/microseconds/etc.)

1 Some benchmarks using Trenton McKinney's setup:
data = {'to_date': [pd.Timestamp('2014-01-24 13:03:12.050000'), pd.Timestamp('2014-01-27 11:57:18.240000')]*1000000,
        'from_date': [pd.Timestamp('2014-01-26 23:41:21.870000'), pd.Timestamp('2014-01-27 15:38:22.540000')]*1000000}
df = pd.DataFrame(data)
df['Diff'] = df['from_date'] - df['to_date']

%timeit df['Diff'].view('int64') // (3600*10**9)
# 11 ms ± 271 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%timeit df['Diff'] // pd.Timedelta(hours=1)
# 36.7 ms ± 2.99 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)

%timeit df['Diff'].astype('timedelta64[h]')
# 46.5 ms ± 865 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%timeit df['Diff'].dt.total_seconds() // 3600
# 169 ms ± 7.71 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)


How to test if a functions is called in React?

Question: Working template of the project: https://codesandbox.io/s/blue-currying-3me1t
The only test I have set up is in src/App.test.js to check that a name is rendered. I am trying to setup another test that checks to see if a function is called before the buttons are generated.
In FontAwesome.js there is a registerIcons() function that registers all of the icons needed for the website. I call this function in Buttons.js as it is the place where I use the icons.
I want to create a test in App.test.js that checks to see if registerIcons() is called before the buttons are created in Buttons.js.
Comment: FYI, may be below link will help you. https://stackoverflow.com/questions/40393486/test-if-function-is-called-react-and-enzyme
Comment: Not really helpful for my case. They are testing render on click via simulation.
Answer: You could typically do this by manually mocking your FontAwesome dependency like this:
import React from "react";
import { render } from "@testing-library/react";
import Button from "./Buttons.js";
import registerIcons from './FontAwesome'

jest.mock('./FontAwesome', () => ({
  __esModule: true
  default: jest.fn()
}))

test("registers icons", () => {
  render(<Button />);

  expect(registerIcons).toHaveBeenCalled();
});

However, it seems code sandbox does not currently support mocking. You could try it in your own IDE though.
Comment: I am getting an error that says `TypeError: (0 , _FontAwesome.default) is not a function` and all of the stackoverflow answers for this error involved incorrectly implemented import statements. However, I think that all of my import statements are formatted correctly. Any suggestions?
Comment: I missed the `__esModule: true` from the export. I've just added it to my answer, try including that


Why assign global variable to value inside a callback function in node js return undefined in console?

Question: Take this example
var s;
cb = function(error,result){
s = result;
}
memcached.get('hellow',cb);
console.log(s);

This give me undefined. What is wrong with my code?
Comment: The answers on this question so far have been great; I wanted to mention that you may be interested in this screencast, which covers this exact issue: http://nodecasts.net/episodes/5-thinking-asynchronously
Answer: The console.log(s); line executes before the cb function does because cb isn't called by memcached.get until result is available.  This is the classic asynchronicity that occurs with any I/O operation in node.js.
Comment: To cut a long story short: You can't - at least not without additional helpers such as the already mentioned `async` module.
Comment: yes, but how i could get the `s` value outside callback function?
Comment: Not quite sure what you're asking.  Any code that relies on the result of the `memcached.get` must execute after the callback is called.  So you can put your code that references `s` in the callback, or use a flow control library like [async](https://github.com/caolan/async) to execute another function after `cb` is called.
Answer: You need to execute console.log after defining s because it asynchronous:
var s;
cb = function(error,result){
    s = result;
    console.log(s);
}
memcached.get('hellow',cb);

Comment: good but is there is another way to get `s` value outside callback function?
Comment: call external function, emit event or wait some time with setTimeout (not the best way)
Answer: The variable s is being initialized within a call back function. This call back function will get triggered only when memcached.get() completes getting the data for 'hellow'.
Javascript reliesy on the event loop mechanism. This means that the javascript runtime will continue executing the script until it reaches the end without blocking for any callback to occur.
As a result in your example, the javascript runtime will execute the line console.log(s) immediately after the line memcached.get('hellow',cb) without blocking. Hence console.log(s) in your case will print a valid value (other then undefined) only if the cb has executed prior to the last line.
Please move the line console.log(s) within the call back function for more consistent results.
Comment: it seams that this is the only way to achieve result


Possible to add a organic group role programmatically?

Question: Im trying to programmatically add OG group roles and assign permissions through an update hook. Is this possible?
Comment: You asking to add a new og role by programmatic way?not adding existing og role to a user, right?
Comment: thats correct, I'd like to add a new og role programmatically
Answer: It seems that hook_og_default_roles() will only assign the role to new group members. The role must first exist in the roles table. You can do this by creating it in the OG UI or by using og_role_create() and og_role_save () as above.
Comment: Sorry correction. It does use this hook but only on the **first** time an entity group type (bundle) is created. The code checks that roles exist for the group type and returns if it finds them, so after they are created for the first instance of a group type it never calls the hook again.
Answer: If you just want to add a role, the recommended way is through hook_og_default_roles(). This will add the og role when the module is enabled.
If you have to add it in an update or only when a certain condition is met, then you can use the API function og_role_create() (using only the first parameter) and og_role_save().
Permissions can be created through hook_og_permission() and granted to the role with og_role_grant_permissions().


How to model the vaccination of healthcare and frontline workers?

Question: Let us consider the standard SEIR model with additional vaccination compartment:
\begin{eqnarray*}
\frac{dS}{dt}&=& -\beta \frac{SI}{N} - bS \\
\frac{dV}{dt}&=& bS - \epsilon(\beta \frac{VI}{N}) \\
\frac{dE}{dt}&=& \beta \frac{SI}{N} + \epsilon(\beta \frac{VI}{N}) - \alpha E \\
\frac{dI}{dt}&=& \alpha E - \gamma I\\
\frac{dR}{dt}&=& f\gamma I\\
\end{eqnarray*}
Here I assume that $V$ is the number of healthcare and frontline workers who are vaccinated. Now, in reality, there are only a limited number of such individuals. Thus, I want to alter the parameter $b$ so that the number of vaccinated persons cannot exceed a specific number, say $K.$ Your suggestions are so much appreciated.
Answer: This is an answer to my question: Take $$b = r \left( 1 - \frac{V}{K} \right)$$ where $r$ is some constant.


Insert ajax data to database based on model

Question: I use ajax form data and get these data:
model[lat]:39.5500507
model[lng]:-105.78206740000002
model[width]:100
model[widthIn]:%
model[height]:300
model[mapTypeId]:ROADMAP
model[zoom]:15

I use wordpress in the server side. All I want to do is to insert them into database using $wpdb all in once like:
$modeldata = $_POST["something that represents whole model data"]

And then insert an array like:
array($modeldata -> $modeldata)

So each model data will be placed into their respective column with the same name in database. For example, model[width] in column width, model[height] in column height.
Is something like that possible instead of inserting them one by one?
NOTE: I have created all the columns name in table so don't assume I haven't
Comment: better to hook the ajax request via [wp_ajax](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)) or [wp_ajax_nopriv](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_nopriv_(action))
Answer: Your post data is as follows
$_POST = array(

   'model' => array(
        'lat' => 39.00
        'lng' => 105.00
        'width' =>
        'widthIn' => %
        ---
   );
);

So in wordpress, to insert these data in say 'geotable' table, use following code block
global $wpdb;
$wpdb->insert('geotable',$_POST['model']);

Comment: Your code doesnt work, is it a must to use `wp_localize_script`?