text:
Q: Microsoft Unity Service is null when controller is hit I'm looking at Microsoft Unity injection for a webapi we've based on the full stack code i found here;
Full Stack WebApi GitHub Repo
Now when I run the code and hit the patients controller in this case, the
[Dependency]
public PatientService PatientService { get; set; }

is null.
Now the patient service is the entity having the context injected into its constructor.
public class PatientService : BaseService
{
    private readonly Func<IUCareDataContext> _contextFactory;

    /// <summary>
    /// Initializes a new instance of the <see cref="PatientService"/> class.
    /// </summary>
    /// <param name="contextFactory">The context factory.</param>
    public PatientService(Func<IUCareDataContext> contextFactory)
    {
        this._contextFactory = contextFactory;
    }

From looking at the Unity documentation and UnityConfig.cs I can see that the Register is completed, but no Resolve?
namespace CCS.Services.WebApi
{
   using CCS.Data.UCare;
   using Data;
   using Microsoft.Practices.Unity;
   using System.Web.Http;
   using Unity.WebApi;

public static class UnityConfig
{
    public static void RegisterComponents()
    {
        var container = new UnityContainer();

        container.RegisterType<IUCareDataContext, UCareDataContext>();

        GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
    }
}
}

Unity [Dependency] Attribute MSDN
Is this implementation missing something or should the dependency injection just work automatically when the controller is instantiated?
As it was pointed out I could inject the service. But this would then mean I would have to register every service to unity, with all services ultimately having the same context interface being injected to it. I would have thought there is a way around this?


text:
Q: Disable client side form validation in ASP.NET Core How can I disable client-side form validation in my ASP.NET Core 1.1 app? But I need the server-side one.

A: You do this in your ConfigureServices class in your Startup file:
services.AddMvc().AddViewOptions(options =>
    options.HtmlHelperOptions.ClientValidationEnabled = false);

This will work for the attributes generated by tag helpers.

A: you just remove the javascript for jquery.unobtrusive.validation.js
In the VS project templates that is in _ValidationScriptsPartial.cshtml

A: In Razor Pages
services.Configure<HtmlHelperOptions>(o => o.ClientValidationEnabled = false);

See Disable client-side validation

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bash script redirect all output to file I have following script that works fine on desktop CentOS 7, but it does not work correct on server CentOS 7 on digitalocean droplet.
The problem is that it does not auto exit on complete, I have to press enter to exit
#!/bin/bash

LOG_FILE=/var/log/mylog.log

if [ -f $LOG_FILE ]; then
  mv $LOG_FILE $LOG_FILE.$(date +%s)
fi

exec > >(tee -a -i $LOG_FILE)
exec 2>&1

echo "track 1x"
echo "track 2x"

A: Another possible way to structure this code in a way that won't trigger this race condition is to group the rest of the code inside a { ... } block and pipe that to tee.
That way, bash will be guaranteed to wait() for tee to complete before ending the script.
#!/bin/bash

LOG_FILE=/var/log/mylog.log

if [[ -f "$LOG_FILE" ]]; then
  mv "$LOG_FILE" "$LOG_FILE.$(date +%s)"
fi

{
  echo "track 1x"
  echo "track 2x"
} 2>&1 | tee -a -i "$LOG_FILE"

A: It may look like you need to press enter but you don't need to.
The issue is that the next prompt may, sometimes, appear before the output from process substitution with tee completes.  Whether the new prompt appears before or after the tee output depends on the vagaries of multitasking.  It may randomly appear one way or the other.
For example, I ran your script and the output looked like:
$ bash script
$ track 1x
track 2x

The second$ is the new prompt.  The track 1x and track 2x lines are output from tee that appears after the prompt is written.  You may enter a new command without entering enter first.  I did that here for example:
$ bash script
$ track 1x
track 2x
date
Thu Aug  1 22:52:45 PDT 2019

I entered a new command, date, and the command was processed producing the output Thu Aug  1 22:52:45 PDT 2019.  It was not necessary to press enter before typing the new command.

A: I added new line sleep .1 and it worked
@source https://stackoverflow.com/questions/30687504/redirected-output-hangs-when-using-tee
#!/bin/bash

LOG_FILE=/var/log/mylog.log

if [ -f $LOG_FILE ]; then
  mv $LOG_FILE $LOG_FILE.$(date +%s)
fi

exec > >(tee -a -i $LOG_FILE)
exec 2>&1
sleep .1

echo "track 1x"
echo "track 2x"


text:
Q: Convert a data frame to into row vector or long vector I'm not sure what is the exact data type that is but when I see class It shows character and numeric.
My intended data what I want to use small subset is this
a <- dput(head(Age))
structure(list(Blast_Percentage = c(82L, 83L, 91L, 72L, 68L,
88L)), row.names = c("TCGA-AB-2856", "TCGA-AB-2849", "TCGA-AB-2971",
"TCGA-AB-2930", "TCGA-AB-2891", "TCGA-AB-2872"), class = "data.frame")

Second data frame
b <- dput(head(Sample_info))
structure(list(patient = structure(c(35L, 32L, 118L, 93L, 64L,
47L), .Label = c("TCGA-AB-2805", "TCGA-AB-2806", "TCGA-AB-2808",
"TCGA-AB-2810", "TCGA-AB-2811", "TCGA-AB-2812", "TCGA-AB-2813",
"TCGA-AB-2814", "TCGA-AB-2815", "TCGA-AB-2817", "TCGA-AB-2818",
"TCGA-AB-2819", "TCGA-AB-2820", "TCGA-AB-2821", "TCGA-AB-2822",
"TCGA-AB-2823", "TCGA-AB-2825", "TCGA-AB-2826", "TCGA-AB-2828",
"TCGA-AB-2830", "TCGA-AB-2834", "TCGA-AB-2835", "TCGA-AB-2836",
"TCGA-AB-2839", "TCGA-AB-2840", "TCGA-AB-2841", "TCGA-AB-2842",
"TCGA-AB-2844", "TCGA-AB-2845", "TCGA-AB-2846", "TCGA-AB-2847",
"TCGA-AB-2849", "TCGA-AB-2851", "TCGA-AB-2853", "TCGA-AB-2856",
"TCGA-AB-2858", "TCGA-AB-2859", "TCGA-AB-2861", "TCGA-AB-2862",
"TCGA-AB-2863", "TCGA-AB-2865", "TCGA-AB-2866", "TCGA-AB-2867",
"TCGA-AB-2869", "TCGA-AB-2870", "TCGA-AB-2871", "TCGA-AB-2872",
"TCGA-AB-2873", "TCGA-AB-2874", "TCGA-AB-2875", "TCGA-AB-2876",
"TCGA-AB-2877", "TCGA-AB-2878", "TCGA-AB-2880", "TCGA-AB-2881",
"TCGA-AB-2882", "TCGA-AB-2883", "TCGA-AB-2884", "TCGA-AB-2885",
"TCGA-AB-2886", "TCGA-AB-2888", "TCGA-AB-2889", "TCGA-AB-2890",
"TCGA-AB-2891", "TCGA-AB-2892", "TCGA-AB-2893", "TCGA-AB-2894",
"TCGA-AB-2895", "TCGA-AB-2896", "TCGA-AB-2897", "TCGA-AB-2898",
"TCGA-AB-2899", "TCGA-AB-2900", "TCGA-AB-2901", "TCGA-AB-2908",
"TCGA-AB-2910", "TCGA-AB-2911", "TCGA-AB-2912", "TCGA-AB-2913",
"TCGA-AB-2914", "TCGA-AB-2915", "TCGA-AB-2916", "TCGA-AB-2917",
"TCGA-AB-2918", "TCGA-AB-2919", "TCGA-AB-2920", "TCGA-AB-2921",
"TCGA-AB-2924", "TCGA-AB-2925", "TCGA-AB-2927", "TCGA-AB-2928",
"TCGA-AB-2929", "TCGA-AB-2930", "TCGA-AB-2931", "TCGA-AB-2932",
"TCGA-AB-2933", "TCGA-AB-2934", "TCGA-AB-2935", "TCGA-AB-2936",
"TCGA-AB-2937", "TCGA-AB-2939", "TCGA-AB-2940", "TCGA-AB-2942",
"TCGA-AB-2943", "TCGA-AB-2944", "TCGA-AB-2946", "TCGA-AB-2948",
"TCGA-AB-2949", "TCGA-AB-2950", "TCGA-AB-2952", "TCGA-AB-2955",
"TCGA-AB-2956", "TCGA-AB-2959", "TCGA-AB-2963", "TCGA-AB-2965",
"TCGA-AB-2966", "TCGA-AB-2970", "TCGA-AB-2971", "TCGA-AB-2973",
"TCGA-AB-2975", "TCGA-AB-2976", "TCGA-AB-2977", "TCGA-AB-2979",
"TCGA-AB-2980", "TCGA-AB-2981", "TCGA-AB-2982", "TCGA-AB-2983",
"TCGA-AB-2984", "TCGA-AB-2986", "TCGA-AB-2987", "TCGA-AB-2988",
"TCGA-AB-2990", "TCGA-AB-2991", "TCGA-AB-2992", "TCGA-AB-2994",
"TCGA-AB-2995", "TCGA-AB-2996", "TCGA-AB-2998", "TCGA-AB-2999",
"TCGA-AB-3000", "TCGA-AB-3001", "TCGA-AB-3002", "TCGA-AB-3007",
"TCGA-AB-3008", "TCGA-AB-3009", "TCGA-AB-3011", "TCGA-AB-3012"
), class = "factor"), FAB = structure(c(5L, 1L, 5L, 3L, 2L, 4L
), .Label = c("M0", "M1", "M2", "M3", "M4", "M5"), class = "factor")), row.names = c(NA,
6L), class = "data.frame")

The way I want to turn this data frame is into this
> age
 s1  s2  s3  s4  s5  s6  s7  s8  s9 s10 s11 s12 s13 s14 s15 s16 s17 s18 s19 s20 s21 s22 s23 s24 s25 s26 s27 s28 s29 s30 s31 s32 s33 s34 s35 s36 s37 s38
  2   2   5  11  20  32  61  93  93 144 232 303 649 654 904   2   2   5  11  20  32  61  93  93 144 232 303 649 654 904 904   2   2   5  11  20  32  61
s39 s40 s41 s42 s43 s44 s45 s46 s47 s48 s49 s50 s51 s52 s53 s54 s55 s56 s57 s58 s59 s60 s61 s62 s63
 93  93 144 232 303 649 654 904 904   2   2   5  11  20  32  61  93  93 144 232 303 649 654 904 904
> class(age)
[1] "numeric"

and the other one would be for the second data frame it should look like this
samp_tissue
      s1       s2       s3       s4       s5       s6       s7       s8       s9      s10      s11      s12      s13      s14      s15      s16      s17
"Cortex" "Cortex" "Cortex" "Cortex" "Cortex" "Cortex" "Cortex" "Cortex" "Cortex" "Cortex" "Cortex" "Cortex" "Cortex" "Cortex" "Cortex"   "Lung"   "Lung"
     s18      s19      s20      s21      s22      s23      s24      s25      s26      s27      s28      s29      s30      s31      s32      s33      s34
  "Lung"   "Lung"   "Lung"   "Lung"   "Lung"   "Lung"   "Lung"   "Lung"   "Lung"   "Lung"   "Lung"   "Lung"   "Lung"   "Lung"  "Liver"  "Liver"  "Liver"
     s35      s36      s37      s38      s39      s40      s41      s42      s43      s44      s45      s46      s47      s48      s49      s50      s51
 "Liver"  "Liver"  "Liver"  "Liver"  "Liver"  "Liver"  "Liver"  "Liver"  "Liver"  "Liver"  "Liver"  "Liver"  "Liver" "Muscle" "Muscle" "Muscle" "Muscle"
     s52      s53      s54      s55      s56      s57      s58      s59      s60      s61      s62      s63
"Muscle" "Muscle" "Muscle" "Muscle" "Muscle" "Muscle" "Muscle" "Muscle" "Muscle" "Muscle" "Muscle" "Muscle"

How to convert them into above type I would like to know.
I tried to search but Im not sure about the right query to find what Im looking for
Possible solution what I got from this post
whatyouwant <- setNames( as.numeric(Age$Blast_Percentage),as.character(Age$patient))
class(whatyouwant)
what <- setNames( as.character(Sample_info$FAB),as.character(Age$patient))
class(what)
what

A: Your expected outcome is not clear to me (i.e. using your sample data, what should the final outcome be?), but perhaps you're looking for table() (my guess for "a") or deframe() from the tibble package:
library(tibble)

a <- structure(list(Blast_Percentage = c(82L, 83L, 91L, 72L, 68L,
                                    88L)), row.names = c("TCGA-AB-2856", "TCGA-AB-2849", "TCGA-AB-2971",
                                                         "TCGA-AB-2930", "TCGA-AB-2891", "TCGA-AB-2872"), class = "data.frame")
b <- structure(list(patient = structure(c(35L, 32L, 118L, 93L, 64L,
                                     47L), .Label = c("TCGA-AB-2805", "TCGA-AB-2806", "TCGA-AB-2808",
                                                      "TCGA-AB-2810", "TCGA-AB-2811", "TCGA-AB-2812", "TCGA-AB-2813",
                                                      "TCGA-AB-2814", "TCGA-AB-2815", "TCGA-AB-2817", "TCGA-AB-2818",
                                                      "TCGA-AB-2819", "TCGA-AB-2820", "TCGA-AB-2821", "TCGA-AB-2822",
                                                      "TCGA-AB-2823", "TCGA-AB-2825", "TCGA-AB-2826", "TCGA-AB-2828",
                                                      "TCGA-AB-2830", "TCGA-AB-2834", "TCGA-AB-2835", "TCGA-AB-2836",
                                                      "TCGA-AB-2839", "TCGA-AB-2840", "TCGA-AB-2841", "TCGA-AB-2842",
                                                      "TCGA-AB-2844", "TCGA-AB-2845", "TCGA-AB-2846", "TCGA-AB-2847",
                                                      "TCGA-AB-2849", "TCGA-AB-2851", "TCGA-AB-2853", "TCGA-AB-2856",
                                                      "TCGA-AB-2858", "TCGA-AB-2859", "TCGA-AB-2861", "TCGA-AB-2862",
                                                      "TCGA-AB-2863", "TCGA-AB-2865", "TCGA-AB-2866", "TCGA-AB-2867",
                                                      "TCGA-AB-2869", "TCGA-AB-2870", "TCGA-AB-2871", "TCGA-AB-2872",
                                                      "TCGA-AB-2873", "TCGA-AB-2874", "TCGA-AB-2875", "TCGA-AB-2876",
                                                      "TCGA-AB-2877", "TCGA-AB-2878", "TCGA-AB-2880", "TCGA-AB-2881",
                                                      "TCGA-AB-2882", "TCGA-AB-2883", "TCGA-AB-2884", "TCGA-AB-2885",
                                                      "TCGA-AB-2886", "TCGA-AB-2888", "TCGA-AB-2889", "TCGA-AB-2890",
                                                      "TCGA-AB-2891", "TCGA-AB-2892", "TCGA-AB-2893", "TCGA-AB-2894",
                                                      "TCGA-AB-2895", "TCGA-AB-2896", "TCGA-AB-2897", "TCGA-AB-2898",
                                                      "TCGA-AB-2899", "TCGA-AB-2900", "TCGA-AB-2901", "TCGA-AB-2908",
                                                      "TCGA-AB-2910", "TCGA-AB-2911", "TCGA-AB-2912", "TCGA-AB-2913",
                                                      "TCGA-AB-2914", "TCGA-AB-2915", "TCGA-AB-2916", "TCGA-AB-2917",
                                                      "TCGA-AB-2918", "TCGA-AB-2919", "TCGA-AB-2920", "TCGA-AB-2921",
                                                      "TCGA-AB-2924", "TCGA-AB-2925", "TCGA-AB-2927", "TCGA-AB-2928",
                                                      "TCGA-AB-2929", "TCGA-AB-2930", "TCGA-AB-2931", "TCGA-AB-2932",
                                                      "TCGA-AB-2933", "TCGA-AB-2934", "TCGA-AB-2935", "TCGA-AB-2936",
                                                      "TCGA-AB-2937", "TCGA-AB-2939", "TCGA-AB-2940", "TCGA-AB-2942",
                                                      "TCGA-AB-2943", "TCGA-AB-2944", "TCGA-AB-2946", "TCGA-AB-2948",
                                                      "TCGA-AB-2949", "TCGA-AB-2950", "TCGA-AB-2952", "TCGA-AB-2955",
                                                      "TCGA-AB-2956", "TCGA-AB-2959", "TCGA-AB-2963", "TCGA-AB-2965",
                                                      "TCGA-AB-2966", "TCGA-AB-2970", "TCGA-AB-2971", "TCGA-AB-2973",
                                                      "TCGA-AB-2975", "TCGA-AB-2976", "TCGA-AB-2977", "TCGA-AB-2979",
                                                      "TCGA-AB-2980", "TCGA-AB-2981", "TCGA-AB-2982", "TCGA-AB-2983",
                                                      "TCGA-AB-2984", "TCGA-AB-2986", "TCGA-AB-2987", "TCGA-AB-2988",
                                                      "TCGA-AB-2990", "TCGA-AB-2991", "TCGA-AB-2992", "TCGA-AB-2994",
                                                      "TCGA-AB-2995", "TCGA-AB-2996", "TCGA-AB-2998", "TCGA-AB-2999",
                                                      "TCGA-AB-3000", "TCGA-AB-3001", "TCGA-AB-3002", "TCGA-AB-3007",
                                                      "TCGA-AB-3008", "TCGA-AB-3009", "TCGA-AB-3011", "TCGA-AB-3012"
                                     ), class = "factor"), FAB = structure(c(5L, 1L, 5L, 3L, 2L, 4L
                                     ), .Label = c("M0", "M1", "M2", "M3", "M4", "M5"), class = "factor")), row.names = c(NA,
                                                                                6L), class = "data.frame")

table(a)
#> a
#> 68 72 82 83 88 91
#>  1  1  1  1  1  1
deframe(b)
#> TCGA-AB-2856 TCGA-AB-2849 TCGA-AB-2971 TCGA-AB-2930 TCGA-AB-2891 TCGA-AB-2872
#>           M4           M0           M4           M2           M1           M3
#> Levels: M0 M1 M2 M3 M4 M5

Created on 2022-06-29 by the reprex package (v2.0.1)
Or maybe this?
library(tidyverse)

a %>%
  rownames_to_column("patient") %>%
  left_join(b)
#> Joining, by = "patient"
#>        patient Blast_Percentage FAB
#> 1 TCGA-AB-2856               82  M4
#> 2 TCGA-AB-2849               83  M0
#> 3 TCGA-AB-2971               91  M4
#> 4 TCGA-AB-2930               72  M2
#> 5 TCGA-AB-2891               68  M1
#> 6 TCGA-AB-2872               88  M3

Created on 2022-06-29 by the reprex package (v2.0.1)


text:
Q: Como matar, remover ou não inicializar o banco master do SQL Server? Acordei pela manhã e dei um "Executar" em cima do banco "cotacao", banco que eu estou trabalhando no momento. Aí entrou a tela de login e quando eu logei o banco que recebeu as tabelas foi o master e não o "cotacao". No provedor que hospedo meu site e banco, ele não entra. Quando eu logo, é sempre meu banco.
Tem como fazer isso em minha máquina? Escolher um banco padrão e será sempre ele que vai aparecer quando me logar. Como eu faço isso?

A: Se você tiver privilégio pode fazer isto:
ALTER LOGIN pnet WITH DEFAULT_DATABASE = meudb

Coloquei no GitHub para referência futura.


text:
Q: How do I return Data from view back to my edit controller when my view model contained data from 2 different models? I cant figure out how to return the data from my view back to my controller. My view has a view model which contains 2 models. This view model I named Model Holder. I am able to manipulate the data on my view from the Model Holder class with no issues. But When I press the save button I keep on getting errors. Below is code from my ModelHolder class, My View, and my Controller. Any help would be much appreciated.
My ModelHolder Class
    public class ModelHolder
    {
        private LibraryDBEntities db = new LibraryDBEntities();
        public List<Author> authors;
        public List<Book> books;
        int? id;
        public ModelHolder(int? id)
        {
            this.id = id;
            authors = new List<Author>();
            books = new List<Book>();
        }

  }

My View
    @model TM_TWA.ModelHolder

@{
    ViewBag.Title = "Edit";
}

Edit

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

Author

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.authors.FirstOrDefault().Id)

            @Html.LabelFor(model => model.authors.FirstOrDefault().FirstName, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.authors.FirstOrDefault().FirstName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.authors.FirstOrDefault().FirstName, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.authors.FirstOrDefault().LastName, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.authors.FirstOrDefault().LastName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.authors.FirstOrDefault().LastName, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.authors.FirstOrDefault().Website, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.authors.FirstOrDefault().Website, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.authors.FirstOrDefault().Website, "", new { @class = "text-danger" })

                    @Html.DisplayNameFor(model => model.books.First().Title)

                    @Html.DisplayNameFor(model => model.books.First().PublicationDate)

            @foreach (var n in Model.books)
            {

                       @Html.CheckBox(n.Id.ToString(), n.Id.ToString())
                       @Html.DisplayFor(modelItem => n.Title)

                        @Html.DisplayFor(modelItem => n.PublicationDate)

            }

                <input type="submit" value="Save" class="btn btn-default" />

My Controller Method
public ActionResult Edit([Bind(Include = "Id,FirstName,LastName,Website")] Author author, [Bind(Include = "Id")] Book book)
    {
        if (ModelState.IsValid)
        {
            db.Entry(book).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(book);
    }


text:
Q: GET Multiple Values From Multiple Href Politics ~ United States

I'm not quiet sure this is possible in PHP, maybe JavaScript but I don't know much JS.
I want to get multiple GET values from multiple a href links. The code is above. Let's say I click on Politics, and then it'll add the Politics value to the URL, and then I'll click on United States, and I'm trying to add the value of United States to the URL too, but at the moment it's just overwriting the one that's there.
If I click on Politics it adds ?cate=politics, and then if I click United States it adds &cout=us as well. So it'll be something like: ?cate=politics&cout=us.
I'm trying to get both GET variables in the URL when clicking both links. If it helps I'm building a filter that will grab the GET variables.

A: If I understood you, this would be the solution:
Politics ~
United States

Javascript:

Hope this helps. Cheers

A: It seems to me the most obvious solution is hard code it into your HTML (use an ampersand & to add multiple parameters to the URL):
Politics ~
  United States

Otherwise, you'd need a Javascript event handler like onclick, but if you're new to JS the learning curve might be a bit steep for your immediate needs.
UPDATE (after comment)
In that case, here's a starter function you can work from:
HTML:
Click this link

Javascript:
// $(id) is a common library shortcut to get an element by its id.

$('test').onclick = function() {
  $('test').href = $('test').href + '&bar=2';
  alert($('test').href);
}

Not sure what you have in mind after that.  window.location.href = ... could be what you're looking for?
An important note though: this way does not degrade gracefully; your form will not work if the user doesn't enable Javascript.  Personally, I recommend the first solution of hard-coding the parameters.

A: This is possible in multiple page loads. When you load the page:
$cate = isset($_GET['cate']) ? $_GET['cate'] : null;
$cout = isset($_GET['cout']) ? $_GET['cout'] : null;

echo 'Foo';

That "should" do what you are looking for.

A: This can't be done in this way. You have two solutions: make hrefs dynamicly on PHP side (tree based structure - IMHO easiest way with using recursion) or make whole "menu" on browser side in JavaScript (I recomend jQuery) - much complicated, "robots" not supported, problems with browsers compatiblity, etc.
Maybe I haven't understood your problem. Maybe you are expecting this solution:
<?php
echo "Politics";
$cate = $_GET['cate'];
if ($cate) $cate = "cate=$cate&";
echo "United States";


text:
Q: Different font size for UILabel using adaptive layout In Xcode 6 we have a new feature called adaptive layout. By using that I have created a new project in which it I need to have different font size based on the layout.
In iPhone 3.5 inch screen I must have font size as 17pt, and other screen size in iPhone must be 21pt.
Can anyone tell me how I can achieve this using adaptive layout?

A: Yes, you can do with storyboad. There is a + sign on the left of the font, click it and select the size class and choose the font size needed

A: In viewDidAppear or viewWillAppear, you can detect the size of the layout. You only have to update font size based on the detected size.
You can use [[UIScreen mainScreen] bounds]; or in iOS8 : [[UIScreen mainScreen] nativeBounds];


text:
Q: Why the regex that specifies a max length does not work in C# wpf I tried this regex but it doesn't work. I can write as many characters as I want without the validation stopping my entries. I would like to know why. In particular, if I remove the part that handles length, it works fine, but I need to handle length in my project. So I would like to know how to handle the maximum length in a c# regex
private void AlphaValidationTextBox(object sender, TextCompositionEventArgs e)
     {
         if (!Regex.IsMatch(e.Text, "^[a-zA-Z]{0,10}$"))
         {
             e.Handled = true;
         }
     }

A:
I tried this regex but it doesn't work. I can write as many characters as I want without the validation stopping my entries. I would like to know why. In particular, if I remove the part that handles length, it works fine, but I need to handle length in my project

Long story short, the e.Text is the partial issue, especially coming from the TextCompositionEventArgs.
When a user types something into that textbox, the event will be kicked off, but will only contain the value the user entered, not any other previous entered text. In order to check what the user previously entered plus the new value, you would need to concatenate two separate properties.
if (!Regex.IsMatch((e.Source as TextBox)?.Text + e.Text, "^[a-zA-Z]{0,10}$"))
{
   e.Handled = true;
}

In the above example, I am using e.Source which is the textbox itself and its current text (before this new value), plus the new value. The is the exact reason why you're only getting a length of one.
Please note, there are other ways to validate data as well, but not related to this post and would be too long.


text:
Q: VS2008 deployment project. Change UpgradeCode for every build Is it possible to setup vdproj so as new UpgradeCode is generated for every new .msi?
Why I need this. We have only one deployment project, only one application. It is very convenient (for non-developing audience) to double-click .msi file and reinstall it disregarding any other application already installed. Most often it is necessary when QA guys need to install same version (but different .msi) into their system.
Thank you.

A: You should be able to use some of the information in the first answer for the question How to keep the installer's version number in sync with the installed assemblies' version numbers?
They reference a script at CodeProject which you could modify to do what you wanted:
http://www.codeproject.com/KB/install/NewSetupVersion.aspx


text:
Q: Java returning subclass without generic parameter in superclass method I really love using initializers to make constructing and configuring classes more understandable. Basically I prefer this:
new ClassObj().StartingFrom(1).EndingAt(5).IncrementBy(1).Backwards();

Rather than this:
new ClassObj(1,5,1,false);

This is a bit of a pain in Java when mixed with inheritance, as returning types default to as generic as possible. I've found a workable solution using self-referential inheritance (Java: returning subclass in superclass method signature), but I'm having some problems with it.
My issue is that the Parent class implements Iterable, but the generic type parameter gets lost, so the for-each loop wants to return an Object instead of a File.
Here's an SSCCE showing the behavior:
public class SSCCE {
  private static abstract class Sentence<T extends Sentence<T>> implements Iterable<String> {
    protected LinkedList<String> Words = new LinkedList<>();

    abstract T self();

    public T Say(String word) {
      Words.add(word);
      return self();
    }

    @Override
    public Iterator<String> iterator () {
      return Words.iterator();
    }
  }

  static class QuietSentence extends Sentence<QuietSentence> {
    public QuietSentence Whisper(String word) {
      Say(word.toLowerCase());
      return this;
    }

    @Override
    QuietSentence self() {
      return this;
    }
  }

  static class LoudSentence extends Sentence<LoudSentence> {
    public LoudSentence Shout(String word) {
      return Say(word.toUpperCase());
    }

    @Override
    LoudSentence self() {
      return this;
    }
  }

  static void PrintWords(Sentence words) {
    for(Object obj : words) {
        // I'd really like to avoid this cast
        String word = (String)obj;
        System.out.println(new StringBuilder(word).append(": ").append(word.length())
                  .toString());
    }
  }

  public static void main (String[] args) {
    QuietSentence peaceful_words = new QuietSentence().Say("Hello").Whisper("World");
    PrintWords(peaceful_words);

    LoudSentence noisy_words = new LoudSentence().Say("Hello").Shout("World");
    PrintWords(noisy_words);
  }
}

What's going on, and how can I fix it?

A: So it turns out the problem was that I was not specifying the type correctly. A minimal fix in the PrintWords function solves the problem.
static void PrintWords(Sentence<? extends Sentence> words) {
    for(String word : words) {
        System.out.println(new StringBuilder(word).append(": ").append(word.length())
                .toString());
    }
}


text:
Q: re-rendered HTML is not being affected by jQuery functionality A couple of minutes ago I faced a situation where I needed to do some functions whenever some events were triggered like:
<button>Default button</button> and then a script like:
$('button').click(() => $('body').append(`<button>Re-rendered button</button>`));

So I was searching for a $(document).change() function and I found this solution that worked great for my situation:

$(document).bind('DOMContentLoaded DOMSubtreeModified', () => {
  $('button').on('click', () => {
    $('body').append(`<p><button>Another button</button></p>`);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>First Button</button>

In fact, this code here adds three buttons, but on CodePen works as intended.
So, the question is, how should I apply (as a best practice) the same logic in order to let the new buttons be affected by jQuery functions?


text:
Q: null pointer exception when using TimePickerDialog I am working on activity which uses timepickerdialog for setting a time.
But after setting up the time fom the dialog box, and then when i proceed, i get exception
as:
java.lang.RuntimeException: Unable to pause activity
Caused by: java.lang.NullPointerException
at android.widget.TimePicker.updateInputState(TimePicker.java:995)
at android.widget.TimePicker.onSaveInstanceState(TimePicker.java:640)
at android.view.View.dispatchSaveInstanceState(View.java:13561)

My code uses :

*

*OnClick
showDialog(END_TIME_PICKER_ID);

*protected void onPrepareDialog(int id, Dialog dialog)
  case END_TIME_PICKER_ID :
        endHourOfDay = mEndCalendar.get(Calendar.HOUR_OF_DAY);
         endMinuteOfDay = mEndCalendar.get(Calendar.MINUTE);

        ((TimePickerDialog) dialog).updateTime(endHourOfDay, endMinuteOfDay);
        ((TimePickerDialog) dialog).show();
        break;

*protected Dialog onCreateDialog(int id)
 case END_TIME_PICKER_ID :
  return new TimePickerDialog(this, mEndTimeSetListener, endHourOfDay, endMinuteOfDay, false);

*on Time Set listener
 private TimePickerDialog.OnTimeSetListener mEndTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute)
{
    endHourOfDay = hourOfDay;
    endMinuteOfDay = minute;
 GregorianCalendar endCalendar = (GregorianCalendar) mEndCalendar.clone();
    endCalendar.set(Calendar.DAY_OF_MONTH, mStartCalendar.get(Calendar.DAY_OF_MONTH));
    endCalendar.set(Calendar.HOUR_OF_DAY, endHourOfDay);
    endCalendar.set(Calendar.MINUTE, endMinuteOfDay);
    endCalendar.set(Calendar.SECOND, second);
 }

So when i run the above snippet, and after setting the timepicker and then when i click playbutton to go to the next activity, it gives this application crash.
Then it go and plays ( new activity)
When i click back key , i get another error.
     java.lang.RuntimeException: Unable to start activity ComponentInfo

When i click ok, it starts from the activity group again with the default activity inside the activity group.
I feel all these issues are caused by the timepicker dialog.
If i dont open the timepickerdialog ( to edit time),  everything works fine .
Please let me know if i am doing something wrong with the timepickerdialog code.

A: I have faced the same issue on android 4.4, on old version it wasnt happend. Genertally i found that this issue is connected with timePicker.
From Logcat:
E/AndroidRuntime( 8671): java.lang.NullPointerException

E/AndroidRuntime( 8671):    at android.widget. (TimePicker.java:995)

E/AndroidRuntime( 8671):    at android.widget.TimePicker.onSaveInstanceState(TimePicker.java:640)

E/AndroidRuntime( 8671):    at android.view.View.dispatchSaveInstanceState(View.java:13570)

E/AndroidRuntime( 8671):    at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2813)

E/AndroidRuntime( 8671):    at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2819)

E/AndroidRuntime( 8671):    at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2819)

E/AndroidRuntime( 8671):    at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2819)

E/AndroidRuntime( 8671):    at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2819)

E/AndroidRuntime( 8671):    at android.view.View.saveHierarchyState(View.java:13553)

E/AndroidRuntime( 8671):    at com.android.internal.policy.impl.PhoneWindow.saveHierarchyState(PhoneWindow.java:1875)

E/AndroidRuntime( 8671):    at android.app.Dialog.onSaveInstanceState(Dialog.java:408)

E/AndroidRuntime( 8671):    at android.app.TimePickerDialog.onSaveInstanceState(TimePickerDialog.java:238)

E/AndroidRuntime( 8671):    at android.app.Activity.saveManagedDialogs(Activity.java:1267)

E/AndroidRuntime( 8671):    at android.app.Activity.performSaveInstanceState(Activity.java:1185)

E/AndroidRuntime( 8671):    at android.app.Instrumentation.callActivityOnSaveInstanceState(Instrumentation.java:1241)

E/AndroidRuntime( 8671):    at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3331)

E/AndroidRuntime( 8671):    at android.app.ActivityThread.handleStopActivity(ActivityThread.java:3390)

E/AndroidRuntime( 8671):    at android.app.ActivityThread.access$1100(ActivityThread.java:163)

E/AndroidRuntime( 8671):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1279)

E/AndroidRuntime( 8671):    at android.os.Handler.dispatchMessage(Handler.java:102)

E/AndroidRuntime( 8671):    at android.os.Looper.loop(Looper.java:157)

E/AndroidRuntime( 8671):    at android.app.ActivityThread.main(ActivityThread.java:5335)

E/AndroidRuntime( 8671):    at java.lang.reflect.Method.invokeNative(Native Method)

E/AndroidRuntime( 8671):    at java.lang.reflect.Method.invoke(Method.java:515)

E/AndroidRuntime( 8671):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)

E/AndroidRuntime( 8671):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)

E/AndroidRuntime( 8671):    at dalvik.system.NativeStart.main(Native Method)

I solved this issue by adding
<TimePicker android:id="@+id/timePicker"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_gravity="center_horizontal"
android:descendantFocusability="blocksDescendants">
 <requestFocus />
</TimePicker>

i have also set timePicker in this order find, set24 then listener:
timePicker = (TimePicker) viewContent.findViewById(R.id.timePicker);
timePicker.setIs24HourView(true);
timePicker.setOnTimeChangedListener(listener);

This is some kind of system issue. This fix is working if you will create timepicker in xml -i believe this is also source of the problem.

A: Null pointer occurs when your using variable or object without initializing it or your trying to access variable or object before declaring or initializing it
use logcat to get error after getting error in logcat go to that error by double clicking on it then you can get that object/variable which you are using before initialising /declaring it
you need to declare/initialze that object before it actualy using it


text:
Q: why this code cannot be run?what is "syntax error: postfix/infix operator expected" error in ECLiPSe-clp When I want to run this code in ECLiPSe-CLP I get the following Error
Error:
string stream 27: syntax error: postfix/infix operator expected

|     4 $= X^2 + Y^2,   (Error Mark is under '=')
|

Code:
circles(X, Y) :-
    4 $= X^2 + Y^2,
    4 $= (X - 1)^2 + (Y - 1)^2,
    X $>= Y.

A: The $=/2 operator/predicate is a library predicate. Are you loading the library defining it? E.g.
[eclipse 12]: lib(ic).
...
Yes (0.12s cpu)

[eclipse 13]: [user].
circles(X, Y) :-
     4 $= X^2 + Y^2,
    4 $= (X - 1)^2 + (Y - 1)^2,
     X $>= Y.
 ^Dtty        compiled 4024 bytes in 0.00 seconds

Yes (0.00s cpu)

[eclipse 14]: circles(X, Y).

X = X{-1.0000000000000004 .. 2.0000000000000004}
Y = Y{-1.0000000000000004 .. 2.0000000000000004}

There are 13 delayed goals. Do you want to see them? (y/n)


text:
Q: How do I bind Character to a TextField? I've found an example of how to bind Integer to a TextField:
Binder<Person> b = new Binder<>();
b.forField(ageField)
    .withNullRepresentation("")
    .withConverter(new StringToIntegerConverter("Must be valid integer !"))
    .withValidator(integer -> integer > 0, "Age must be positive")
    .bind(p -> p.getAge(), (p, i) -> p.setAge(i));

The problem is - there is no StringToCharacterConverter and if have an error if I bind fields as is. The error is:
Property type 'java.lang.Character' doesn't match the field type 'java.lang.String'. Binding should be configured manually using converter.

A: You need to implement custom converter, here is very simplified version of what could be StringToCharacterConverter for getting the pattern what the they look like:
public class StringToCharacterConverter implements Converter<String,Character> {

    @Override
    public Result<Character> convertToModel(String value, ValueContext context) {
        if (value == null) {
            return Result.ok(null);
        }

        value = value.trim();

        if (value.isEmpty()) {
            return Result.ok(null);
        } else if (value.length() == 1) {
            Character character = value.charAt(0);
            return Result.ok(character);
        } else {
            return Result.error("Error message here");
        }
    }

    @Override
    public String convertToPresentation(Character value, ValueContext context) {
        String string = value.toString();
        return string;
    }

}


text:
Q: getting layout id from string, won't work Looked through every question, can't get it working.
I wanna set an AppWidgets layout with the value of a string (So the layout can be switched to another one by just changing the string).
String NoteString = "R.layout.widget_blue".toString();

int resID = context.getResources().getIdentifier(NoteString, "layout", context.getPackageName());

RemoteViews views = new RemoteViews(context.getPackageName(), resID);

don't know why it doesn't work, widget just says: "problem loading widget"..
This works fine:
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_blue);

Thanks

A: In order to construct a resource ID from string components, you must pass the individual components into getIdentifier(), not the fully qualified ID as a single parameter:
//Get the ID for R.layout.widget_blue
int resID = context.getResources().getIdentifier("widget_blue", "layout", context.getPackageName());

Then just change the first parameter name to get a different layout resource.

A: Why are you using getIdentifier for this? Since you're including the hard-coded string in there anyway, why not just use the resource identifier included anyway, as you've done in the second example. That's much more efficient, as stated in the documentation on the getIdentifier() method:

Note: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.

A: Below is a set of call to get resources Identifier by name: especially useful for AppWidgets
Layout
val viewId = context.resources.getIdentifier("my_custom_layout", "layout", context.packageName)

image from res/drawable
val viewId = context.resources.getIdentifier("my_image", "drawable", context.packageName)

view based on resource name
val viewId = context.resources.getIdentifier("my_textview_id", "id", context.packageName)

string
val viewId = context.resources.getIdentifier("my_string", "string", context.packageName)


text:
Q: WineBottler: Prefix creation exited with error I'm trying to install a windows program through winebottler. Does anyone have a clue how to fix this? I tried messing around with the system version, but it's really no use it seems. If there's any other program that could handle it that would be great too. I tried to install through both the developer and the stable version of winebottler.
###BOTTLING### default.sh
/var/folders/kh/2mwf9_0513j860jvn_0nvs8w0000gn/T/AppTranslocation/C1851059-0277-467F-9E04-CE3EB0664F8C/d/WineBottler.app/Contents/Frameworks/WBottler.framework/Resources/bottler.sh: line 39: /Applications/Wine.app/Contents/Resources/bin/wine: Bad CPU type in executable
###BOTTLING### Gathering debug Info...

Versions
OS...........................: darwin19
Wine.........................:
WineBottler..................: 4.0.1.1
Wineticks....................: 20200412-next - sha256sum: 04f9048f4d273175ef008c326c248756be40695671c28a2f10e05a5c78a544ee

Environment
PWD..........................: /Applications/Wine.app/Contents/Resources/bin
PATH.........................: /Applications/Wine.app/Contents/Resources/bin:/usr/bin:/bin:/usr/sbin:/sbin
USER.........................: tigeroic
HOME.........................: /Users/tigeroic
COMPUTERNAME.................: MacBook Pro
BUNDLERESOURCEPATH...........: /var/folders/kh/2mwf9_0513j860jvn_0nvs8w0000gn/T/AppTranslocation/C1851059-0277-467F-9E04-CE3EB0664F8C/d/WineBottler.app/Contents/Frameworks/WBottler.framework/Resources
WINEARCH.....................: win32
WINEPREFIX...................: /Applications/Wine.app/Contents/Resources
WINEPATH.....................: /Applications/Wine.app/Contents/Resources/bin
LD_LIBRARY_PATH..............: /Applications/Wine.app/Contents/Resources/lib
DYLD_FALLBACK_LIBRARY_PATH...: /Applications/Wine.app/Contents/Resources/lib:/usr/lib
SILENT.......................:
http_proxy...................:
https_proxy..................:
ftp_proxy....................:
socks5_proxy.................:

Bottle
TEMPLATE.....................:
BOTTLE.......................: /Users/tigeroic/Downloads/Untitled.app
INSTALLER_URL................: /Users/tigeroic/Downloads/Streamlabs+Chatbot+Installer (1).exe
INSTALLER_IS_ZIPPED..........: 0
INSTALLER_NAME...............: Streamlabs+Chatbot+Installer (1).exe
INSTALLER_ARGUMENTS..........:
REMOVE_MONO..................:
REMOVE_GECKO.................:
REMOVE_USERS.................:
REMOVE_INSTALLERS............:
WINETRICKS_ITEMS.............: arch=32 win7
DLL_OVERRIDES................:
EXECUTABLE_PATH..............: winefile
EXECUTABLE_ARGUMENTS.........:
EXECUTABLE_VERSION...........: 1.0.0
BUNDLE_COPYRIGHT.............: © Your Company
BUNDLE_IDENTIFIER............: com.yourcompany.yourapp
BUNDLE_CATEGORYTYPE..........: public.app-category.business
BUNDLE_SIGNATURE.............:
SILENT.......................:

Hardware:

    Hardware Overview:

      Model Name: MacBook Pro
      Model Identifier: MacBookPro16,1
      Processor Name: 8-Core Intel Core i9
      Processor Speed: 2,3 GHz
      Number of Processors: 1
      Total Number of Cores: 8
      L2 Cache (per Core): 256 KB
      L3 Cache: 16 MB
      Hyper-Threading Technology: Enabled
      Memory: 32 GB
      Boot ROM Version: 1037.120.87.0.0 (iBridge: 17.16.15300.0.0,0)
      Serial Number (system): C02CQ8LHMD6T
      Hardware UUID: 25B3D8F4-FE4D-542F-8298-DF4919802B9B
      Activation Lock Status: Enabled

###BOTTLING### Create .app...
###BOTTLING### Enabling CoreAudio, Colors, Antialiasing  and flat menus...
/var/folders/kh/2mwf9_0513j860jvn_0nvs8w0000gn/T/AppTranslocation/C1851059-0277-467F-9E04-CE3EB0664F8C/d/WineBottler.app/Contents/Frameworks/WBottler.framework/Resources/bottler.sh: line 142: /Applications/Wine.app/Contents/Resources/bin/wine: Bad CPU type in executable
### LOG ### Command '/Applications/Wine.app/Contents/Resources/bin/wine regedit /tmp/reg.reg' returned status 126.

###ERROR### Command '/Applications/Wine.app/Contents/Resources/bin/wine regedit /tmp/reg.reg' returned status 126.
Task returned with status 1.


text:
Q: LokiJS - fastest way to update large number of records? I have a large in-memory dataset on the client side, and need to quickly update records in a wide dataset (at most, about 50k records at a time). Right now, I have a loop that looks like this.
// looping over new data entry, then either updating or adding if the id isn't already present
data.forEach((d) => {
const current = collection.by('id', d.id);
  if (current) {
  Object.assign(current, d);
    collection.update(current);
  } else collection.insert(d);
});

This loop takes about 10 seconds on a fast pc for 50k records, which is about 20x as long as I can afford for it take in the larger app context. Any thoughts would be greatly appreciated.
Thank you!


text:
Q: Partitioned Median I wonder if anyone can help I am trying to calculate a median which abides by the groupings in my view.
I like the following code but it just gives me the over all median in each row. I think i need to use OVER(PARTITION BY()) but i just can't make heads nor tails of it even after furious googling and reading renowned articles like this https://sqlperformance.com/2012/08/t-sql-queries/median
 `SELECT
 YEAR(reportsubmitted) as "Year Submitted",
 Month(reportsubmitted) as "Month Submitted", COUNT (DISTINCT(propertyid)) as
 "Number of Reports Submitted", SUM([report fee]) as "Total Report Fee",

(
(SELECT MAX([days From Audit to Submission])

FROM (SELECT TOP 50 PERCENT ([days From Audit to Submission] )

FROM vwCMnAuditorsProcessLength WHERE ReportSubmitted > '2017-04-01' ORDER BY
[days From Audit to Submission] ) AS x)

(SELECT MIN([days From Audit to Submission])

FROM (SELECT TOP 50 PERCENT [days From Audit to Submission]
FROM vwCMnAuditorsProcessLength WHERE ReportSubmitted > '2017-04-01' ORDER BY
[Report Fee] DESC) AS y)
) / 2.0 as "Median Days"

FROM vwCMnAuditorsProcessLength
WHERE reportsubmitted >= '2017-04-01'

GROUP BY MONTH(reportsubmitted), YEAR(reportsubmitted)`

I did try the below as something different but it seems to be discounting a lot of data
SELECT

[MMYYYY ReportSubmitted],

[Total Report Fee],

[Number of Reports Submitted],

AVG([days from audit to submission]) as "Median days to Submission"

FROM (

SELECT [MMYYYY ReportSubmitted], [report fee], propertyid,
CAST([days from audit to submission] as decimal(5,2)) [days from audit to submission],

ROW_NUMBER() OVER(
Partition by [MMYYYY ReportSubmitted]
Order by [days from audit to submission] ASC) AS "RowASC",

ROW_NUMBER() OVER(
Partition by [MMYYYY ReportSubmitted]
Order by [days from audit to submission] DESC) AS "RowDESC",

SUM([report fee]) OVER(Partition by [MMYYYY ReportSubmitted] Order by [days from
 audit to submission]) AS "Total Report Fee",
COUNT(propertyid) OVER(Partition by [MMYYYY ReportSubmitted] Order by [days from audit to submission]) AS "Number of Reports Submitted"

FROM vwCMnAuditorsProcessLength) x

WHERE RowASC in (RowDESC,RowDESC-1,RowDESC+1)

 Group by [MMYYYY ReportSubmitted], [Total Report Fee], [Number of Reports Submitted]
Order by [MMYYYY ReportSubmitted]

If anyone has any ideas I would be really greatful

A: If you don't care about performance then the simplest way is the best:
SELECT SalesPerson, Median = MAX(Median)
FROM
(
   SELECT SalesPerson,Median = PERCENTILE_CONT(0.5) WITHIN GROUP
     (ORDER BY Amount) OVER (PARTITION BY SalesPerson)
   FROM dbo.Sales
)
AS x
GROUP BY SalesPerson;

Example from: https://sqlperformance.com/2014/02/t-sql-queries/grouped-median
If you want even simpler method I recommend CRL function:
https://stackoverflow.com/a/16719240/1903793
It lets you to calculate median like this:
SELECT dbo.Median(Field) FROM Table


text:
Q: Find CKEDITOR Node's (self) inner text i have a node with inner text and children's also have inner Text.
how can i fetch current nodes inner text (without children and its inner Text).
For Example :
<myTag>
myTag Text
<child1>ch1 Text</child1>
<child2>ch2<child3></child3> Text</child2>
some text
</myTag>

Required Result (myTag Inner Text Only):
Find inner text of myTag:
1.myTag Text
<child1>
2.some text
<child2>

Find inner nodes by
x=myTagNode.getchildren()
for(var i=0;i<x.count();i++)
{
if(x[i].type==1)
{
alert(x[i].getName());
}
}

How can i get the inner Text (without children inner Text)?

A: Try using a treeWalker:
var mytag=document.getElementsByTagName("mytag")[0];
var treeWalker = document.createTreeWalker(mytag, NodeFilter.SHOW_TEXT);
var nodeList = [];
while(treeWalker.nextNode()) nodeList.push(treeWalker.currentNode);


text:
Q: jQuery - AJAX request using both native XHR and flXHR (Flash) fallback - how to minimize code duplication? I need to retrieve data via cross-domain XMLHttpRequest. To make this work in (almost) all browsers, I use native XHR first and, if that fails, flXHR.
The (working) code I currently have for this is as follows:
jQuery.support.cors = true; // must set this for IE to work

$.ajax({
    url: 'http://site.com/dataToGet',
    transport : 'xhr',
    success: function(data) {
        console.log('Got data via XHR');
        doStuff(data);
    },
    error: function(xhr, textStatus, error) {
        console.log('Error in xhr:', error.message);
        console.log('Trying flXHR...');
        $.ajax({
            url: 'http://site.com/dataToGet',
            transport : 'flXHRproxy',
            success: function (data) {
                console.log('Got data via flXHR');
                doStuff(data);
            },
            error: function (xhr, textStatus, error) {
                console.log('Error in flXHR:', error.message);
                console.log('Both methods failed, data not retrieved.');
            }
        });
    }
});

This feels like a lot of code duplication to me, especially in the success handlers. Is there a more efficient way to do this? I'd really prefer to make one $.ajax call that would try both transports in turn, instead of having to use the error handler to make the call a second time. It's not too bad in this example, but rapidly gets more complicated if the success handler is longer or if the success handler has to itself issue another $.ajax call.

A: I've created a jquery-specific and slimmed-down fork of flxhr that simplifies your code sample above. You can see an example of usage in the "Usage" section in the README.
https://github.com/b9chris/flxhr-jquery-packed
In particular, you don't want to waste time waiting for a standard CORS request to fail. It's easy to determine whether flxhr is necessary by testing $.support.cors upfront (no need to override it). Then just use flxhr explicitly where necessary.

A: Why don't you just wrap this in a function by itself? That's after all, how you end up reusing code. You can even pass functions as arguments to make sure that you don't have to repeat this code more than once.
To me this is pretty straight forward but maybe I've misunderstood.
function xhr(success) {
    $.ajax({
        success: success,
        error: function() {
            $.ajax({ success: success })
        }
    });
}

Then just pass the success handler once
xhr(function(data){/*magic*/});

Or if you wanna basically avoid redundant configuration of the ajax call use the first object as a template, like this:
function xhr(success) {
    var ajaxParams = { success: success };
    ajaxParams.error = function() {
        $.ajax($.extend(ajaxParams, { transport: 'xhr' }));
    }
    $.ajax(ajaxParams);
}

I simplified the whole thing a bit, but I hope you get the point.
Edit
Reading that last bit, maybe this will give you some ideas... it's a variation of that last snippet.
function xhr(success) {
    var ajaxParams = { success: success };
    ajaxParams.error = function() {
        var newParams = $.extend(ajaxParams, { transport: 'xhr' });
        newParams.success = function() {
            // do something
            // arguments is a special array, even if no parameters were
            // defined in any arguments where passed they will be found
            // in the order they were passed in the arguments array
            // this makes it possible to forward the call to another
            // function
            success.apply(this, arguments);
        }
        $.ajax(newParams);
    }
    $.ajax(ajaxParams);
}


text:
Q: rCharts installing problems I am using a windows 7 system and am trying to install rCharts. I keep getting the following error message:
Downloading github repo ramnathv/rCharts@master
Error in utils::unzip(src, list = TRUE) : 'exdir' does not exist
I am not very tech savvy and I need to use rCharts for a project. Any help in detail would be greatly appreciated.


text:
Q: How to convert a string to number I can't figure it out how to convert this string 82144251 to a number.
Code:
var num = "82144251";

If I try the code below the .toFixed() function converts my number back to a string...
Question update:
I'm using the Google Apps Script editor and that must be the issue...
num = parseInt(num).toFixed() // if I just do parseInt(num) it returns 8.2144251E7

A: No questions are dumb.
a quick answer:
to convert a string to a number you can use the unary plus.
var num = "82144251";

num = +num;

Doing num = +num is practically the same as doing num = num * 1; it converts the value in a to a number if needed, but after that it doesn't change the value.

A: You can convert a string to number using unary operator '+' or parseInt(number,10) or Number()
check these snippets

var num1a = "1";
console.log(+num1a);

var num1b = "2";
num1b=+num1b;
console.log(num1b);

var num3 = "3"
console.log(parseInt(num3,10));

var num4 = "4";
console.log(Number(num4));

Hope it helps

A: It looks like you're looking for the Number() functionality here:
var num = "82144251"; // "82144251"
var numAsNumber = Number(num); // prints 82144251
typeof num // string
typeof numAsNumber // number

You can read more about Number() here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number
Hope this helps!

A:

var num = "82144251";
num = parseInt(num).toFixed()
console.log(num, typeof num); // string
num = parseFloat(num);
console.log(num, typeof num); // number

A: var intNum = parseInt("82144251", 10); // intNum is number

A: I use num-0, since it is easier for inline use.


text:
Q: Rake task is not getting executed in rails controller I am trying to call rake task in one of my methods of controller. The action is getting executed the method is also getting redirected but my rake task is not working. I have tried everything system, backticks, calling another model method etc. But its not at all working. And its happening only in production in development it works fine. I have no clue what is wrong. Thanks in advance.
`rake maintenance:sidekiq:print`

or
system('rake maintenance:sidekiq:print')

A: Not sure how you are calling the task, but there are couple of ways
system "rake task_name"

Else you can do something like
require 'rake'
Rake::Task["task_name"].invoke

It works for me .


text:
Q: Uneven line-height in TextFlow control? I've switched from the regular TextField to the new TextLayout framework, thus using the new TextFlow control. Everything is great except that lines for some reason don't snap horizontally to pixels. Meaning, the line-height varies due to rounding and the selection rectangle becomes blurry. I've looked up and down the documentation and can't find anything that would explain this, nor do I find anything on the mighty google.
I haven't done anything strange and it's still a minimal implementation so I don't see what I personally could've done wrong: http://pastebin.com/hBxR1eVS ... setting the line-height works partially (although far from ideal), but there is still something causing a non-integer height. I'm compiling against Flex SDK 4.5.1 with FlashDevelop.
There must be a way to force lines to snap to pixels... right?

EDIT: Apparently this is present even in their own demo swf: http://sourceforge.net/projects/tlf.adobe/files/3.0/current/Flow.swf/download
So basically, the question is then... can it be fixed/corrected by making some custom implementation of some class or perhaps make some adjustment to the TextLayout-framework itself?

As you can see here, the spacing between the lines varies between 5 and 6 pixels, and the selection rectangle is blurred (everything is selected, the background is grey).


text:
Q: How to open camera inside ionic custom app I am developing custom app using Ionic and Typescript.
Where I want to open camera and take picture, I am able to open camera from my app but the problem is, it is opening the native camera and which is coming out from my app.
What I want is open camera inside from my app, may be in Div container (which has predefined width and height)
Thank you in advance.

A: You could use a third-party plugin cordova-plugin-camera-preview. Which provides powerful features, including set a custom size(position) for camera preview box.


text:
Q: Azure DevOps - Automatically run rails migrations I created a Azure devops project that deploys my code from Github. My project is a Rails app that runs on Docker. When I create the Azure DevOps project, it creates the CI/CD pipelines for me. The deployment works, but I can't figure out how to automatically migrate the database when we deploy. I know I can do it manually, but I prefer not to as we might forget when we deploy.
I tried to run the following commands in the "Post Deployment Actions"

*

*rake db:migrate

*bundle exec rake db:migrate

*rbenv exec bundle exec rake db:migrate

*docker-compose run web rake db:migrate
I've also generated my own kuduscript (using kuduscript) to add in the line for migration but it did not work. I don't know if it's because it's not reading my deployment script or if that line doesn't work.
Am I missing something? Should I try to figure out how to migrate through Docker instead? I've looked at all these links but they all run the migration manually.
https://learn.microsoft.com/en-us/azure/app-service/containers/quickstart-ruby
https://medium.com/paris-rb/deploying-your-rails-postgresql-app-on-microsoft-azure-180f8a9fab47
https://learn.microsoft.com/en-us/azure/app-service/containers/tutorial-ruby-postgres-app

A: So not sure if you ever figured this out but I just had to do this for a migration I'm working on. The best way to do what you're after from what I've found is to setup a stage in your release pipeline like so:
stage setup
Where basically:

*

*Your service connection logs into the container registry

*Pulls the image you just built and pushed to the registry

*Use a docker run command to then run your image with all the necessary environment variables and anything else needed to run it properly.

*You can then use another task if needed to run a docker exec bundle exec rake db:migrate

If the migrate task runs successfully it should exit 0 allowing you to then run your app service on the latest tagged image with the correct database changes already done.


text:
Q: can we run digits or caffe on Mac without GPU? I have seen caffe installation for Mac. But I have a question. If my Mac does not have GPU, then I have no chances to use GPU?? and I have to use CPU-only?
or I have the chance of using (virtual!) GPU by NVIDIA web driver?
Moreover, can I have digits on my Mac? as I try to download it, it does not have any options for Mac download and it is just for Ubuntu!
I am very confused about these questions! Can you please make me clear about these?

A: The difference in architectures between CPU and GPU does not allow simple transformation of the code written for one architecture to the other.  The GPU drivers are specifically written for the GPU architecture and cannot be easily virtualized. On the other hand, some software supports both. This includes OpenGL instructions and caffe (http://caffe.berkeleyvision.org/). NVidia DIGITS is based on caffe and therefore can work without a dedicated GPU (Here the thread how to install on Macs: https://github.com/NVIDIA/DIGITS/issues/88)
According to  https://www.github.com/NVIDIA/DIGITS/issues/251 CUDA cannot be run on computers that do not have a dedicated NVidia GPU, but according to How to run my CUDA application on ATI or Intel card in software mode? there is a program gpuocelot that receives CUDA instructions and can work on NVidia GPU, AMD GPU and x86.
In scientific shared computing they wrote separate programs for different  devices, e.g. Einstein at Home has four separate programs to find gravitational waves: CPU, NVidia GPU (CUDA), AMD GPU and ARM.
To make DIGITS work you need to

build Caffe with CPU_ONLY and tell DIGITS not to use any GPUs by
  running digits-devserver with the --config flag

(https://github.com/NVIDIA/caffe/blob/v0.13.2/Makefile.config.example#L9-L10, https://github.com/NVIDIA/DIGITS/issues/251).
Other possibility:

you can still use the --config flag with the web installer. Try this:
./runme.sh --config. Choose "N" to select none.

Also a possibility:

I am trying to answer how you can choose CPU or GPUs..  Within the
  caffe folder, there is a Makefile.config.example file..  Copy the
  contents of this file into a new file and rename it as
  "Makefile.config". If you want to use CPU, then
  1. comment out the "USE_CUDNN :=1 Within "Makefile.config" file,
  2. uncomment CPU_ONLY := 1
  3. issue the make all command again within the caffe folder..

And if nothing helps you can do the procedure two times because it helped someone at the end of the thread.


text:
Q: How to access the shell in google Colab when running the R kernel When I use Python with colab, you can access the underlying operating system using things like ! and %%shell, e.g., !ls to list the files.
When I use colab with the R kernel, the ! and %%shell tricks don't work.  Is there a way to call the shell from colab in this case?
https://colab.research.google.com/#create=true&language=r

A: There is the base R function system which allows you to call the shell behind the Notebook. Since colab suppresses the stdout, one needs to set the option intern = TRUE to see the result as an R character vector. To properly display line breaks, I defined a function called shell_call which is analog to ! in ipython:
shell_call <- function(command, ...) {
  result <- system(command, intern = TRUE, ...)
  cat(paste0(result, collapse = "\n"))
}

shell_call("ls -lah / | head")

A: The implementation of magics is kernel specific as explained here:

To Jupyter users: Magics are specific to and provided by the IPython
kernel. Whether Magics are available on a kernel is a decision that is
made by the kernel developer on a per-kernel basis. To work properly,
Magics must use a syntax element which is not valid in the underlying
language. For example, the IPython kernel uses the % syntax element
for Magics as % is not a valid unary operator in Python. However, %
might have meaning in other languages.

R does not offer good conditions to implement magics this way as for example %% is used as the modulo operator and ! as the logical NOT operator.
This is why the developers of the IRkernel have chosen not to support %%cell magic - see this or this.
As already outlined in the comments when working with the IRkernel you'll need to find solutions in the R language itself e.g. using built-in functions to access the shell system2("ls", stdout = TRUE) or search for files list.files() (you might also want to wrap them in a custom function as suggested by @danlooo).
If you still want to use magics another approach would be to use R magics (extension rmagic) along with the IPython kernel as shown here or here:


text:
Q: How to send the OAuth request in Node I want to access the WS REST API in node.js. I have the oauth_consumer_key and the oauth_token and the API end point. The oauth_signature_method is HMAC-SHA1.
How to send the OAuth request in Node?
Is there a module/library to generate the request headers? What I expect is a function like:
var httprequest = createRequest(url, method, consumer_key, token);

*

*UPDATE 10/14/2012. Adding the solution.

I'm using the code below.
var OAuth = require('oauth').OAuth;

consumer = new OAuth('http://term.ie/oauth/example/request_token.php',
                    'http://term.ie/oauth/example/access_token.php',
                    'key', 'secret', '1.0',
                    null, 'HMAC-SHA1');

// Get the request token
consumer.getOAuthRequestToken(function(err, oauth_token, oauth_token_secret, results ){
    console.log('==>Get the request token');
    console.log(arguments);
});

// Get the authorized access_token with the un-authorized one.
consumer.getOAuthAccessToken('requestkey', 'requestsecret', function (err, oauth_token, oauth_token_secret, results){
    console.log('==>Get the access token');
    console.log(arguments);
});

// Access the protected resource with access token
var url='http://term.ie/oauth/example/echo_api.php?method=foo&bar=baz';
consumer.get(url,'accesskey', 'accesssecret', function (err, data, response){
    console.log('==>Access the protected resource with access token');
    console.log(err);
    console.log(data);
});

A: We use https://github.com/ciaranj/node-oauth

A: This is more of a complete node twitter package that seems streamlined and useful.
https://npmjs.org/package/twitter


text:
Q: Issues Linking CSS File to JSP I am trying to link a css to my jsp page but I keep getting a 404 page not found error.
href in the homepage.jsp:
  <link href="../resources/css/welcome.css" rel="stylesheet" />
file structure:
-->webapp
  -->img
  -->resources
    -->css
      -->welcome.css
  -->WEB-INF
    -->views
      -->homepage.jsp

A: As you're using Spring MVC:
<link href="<c:url value="/resources/css/welcome.css" />" rel="stylesheet">

If you hate JSTL, you can use the "page context" variable to get the resources like this :
<link href="${pageContext.request.contextPath}/resources/css/welcome.css" rel="stylesheet" >


text:
Q: Converting golfed (200 character) Ruby Code to functionally equivalent simplified JAVA code I need a simplified (Pseudo/C++/JAVA) version of this Ruby code -
def P(a)a.min<0?0:a.max<1?1:(b=a*1;t=k=0;b.map{b[k]-=1;k+=1;t+=P(b)};t)end
def d(n,a)print n>1?((0..a[-1]).map{|i|d(n-1,a+[i])};"\n"):"#{P(a)} "end
d(ARGV[0].to_i,[ARGV[1].to_i])

For context, please visit Code golf- Pascal's pyramid and higher dimensions
Here is what I have so far,
Pseudo code-
/**
*   This prints out one 'row', specified by indices in array
*   for Pascal's triangle of the given dimension
**/
void doit(int dimension, list array){
    if(dimension>1){
        for(int i=0;i<=array.lastElement();++i){
            // Recursively call function with reduced dimension and
            // extended array (count index appended)
            doit(dimension-1, array.append(i));
        }
        print a newline;
    }
    else{
        print Pascal(a);
    }
}

/**
*   This calculates a specific entry in the Pascal's triangle
**/
int Pascal(list array){
    // Pascal(...,-1,...) = 0
    if(minimum(array)<0){
        return 0;
    }
    // Pascal(0,0,...,0) = 1
    else if(maximum(array)<1){
        return 1;
    }
    // Pascal(a,b,c,...) = Pascal(a-1,b,c,...) + Pascal(a-1,b-1,c,...) + Pascal(a-1,b-1,c-1,....)
    else{
        list work_array = array.copy();
        int result = 0;

        for(int i=0;i<work_array.length;++i){
            // Decrement i'th element in array
            work_array[i] = work_array[i]-1;
            // Recursively call this function with modified array
            // and add return value to result.
            result = result + Pascal(work_array);
        }

        return result;
    }
}

void main(firstArg, secondArg){
    doit(firstArg.toInt(), new list [secondArg.toInt()]);
}

Implementation of above Pseudo Code in JAVA-
import java.util.*;
public class Pascal {

    public static void main(String[] args) {
        ArrayList<Integer> power=new ArrayList<Integer>();
        power.add(3);
        doit(4,power);

    }

    public static void doit(int dimension, ArrayList<Integer> array){
        if(dimension>1){
            for(int i=0;i<=(int) array.get(array.size() - 1);++i){
                array.add(i);
                doit(dimension-1,array);
            }
            System.out.println();
        }
        else{
            System.out.print(Pa(array));
        }
    }

    public static int Pa(ArrayList<Integer> array){
        if((int)Collections.min(array) <0){
            return 0;
        }
        else if((int)Collections.max(array) <1){
            return 1;
        }
        else{
            ArrayList<Integer> work_array = new ArrayList<Integer>();
            //Collections.copy(work_array, array);
            for(int i=0;i<array.size();i++){
                work_array.set(i, array.get(i));
            }
            int result=0;
            for(int i=0;i<work_array.size();++i){
                work_array.set(i, work_array.get(i)-1);
                result=result+Pa(work_array);
            }
            return result;
        }
    }

}

But this does not give the same output, it shows an error-
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0   at java.util.ArrayList.rangeCheck(Unknown Source)   at java.util.ArrayList.set(Unknown Source)  at Pascal.Pa(Pascal.java:35)    at Pascal.doit(Pascal.java:20)  at Pascal.doit(Pascal.java:15)  at Pascal.main(Pascal.java:7)

What am I doing wrong?

A: You don't have any elements in your ArrayList<Integer> work_array = new ArrayList<Integer>(); therefore your index ist out of range, since the  size() returns 0.


text:
Q: Como setar cor de fundo em múltiplas linhas de uma JTable? Gostaria de saber como setar a cor do background de múltiplas linhas da tabela. No código abaixo ele simplesmente seta o background em apenas uma linha, ou seja, no ultimo elemento do vetor. A ideia é passar uma lista de strings, e o código deve setar um fundo vermelho em todas as linhas da tabela que contenham as mesmas strings da lista passada.
public class ColorCellRenderer extends DefaultTableCellRenderer {

private Color color = Color.RED;
private String textToColor;
private List<String> list;

public ColorCellRenderer(){
    super();
  }

public ColorCellRenderer(String string) {
    textToColor = string;

}

public ColorCellRenderer(List<String> list2) {
    list = list2;
}

@Override
public Component getTableCellRendererComponent(JTable table,
        Object value,
        boolean isSelected,
        boolean hasFocus,
        int row,
        int column ) {
    final java.awt.Component cellComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

    for (int c=0; c<list.size(); c++)
    {

    Object val = table.getValueAt(row, 0);
    String sval = val.toString();
    System.out.println("##"+sval);

    if (sval.equals(list.get(c))) {
     cellComponent.setForeground(Color.black);
       cellComponent.setBackground(Color.red);
    }
    else {
     cellComponent.setBackground(Color.white);
     cellComponent.setForeground(Color.black);
        }
    }
    return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
}

A: Acabei resolvendo meu problema. Troquei o laço de repetição por esta condição.
if (list.contains(val.toString())) {
 cellComponent.setForeground(Color.black);
   cellComponent.setBackground(Color.red);
}
else {
 cellComponent.setBackground(Color.white);
 cellComponent.setForeground(Color.black);
    }


text:
Q: How to figure out optimal max_worker_processes? Yet I can not find any reliable recommendation regarding the optimal value for max_worker_processes.
Some sources suppose that the value should not be higher than the number of available cores, but is that correct taking that server threads do a lot of IO?
Say I have 8 cores for PG container and plan to handle about 100 clients in parallel. Is that feasible, especially with the default max_worker_processes=8 ?
Any trusted reference would be much appreciated.

A: The reasonable limit dies not depend on the number of client connections, but on the actual upper limit on concurrent queries.
If it is guaranteed that only one of these clients will ever be active at the same time, you could set max_worker_processes, max_parallel_workers and max_parallel_workers_per_gather one less than the number of cores or parallel I/O operations that your storage can handle, whatever of the two is smaller. In essence, one query can then consume all the available resources.
On the other hand, if many of these clients are likely to run queries concurrently, you should disable parallel query by setting max_parallel_workers_per_gather to 0 to avoid overloading your database.
Concerning your comments to my answer: if your goal is to limit the number of active queries, use a connection pool.


text:
Q: nginx php-fpm xdebug netbeans can start only one debug session In the past, I've used apache+mod_php+xdebug+netbeans for development my website (server is my local machine, running Debian Squeeze), with pleasure - xdebug worked just as expected, debug sessions could be started and stopped any time, when I need it. But, when I moved to nginx+php_fpm+xdebug+netbeans I've experienced some problems with debugging.

*

*My debug session could be very long (much more than 30 seconds) and it seems, that nginx couldn't wait so long, it shows "504 Gateway timeout error". I've tried lots of recommendations for solve this, but no luck. Though, it is not a very important for me, because of debugging session itself continues to run, and it's just a little uncomfortable thing.

*My debug session could be run only once, so, if I stop it, and try to launch debugging again, netbeans couldn't accept connection from xdebug (it writes "Waiting for xdebug connection" and it is forever). After restart of netbeans the debug session could be started again normally.

*In come cases, that I couldn't understand, the debugging is "turning on for all php scripts" and prevent's any other scripts to run. For example, I start debug session on my website's http://mysite.local/index.php and working with it. After some time, I noticed, that my adminer (placed on intranet.local/adminer.php) doesnt run, the browser tries to load page for some time, and than shows "504 Gateway timeout error". If I see this behavior, I could just stop xdebug debug session in netbeans, and all other scripts starting to operate normally.

Now, when I writing this question, I made some investigations, and found, that, if I start debug session for some seconds, after that stop it, and start again - it starts normally. It seems like the problem appears after some time of active debugging.
My system and apps:
Debian squeeze:2.6.32-5-686
Nginx: 1.4.1 (from dotdeb repository)
php5-fpm: 5.3.26-1~d (from dotdeb repository)
php5-xdebug: 5.3.26-1~d (from dotdeb repository)
netbeans: 7.3
My config:

*

*nginx base config: https://gist.github.com/MihanEntalpo/6229801

*nginx website config file: https://gist.github.com/MihanEntalpo/6229781

*fastcgi_params file: https://gist.github.com/MihanEntalpo/d93fd4105573e1eda56f

*php-fpm pool config file: https://gist.github.com/MihanEntalpo/6229820

*php-fpm xdebug config file: https://gist.github.com/MihanEntalpo/6229836

*netbeans: options, that was just the same with apache server:

*

*Break on first line = OFF

*Evalution in popup window = ON

*Show requesting URL's = ON

*Port = 9000

Record in nginx's error log file, when it cannot wait for script being debugged, or other script, locked by the problem #3, mentioned early:
2013/08/14 14:40:16 [error] 4822#0: *111 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 192.168.100.1, server: intranet.local, request: "GET /adminer.php?username=root&db=devel&table=user HTTP/1.1", upstream: "fastcgi://127.0.0.1:9999", host: "intranet.local", referrer: "https://intranet.local/adminer.php?username=root&db=devel"
php-fpm's logs doesn't contains ANY error messages...
I don't like to disturb anyone with my problems, and always trying to solve it by myself. But in this case, I'm fighting with this ones for some MONTHS without luck...
If anyone faced this problems, or have working config for using with nginx+php-fpm+xdebug+netbeans - please help me :)

A: Thank you, everyone who tried to think in the direction of my problem.
I've solve it successfully.

*

*First problem (with 504 error) could be solved by nginx option fastcgi_read_timeout, for example, it could be fastcgi_read_timeout 600; for tell nginx that it should wait for 600 seconds. It should be placed to host's config file, or to /etc/nginx/fastcgi_params (in Debian)

*Second problem was caused by option in my xdebug.conf: xdebug.remote_autostart=1;, it should be xdebug.remote_autostart=0;. I doesn't understand the real meaning of this option, but it does following: Any php script automatically trying to connect to debugger (netbeans in my case). So, in some case, netbeans loses a connection, and when I press "Start debugging", it doesn't know, that new connection should be opened, and waiting for xdebug client forever. Now, with the mentioned option, I can start and stop debugging any time when I need it.

*Third problem had the same source, as the second one. All others scripts, running on my server have tried to connect to netbeans, but with lost connection it was senseless.

Anyway, I hope this would help someone, who want to solve similar problems. StackOverflow helped me by forcing me to definitely describe my problem, and in this process I've gained new ideas on what to try.

A: When updating fastcgi_read_timeout you can increase the time limit for all sites on the server (vagrant homestead VM in my case) you can do the following once you've SSH'd into your VM:
sudo pico /etc/nginx/nginx.conf

and add
fastcgi_read_timeout 300;

to the http section.

A: For everyone having the same problem where the accepted answer did not work, in my case, it was a recently installed application that was blocking xdebug.
My company has remote access to install security software on my laptop so they installed ESET Endpoint Security.app and ESET Remote Administrator Agent.app which apparently also filters localhost connections. It took me two days until I finally noticed that there was an ESET daemon running and blocking connections on 127.0.0.1:9000.
The solution was to move to trash both applications since I don't have the necessary admin privileges to disable filtering in the application settings.


text:
Q: Errors in christopher gandrud's book reproduction from github in rstudio I downloaded the repository of new book reproducible research with r and rstudio from github page of christopher gandrud. Even after following the instructions, I am getting following error when I run knit2pdf in bookmake.R file:
running: "sh"  -c "pandoc Children/FrontMatter/StylisticConventions.md -t latex -o StyleTemp.tex"
Quitting from lines 99-100 (Rep-Res-Parent.Rnw)
Error in system(cmd, intern = TRUE) : '"sh"' not found

How can I resolve  this?

A: This is a known issue, you do not have a shell program on your windows path.
The solution is to install RTools and make sure you check the checkbox to modify PATH when you install RTools


text:
Q: How to authenticate id password in Gdata video upload to you tube To upload vedio on you tube i am using Gdata sample code.
Its working fine as it is. But in my application I need to authenticate username and password of user before user try to upload video.
Can I do it with Gdata service ?
Thanks for any help.

A: Below is method for client login in Youtube:
- (BOOL)login:(NSString *)strusername password:(NSString *)strpassword
{
   NSMutableURLRequest *request = [NSMutableURLRequest
                                requestWithURL:[NSURL URLWithString:@"https://www.google.com/accounts/ClientLogin"]];

   NSString *params = [[NSString alloc] initWithFormat:@"Email=%@&Passwd=%@&service=youtube&source=&continue=http://www.google.com/",username,password];
   [request setHTTPMethod:@"POST"];
   [request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
   [params release];
   [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-type"];

   NSHTTPURLResponse *response;
   NSError *error;
   [request setTimeoutInterval:120];
   NSData *replyData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

   NSString *replyString = [[[NSString alloc] initWithData:replyData encoding:NSUTF8StringEncoding] autorelease];
   if([replyString rangeOfString:@"Auth="].location!=NSNotFound)
   {
    NSString *authToken=[[replyString componentsSeparatedByString:@"Auth="] objectAtIndex:1];
    NSLog(@"Auth : %@",authToken);
    return YES;
   }
   else
   {
    return NO;
   }
 }


text:
Q: JSF FacesTagExtraInfo class not in JSF 1.2 v I'm trying to move and old JSF v1.0 application from Sun One to Jboss 4.3 EAP  that has jsf v 1.2 jars. I've been able to get the application to compile and deploy but when try to run it locally it gives me a ClassNotFoundException (and rightly so) for com.sun.faces.taglib.FacesTagExtraInfo
It doesn't exist in the jsf_impl.jar, as it did in the 1.0 versions, along with 2 other class files.  I can't stick the old v in the deploy folder for jboss (one it doesn't work that way and jboss complains about local configuration error, since it wants to use it's jars).  I've done some searching but I can't seem to find a solution.

A: That class was removed in JSF 1.2 because it became superfluous with the new view handler. If you're getting this exception, then it means that you still have a jsf-api.jar of version 1.0/1.1 wandering somewhere in the classpath which got precedence over the version 1.2 one during classloading. But you do have a jsf-impl.jar of version 1.2 in the classpath (likely the appserver-provided one).
Cleanup your classpath to get rid of the old 1.0 JAR's and restart. The default paths covered by the webapp's runtime classpath are under each Webapp/WEB-INF/lib, JDK/lib and JDK/lib/ext.


text:
Q: fancy header not quite working I'm trying to format the header in the table to contents for my university's dissertation formatting.  I have two files. The first file is dis.tex and the second is asudis.sty, both pasted below. The first page of the TOC is correct/what is required but the 2nd page has TOC on the left and right headers even though the .sty files says it should be otherwise. It needs to say "Chapter" as the left header on p.2 and "Page" as the right header. On the third page with the list of tables, that is correct but the 4th and 5th pages need to also say "Table" on the left and "Page" on the right but instead say "LIST OF TABLES" for both left and right headers. Similarly for the list of figures - p.6 is correct but p. 7-8 should say "Figure" on the left and "Page" on the right. The .sty file looks correct to me in that it's asking latex to use Table and Page as the headers.
dis.tex:
\documentclass[12pt,letterpaper]{report}
\usepackage{natbib}
\usepackage[sectionbib,,globalcitecopy]{bibunits}% SC added
\defaultbibliographystyle{asudis}
\defaultbibliography{dis}
\usepackage{geometry}
\usepackage{fancyhdr}
\usepackage{afterpage}
\usepackage{graphicx}
\usepackage{amsmath,amssymb,amsbsy}
\usepackage{dcolumn,array}
\usepackage{tocloft}
\usepackage{asudis1}
\usepackage{lipsum}

\usepackage[font=xipt,labelfont=bf]{caption}

\begin{document}

\tableofcontents

% This puts the word "Page" right justified above everything else.
\addtocontents{toc}{~\hfill Page\par}
\newpage
% Making the LOT and LOF "parts" rather than chapters gets them indented at
% level -1 according to the chart: top of page 4 of the document at
% ftp://tug.ctan.org/pub/tex-archive/macros/latex/contrib/tocloft/tocloft.pdf

% This gets the headers for the LOT right on the first page.  Subsequent pages
% are handled by the fancyhdr code in the asudis.sty file.

\addcontentsline{toc}{part}{LIST OF TABLES}
\renewcommand{\cftlabel}{Table}
\listoftables
\addtocontents{lot}{Table~\hfill Page \par}
\newpage

\addcontentsline{toc}{part}{LIST OF FIGURES}
\addtocontents{toc}{CHAPTER \par}
\renewcommand{\cftlabel}{Figure}
\listoffigures
\addtocontents{lof}{Figure~\hfill Page \par}
\newpage

% This gets the headers for the LOF right on the first page.  Subsequent pages
% are handled by the fancyhdr code in the asudis.sty file.

\pagestyle{plain}

%-----------------------body
\doublespace
\pagenumbering{arabic}

\chapter{lipsum 1}
\lipsum[1-2]
\section{lipsum 1a}
\lipsum[2-3]
\section{lipsum 1b}
\lipsum[4-5]
\section{lipsum 1c}
\lipsum[6-7]
\section{lipsum 1c}
\lipsum[8-9]

\begin{figure}
\caption{\lipsum[1]}
\end{figure}
\pagebreak
\begin{figure}
\caption{\lipsum[2]}
\end{figure}
\pagebreak
\begin{figure}
\caption{\lipsum[3]}
\end{figure}
\pagebreak
\begin{table}
\caption{\lipsum[4]}
\end{table}
\pagebreak
\begin{table}
\caption{\lipsum[5]}
\end{table}
\pagebreak
\begin{table}
\caption{\lipsum[6]}
\end{table}

\chapter{lipsum 2}
\lipsum[1-2]
\section{lipsum 1a}
\lipsum[2-3]
\section{lipsum 1b}
\lipsum[4-5]
\section{lipsum 1c}
\lipsum[6-7]
\section{lipsum 1c}
\lipsum[8-9]
\begin{figure}
\caption{\lipsum[7]}
\end{figure}
\pagebreak

\begin{figure}
\caption{\lipsum[8]}
\end{figure}

\pagebreak
\begin{figure}
\caption{\lipsum[9]}
\end{figure}
\pagebreak
\begin{table}
\caption{\lipsum[10]}
\end{table}
\pagebreak
\begin{table}
\caption{\lipsum[11]}
\end{table}
\pagebreak
\begin{table}
\caption{\lipsum[12]}
\end{table}
\chapter{lipsum 3}
\lipsum[1-2]
\section{lipsum 1a}
\lipsum[2-3]
\section{lipsum 1b}
\lipsum[4-5]
\section{lipsum 1c}
\lipsum[6-7]
\section{lipsum 1c}
\lipsum[8-9]

\chapter{lipsum 4}
\lipsum[1-2]
\section{lipsum 1a}
\lipsum[2-3]
\section{lipsum 1b}
\lipsum[4-5]
\section{lipsum 1c}
\lipsum[6-7]
\section{lipsum 1c}
\lipsum[8-9]
\chapter{lipsum 3}
\lipsum[1-2]
\section{lipsum 1a}
\lipsum[2-3]
\section{lipsum 1b}
\lipsum[4-5]
\section{lipsum 1c}
\lipsum[6-7]
\section{lipsum 1c}
\lipsum[8-9]

\end{document}

2nd file is asudis1.sty:
\geometry{top=1.0in,hmargin=1.25in,height=9.0in,includefoot,
letterpaper}%,showframe,showcrop}
%
% Define singlespace and doublespace commands for 12pt fonts.
%
\newcommand{\doublespace} {
  \renewcommand{\baselinestretch}{1.66}\small\normalsize
}
\newcommand{\exactdoublespace} {
  \renewcommand{\baselinestretch}{1.8}\small\normalsize
}
\newcommand{\oneandhalfspace} {
  \renewcommand{\baselinestretch}{1.24}\small\normalsize
}
\newcommand{\singlespace} {
  \renewcommand{\baselinestretch}{0.9}\small\normalsize
}
\singlespace

%
% Fix the table of contents
%
%
% Get leader dots right.  They should all be spaced the same and need to be
% added for chapters and parts.
%
\renewcommand{\cftchapdotsep}{1.7}
\renewcommand{\cftchapleader}{\cftdotfill{\cftchapdotsep}}
\renewcommand{\cftpartdotsep}{1.7}
\renewcommand{\cftpartleader}{\cftdotfill{\cftpartdotsep}}
\renewcommand{\cftsecdotsep}{1.7}
\renewcommand{\cftsubsecdotsep}{1.7}
\renewcommand{\cfttabdotsep}{1.7}
\renewcommand{\cftfigdotsep}{1.7}
%
% Fonts for the chapter titles and part titles.
%
\renewcommand{\cftchapfont}{\rm}
\renewcommand{\cftpartfont}{\rm}
\renewcommand{\cftchappagefont}{\rm}
\renewcommand{\cftpartpagefont}{\rm}
%
% Indentations: These are in accordance with the chart at the top of page 4 of
% the document
% ftp://tug.ctan.org/pub/tex-archive/macros/latex/contrib/tocloft/tocloft.pdf
% I simply moved each of the following sections "up" one level to get the
% indentations right.
%
\cftsetindents{chapter}{1.5em}{1.5em}
\cftsetindents{section}{3.0em}{2.3em}
\cftsetindents{subsection}{5.3em}{3.2em}
%
% Spacing between entries is taken care of by the double-spacing in this
% section, so no need for extra space before chapter or part entries.
%
\setlength{\cftbeforepartskip}{0truept}
\setlength{\cftbeforechapskip}{0truept}
%
% Get the title for the TOC normal sized, centered, and at the right height.
%
\setlength{\cftbeforetoctitleskip}{-64.0truept}
\setlength{\cftaftertoctitleskip}{0truept}
%

\renewcommand{\@cfttocstart}{
   \newgeometry{top=1.0in,hmargin=1.25in,height=9.0in,
   includehead,includefoot,letterpaper}%,showcrop,showframe}

   \doublespace
   \pagestyle{fancyplain}
   \afterpage{\lhead{\cftlabel}\rhead{Page}}
}

\renewcommand{\@cfttocfinish}{
   \restoregeometry\clearpage\afterpage{\lhead{}\rhead{}}
}

%%%%%%%%%%%%%%%%%%%%
\renewcommand{\contentsname}{TABLE OF CONTENTS}
\renewcommand{\cfttoctitlefont}{\hfill\normalsize\rm}
\renewcommand{\cftaftertoctitle}{\hfill}
%
\newcommand{\cftlabel}{CHAPTER}
%
% Get rid of the header underline.
\renewcommand{\headrulewidth}{0pt}
%
% Get the header on subsequent pages right.
%
% Get the title for the LOT normal sized, centered, and at the right height.
%
\setlength{\cftbeforelottitleskip}{-64.0truept}
\setlength{\cftafterlottitleskip}{0truept}
%

\renewcommand{\listtablename}{LIST OF TABLES}
\renewcommand{\cftlottitlefont}{\hfill\normalsize\rm}
\renewcommand{\cftafterlottitle}{\hfill}
%
% Get the title for the LOF normal sized, centered, and at the right height.
%
\setlength{\cftbeforeloftitleskip}{-64.0truept}
\setlength{\cftafterloftitleskip}{0truept}
%
\renewcommand{\listfigurename}{LIST OF FIGURES}
\renewcommand{\cftloftitlefont}{\hfill\normalsize\rm}
\renewcommand{\cftafterloftitle}{\hfill}

%%%%%%%%%%

\def\@chapter[#1]#2{\ifnum \c@secnumdepth >\m@ne
                        \refstepcounter{chapter}%
                        \typeout{\@chapapp\space\thechapter.}%
                        \addcontentsline{toc}{chapter}%
                        {\protect\numberline{\thechapter}{\texorpdfstring{\MakeUppercase{#1}}{}}}%
                    \else
                        \addcontentsline{toc}{chapter}{#1}%
                    \fi
                    \chaptermark{#1}%

                    %These two lines below are commented out.

                    %\addtocontents{lof}{\protect\addvspace{10\p@}}%
                    %\addtocontents{lot}{\protect\addvspace{10\p@}}%
                    \if@twocolumn
                      \@topnewpage[\@makechapterhead{#2}]%
                    \else
                      \@makechapterhead{#2}%
                      \@afterheading
                    \fi}

%
% Change some of the rules for float placement.
%
\setcounter{topnumber}{2}          %Maximum 2 floats on top
\setcounter{bottomnumber}{1}       %Maximum 1 float on bottom
%\renewcommand{\topfraction}{0.7}    %Top float max size is 70%
%\renewcommand{\bottomfraction}{0.7} %Bottom float max size is 70%
\renewcommand{\topfraction}{0.9}    %Top float max size is 70%
\renewcommand{\bottomfraction}{0.8} %Bottom float max size is 70%
\renewcommand{\floatpagefraction}{0.7}

%
% Fix chapter and section formats
%
% Chapters names are all caps, centered under "Chapter N"
\renewcommand{\@makechapterhead}[1]{
\begin{center}
\chaptername\ \thechapter\vspace{\baselineskip}\\
\uppercase\expandafter{#1}\vspace{\baselineskip}
\end{center}
}
% Numbers chapters, sections, and subsections
\setcounter{secnumdepth}{2}
% Center section titles
\renewcommand{\section}{\@startsection{section}{1}{0 in}{1em}{1em}{\centering}}
% Center and italicize subsection titles
\renewcommand{\subsection}{\@startsection{subsection}{2}{0 in}{1em}{1em}
{\centering\slshape}}

% This is a bit of a hack.  I couldn't figure out a better way, but surely there
% is one.  What I want is for the title page of the appendix to appear with
% just one double space between the words "Appendix A" and the title.  So, here,
% I redefine the command with our \singlespace command, and then inside the
% actual appendix, I use \doublespace.  This gets the spacing of the appendix
% title page right.

\renewcommand\appendix{\par
   \setcounter{chapter}{0}%
   \setcounter{section}{0}%
   \gdef\@chapapp{\appendixname}%
   \gdef\thechapter{\@Alph\c@chapter}

   % I added this line.

   \singlespace}

%
% Fix bibliography header.
%
\renewcommand\bibname{References}
\renewcommand\bibsection{
\begin{center}\uppercase\expandafter{\bibname}\vspace{1em}\end{center}
}

%
% Modify figure captions so that they print singlespace.
%
\renewcommand{\@makecaption}[2]{% #1 is e.g. Figure 1, #2 is captiontext
  \singlespace
  {\textbf{#1:} #2\par}
}

%
% Modify footnotes to be single spaced per footnote, double in between
%

\setlength{\footnotesep}{\baselineskip} %double space between footnotes

\let\oldfootnoterule\footnoterule %dont put a gap between the line and the first footnote
\def\footnoterule{\oldfootnoterule\vspace{-0.2\baselineskip}}

\let\oldfn\footnote   %single space individual footnotes
\renewcommand{\footnote}[1]{\singlespace\oldfn{#1}\doublespace}

A: Two things:

*

*Your asudis1.sty file is not doing right things to customize the document (a lot of definitions were just hack things). My suggestion is don't use it. Anyway if you don't have other choice, at least you should know what it has been set by understanding the commands inside it. Also you should beware of the compile errors. In your dis.tex file, you need load hyperref package at the end of your preamble otherwise the \texorpdfstring command wasn't defined. The font=xipt  for caption package doesn't make sense, because you didn't \DeclareCaptionFont{xipt}{some code}. So your preamble should like this:

\documentclass[12pt,letterpaper]{report}
\usepackage{natbib}
\usepackage[sectionbib,,globalcitecopy]{bibunits}% SC added
\defaultbibliographystyle{asudis}
\defaultbibliography{dis}
\usepackage{geometry}
\usepackage{fancyhdr}
\setlength{\headheight}{15pt}
\usepackage{afterpage}
\usepackage{graphicx}
\usepackage{amsmath,amssymb,amsbsy}
\usepackage{dcolumn,array}
\usepackage{tocloft}
\usepackage{lipsum}
\usepackage{xcolor}
\usepackage{asudis1}
\usepackage{caption}
\captionsetup{labelfont=bf}
\usepackage[hidelinks]{hyperref}

*To make the header behaviors like you said, you need change the corresponding code as follow in your asudis1.sty file. I remove the letterpaper option from \newgeometry command because it is not available here.

\renewcommand{\@cfttocstart}{
   \newgeometry{top=1.0in,hmargin=1.25in,height=9.0in,
   includehead,includefoot}%,letterpaper option not available in `\newgeometry'%,showcrop,showframe} % changed

   \doublespace
   \pagestyle{fancyplain}
   \afterpage{\markboth{\normalfont Page}{\normalfont\cftlabel}\markright{\normalfont\cftlabel}}
}% changed


text:
Q: Не импортируется Google Play Services В Android Studio выбираю File->New->Import Module указываю путь к папке C:\Users\Almaz\AppData\Local\Android\sdk\extras\google\google_play_services\libproject\google-play-services_lib. Студия пишет "Select modules to import". Пробовал выносить в другую папку, то же самое

A: В build.gradle вашего модуля добавьте compile 'com.google.android.gms:play-services:7.5.0' в секцию dependencies. Так же для решения таких вопросов замечательно подходит официальная документация


text:
Q: How to turn a list of strings into a list of tuples by finding the largest repeating patterns in them in python3? I was trying to find solution for my problem for some time but couldn't find any good idea yet..
I have a list of large strings where some character patterns (there are no spaces) are repeating. For my needs I need to reduce the memory these strings take by finding these patterns and converting the list of strings into two lists: one list that has all of the pattens typed once, and one list that has tuples/lists of pointers to the pattern list so that the original string can be recreated from the tuple.
For example, for the list of strings ['FOOBAR', 'BARFOO'] I would like to get
['FOO', 'BAR'], [(0, 1), (1, 0)]
The words in the pattern list should have length of at least 2 (unless we have no other choice, for example if there is only single character between two repeating patterns or entire input string has only length of 1) - or best as long as possible (cause addressing takes memory too so if some word happens once, it should have just one pointer instead of few).
Also the algorythm needs to be fast (best linear complexity) as my script performs this operation on user's input - and I don't want my user to wait too long.
Below I show example script of how it should work:
def getLists(str_list):
    # code here
    return pointers, out_strings

strings = ["FGJohnyRFGDERT", "VBSJohnR", "AAERFGR"]
pointers, out_strings = getLists(strings)
print(pointers, out_strings)
# [(0, 1, 2, 0, 3, 4, 5), (6, 1, 7), (8, 4, 0, 7)]["FG", "John", "yR", "D", "ER", "T", "VBS", "R", "AA"]

Thank you in advance for help! <3
EDIT: Someone proposed compressions like zlib. Sadly I need to unpack original strings in a low memory and very simple language that has no zlib support. So while compression algorythm can be very complex , the decompression has to be as simple as possible.

A: This sounds like a compression problem. There's plenty of compression libraries out there. zlib is one that comes with the standard library & does a decent job of shrinking things.
Another thought is that you could change data structures. For instance, instead of a list of str, try a list of bytes, or a bytearray with a custom seeking & data segmentation protocol.
Anywho, here's an example of zlib in use:
import zlib

compressed_strings = [
    zlib.compress(string.encode(), 9)
    for string in strings
]
assert strings == [
    zlib.decompress(compressed_string)
    for compressed_string in compressed_strings
]

Best,


text:
Q: Placement of objects after a verb I learned that if we place an indirect object after a direct object, we use to/for to connect. Can we use any other preposition to do the same ?
Example:

Put the blanket on me.

Here, "me" (indirect object) is placed after blanket (direct object) using on.

A: This is not an indirect object. As Grammarly explains, an indirect object happens when a preposition is not used (e.g. "Give me the ball"). Such a sentence can be rewritten to use a prepositional phrase instead (e.g. "Give the ball to me"), but then the word in question ceases to be an indirect object.
Your sentence just has an ordinary prepositional phrase ("on me"). You couldn't use an indirect object there; you would end up writing "Put me the blanket," which obviously makes no sense.


text:
Q: In Poco::Data for SQLite, is there anyway to see the generated sql? When Poco::Data creates an SQL statment and sends it to a database (like SQLite) is there anyway to see what SQL is generated? Say even before it is sent?
For instance in the following code (similar to one of the Poco provided samples in version 1.6.1 Poco/Data/samples/TypeHandler/src/TypeHandler.cpp) is there anyway to see the generated SQL for the INSERT statement? Even if there is an InvalidSQLException thrown eventually?
using namespace Poco::Data::Keywords;
using Poco::Data::Session;
using Poco::Data::Statement;

int main() {
    Person aperson("firstName", "lastName", 1234);
    Poco::Data::SQLite::Connector::registerConnector();
    Session session("SQLite", "sample.db");
    session << "DROP TABLE IF EXISTS Person", now;
    session << "CREATE TABLE Person (Name VARCHAR(30), LastName VARCHAR(30), ID INTEGER(10))", now;
    session << "INSERT INTO Person VALUES (?,?,?)", use(aperson), now;
    return 0;
}

A: I'm not sure if it's possible for SQLite because, when binding, SQLite API wants the string with placeholders to be prepared and then bound data is bound calling sqlite3_bind*(). ODBC works differently and we can print out the native SQL string that is executed by the back-end.

A: db browser tool has option to execute sql. (http://sqlitebrowser.org/)