text:
Q: Predict the outcome of the testing data from a randomForest object I have a dataframe df
dput(df)
    structure(list(ID = c(4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5,
6, 6, 6, 6, 8, 8, 8, 9, 9), Y = c(2268.14043972082, 2147.62290922552,
2269.1387550775, 2247.31983098201, 1903.39138268307, 2174.78291538358,
2359.51909126411, 2488.39004804939, 212.851575751527, 461.398994384333,
567.150629704352, 781.775113821961, 918.303706148872, 1107.37695799186,
1160.80594193377, 1412.61328924168, 1689.48879626486, 685.154353165934,
574.088067465695, 650.30821636616, 494.185166497016, 436.312162090908
), P = c(1750.51986303926, 1614.11541634798, 951.847023338079,
1119.3682884872, 1112.38984390156, 1270.65773075982, 1234.72262170166,
1338.46096616983, 1198.95775346458, 1136.69287367165, 1265.46480803983,
1364.70149818063, 1112.37006707489, 1346.49240261316, 1740.56677791104,
1410.99217295647, 1693.18871380948, 275.447173420805, 396.449789014179,
251.609239829704, 215.432550271042, 55.5336257666349), A = c(49,
50, 51, 52, 53, 54, 55, 56, 1, 2, 3, 4, 5, 14, 15, 16, 17, 163,
164, 165, 153, 154), TA = c(9.10006221322572, 7.65505467142961,
8.21480062559674, 8.09251754304318, 8.466220758789, 8.48094407814006,
8.77304120569444, 8.31727518543397, 8.14410265791868, 8.80921738865237,
9.04091478341757, 9.66233618146246, 8.77015716015164, 9.46037931956657,
9.59702379240667, 10.1739258740118, 9.39524442215692, -0.00568604734662462,
-2.12940164413048, -0.428603434930109, 1.52337963973006, -1.04714984064565
), TS = c(9.6499861763085, 7.00622420539595, 7.73511170298675,
7.68006974050443, 8.07442411510912, 8.27687965909096, 8.76025039592727,
8.3345638889156, 9.23658956753677, 8.98160722605782, 8.98234210211611,
9.57066566368204, 8.74444401914267, 8.98719629775988, 9.18169205278566,
9.98225438314085, 9.56196773059615, 5.47788158053928, 2.58106090926808,
3.22420704848299, 1.36953555753786, 0.241334267522977), R = c(11.6679680423377,
11.0166459173372, 11.1851268491296, 10.7404563561694, 12.1054055597684,
10.9551321815546, 11.1975918244469, 10.7242192465965, 10.1661703705992,
11.4840412725324, 11.1248456370953, 11.2529612597628, 10.7694642397996,
12.3300887767583, 12.0478558531771, 12.3212362249214, 11.5650773932264,
9.56070414783612, 9.61762902218185, 10.2076240621201, 11.8234628013552,
10.9184029778985)), .Names = c("ID", "Y", "P", "A", "TA", "TS",
"R"), na.action = structure(77:78, .Names = c("77", "78"), class = "omit"), row.names = c(NA,
22L), class = "data.frame")

I have run a RandomForest on this data set with a leave one subject out cross validation. See below.
library (caret)
library(randomForest)
    # Create training dataset
    subs <- unique(df$ID)
    train<- vector(mode = "list", length = length(subs))
    test<- vector(mode = "list", length = length(subs))

# Run a RandomForest with leave one out ID CV
for(i in seq_along(subs))
train[[i]] <- which(df$ID != subs[i])
names(train) <- paste0("ID", subs)
rfFit <- train(Y~ P + TA + TS + R + A,
               data =df,
               method = "rf",
               ntree = 100,
               prox=TRUE, allowParallel=TRUE,
               importance = TRUE,
               trControl = trainControl(method = "cv",
                                         index = train))

I now want to predict the outcome of the randomForest object on a testing dataset (see below)
 # Test dataset
    for(i in seq_along(subs))
    test[[i]] <- subset(df[df$ID == subs[i],])

However, I could not implement it. Can someone help me out with it?

A: You could add the predict in your loop like below:
results <- list()
for(i in seq_along(subs)) {
      test[[i]] <- subset(df[df$ID == subs[i],])
      results[[i]] <- predict(rfFit, test[[i]])
}

print(results)
[[1]]
[1] 1913.784 2194.669 1984.460 1951.577 1907.284 2176.945 2025.345 2221.992

[[2]]
[1]  664.2550  746.0124  851.9516  960.3064 1037.9849

[[3]]
[1] 1132.243 1169.022 1292.756 1523.960

[[4]]
[1] 697.4928 603.5060 610.2461

[[5]]
[1] 667.2926 601.2800


text:
Q: Errors when installing grunt-cli with npm Since today, our project is having problems when doing the npm installation of the grunt-cli. We have specificed the following versions of the grunt packages in the package.json:
"grunt": "~0.4.0",
"grunt-cli": "^1.2.0"

The error that occurs, is the following:
[ERROR] module.js:327
[ERROR]     throw err;
[ERROR]     ^
[ERROR]
[ERROR] Error: Cannot find module '/myproject/node_modules/grunt-cli/bin/grunt'
[ERROR]     at Function.Module._resolveFilename (module.js:325:15)
[ERROR]     at Function.Module._load (module.js:276:25)
[ERROR]     at Function.Module.runMain (module.js:441:10)
[ERROR]     at startup (node.js:139:18)
[ERROR]     at node.js:974:3

Does anyone have any idea how to solve this problem? We didn't change anything.

A: It seems you have some little issue with your node_modules, you might have to delete the node_modules dir completely, then run your npm install again to have your required modules install again.
This should fix your problem.

A: It seems there is a problem with your grunt-cli. Can you please try to remove the same and install it again. You can run the following commands.
npm remove -g grunt grunt-cli

And
npm install -g grunt grunt-cli

A: Remove grunt-cli from your package.json and install it globally and grunt itself can stay in project context.
npm install grunt-cli -g

A: The problem was apparently caused by something else entirely. We changed our UI project version to x.x.x-SNAPSHOT and now it works fine.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how do I download a .war file from maven central? I have the following instructions:
Download the latest jetty-console.war from Maven Central (download the jetty-console.war artifact).
So I go to the link, here:  http://search.maven.org/#search%7Cga%7C1%7Ca%3A%22killbill-profiles-killbill%22
But how do I download using a command line (I am SSH'ing into my server).
Note:  I have read this link, but I don't seem to be able to download the plugin based on the instructions:
A simple command line to download a remote maven2 artifact to the local repository?
In part, I cannot tell what the repo URL should be if I use it, and the command doesn't appear to download the plugin.

A: Here are some generic steps:

*

*Figure out what the direct link to the file is, in your example it's this link for the war

*Use some command line tool to download the file

example with wget:
wget 'http://search.maven.org/remotecontent?filepath=org/kill-bill/billing/killbill-profiles-killbill/0.12.1/killbill-profiles-killbill-0.12.1.war'

Another possibility would be to rsync or scp the war from your machine


text:
Q: The etymology of the term "shiggy" in "Stand on Zanzibar" In John Brunner's Stand on Zanzibar (1968), there is a slang term "shiggy," which refers to a transient woman who becomes a man's temporary romantic partner as a means to obtain shelter:

That would account for the development of the shiggy circuit, the fact that the world's big cities are alive with women who've never had a permanent home, but live out of a bag and sleep a night, a week, half a year wherever there's a man with an apartment to share.

I'm having trouble figuring out the origin of this term.  Some of Brunner's invented slang has pretty clear etymology defined in-universe, e.g. "mucker" from "amok," but there's nothing within the book to suggest any words of similar sound or spelling that this term came from.
According to Urban Dictionary, "shiggy" is a term for obstacle-heavy off-trail terrain used by Hash House Harriers, but it's not clear if that term is as old as the novel, and that meaning doesn't really connect to the way Brunner uses it.
An old reference in Transactions of the Philological Society indicates that "shiggy" is an Irish term meaning "fairy", so maybe the ephemeral and fleeting nature of relationships with these women has led men to think of them as fairies.  No real textual support for this, though.
Any ideas?

A: The word appears to be a contraction of the 13th Century Scottish word "Thig" or "Thiggie" (generally used in conjunction with the word Sorn)

Thig, v. Also: thigge, thige, thyg.
1. tr. To solicit
  (food, subsistence) by begging
2. The act or process of exacting free lodging

and the word "She".
Literally, a she-beggar.
The fact that John Brunner was a resident of Glasgow, Scotland would seem to lend strong credence to this idea. This word is still in semi-regular usage.


text:
Q: Can Estimation board 2.0 include mis-sized stories in the unsized column? If the stories are mis-sized how can we not ignore it but add it to the unsized column?

A: That's a good idea.  I think the old Estimation Board (the one currently in the app catalog in the product) used to bucket mis-sized artifacts in the closest bucket- something estimated 4 would show up in the 5 column.
It should be fairly straightforward to make these changes.  I'm filing a github issue to track this request.
https://github.com/krmorse/EstimationBoard/issues/2


text:
Q: modify title/head in moderncv (\moderncvstyle{classic}) Hi I produced the following output with moderncv:

but, I would like the following one:

Would you be so nice to tell me what I can modify in my code please? Otherwise, could you propose another solution to reach the desired layout please?
\PassOptionsToPackage{dvipsnames}{xcolor}
\documentclass[11pt,a4paper,sans]{moderncv}
\moderncvstyle{classic}
\moderncvcolor{blue2}
\usepackage{etoolbox}
\usepackage[scale=0.8]{geometry}

\usepackage{selinput}
\SelectInputMappings{%
  adieresis={ä},
  eacute={é},
  Lcaron={Ľ},
}

\usepackage[symbol,bottom]{footmisc}

\makeatletter
\renewcommand*{\makecvtitle}{
\recomputecvlengths
\def\phonesdetails{}
\collectionloop{phones}{
\protected@edef\phonesdetails{\phonesdetails\protect\makenewline\csname\collectionloopkey phonesymbol\endcsname\collectionloopitem}}
\def\socialsdetails{}
\collectionloop{socials}{
\protected@edef\socialsdetails{\socialsdetails\protect\makenewline\csname\collectionloopkey socialsymbol\endcsname\collectionloopitem}}
\newbox{\makecvtitledetailsbox}
\savebox{\makecvtitledetailsbox}{
\addressfont\color{color2}
\begin{tabular}{p{0.25\linewidth}p{0.25\linewidth}}
\ifthenelse{\isundefined{\@addressstreet}}{}{\makenewline\addresssymbol\@addressstreet
&
\phonesdetails
\\
\ifthenelse{\equal{\@addresscity}{}}{}{\makenewline\@addresscity}
&
\ifthenelse{\isundefined{\@email}}{}{\makenewline\emailsymbol\emaillink{\@email}}
\\
\ifthenelse{\equal{\@addresscountry}{}}{}{\makenewline\@addresscountry}}
&\ifthenelse{\isundefined{\@homepage}}{}{\makenewline\homepagesymbol\httplink{\@homepage}}
 \socialsdetails
 \ifthenelse{\isundefined{\@extrainfo}}{}{\makenewline\@extrainfo}
\end{tabular}}
\newbox{\makecvtitlepicturebox}
\savebox{\makecvtitlepicturebox}{
\ifthenelse{\isundefined{\@photo}}
 {
    \@initializelength{\makecvtitlepicturewidth}
    \settowidth{\makecvtitlepicturewidth}{0pt}
  }
  {
   \setlength\fboxrule{\@photoframewidth}
   \ifdim\@photoframewidth=0pt
     \setlength{\fboxsep}{0pt}\fi
   {\color{color1}\framebox{\includegraphics[width=\@photowidth]{\@photo}}}}
    \@initializelength{\makecvtitlepicturewidth}
    \settowidth{\makecvtitlepicturewidth}{\usebox{\makecvtitlepicturebox}}
  }
{\raggedright\namefont{\color{color2!50}\@firstname} {\color{color2}\@lastname}}
\\[-.35em]
\ifthenelse{\equal{\@title}{}}{}{\\[1em]\null\hfill\titlestyle{\@title}}\\[0.5em]
\usebox{\makecvtitledetailsbox}
\hfill\usebox{\makecvtitlepicturebox}
    \parbox[b]{\textwidth-\makecvtitlepicturewidth}{}
\ifthenelse{\isundefined{\@quote}}%
{}%
{{\null\hfill\begin{minipage}{\quotewidth}\centering\quotestyle{\@quote}\end{minipage}\hfill\null\\[2.5em]}}%
\par}%
\makeatother

\title{super mega manager of all R\&D departments, with many years of experience in e-commerce, administration and HR}
\name{John}{Doe}
\address{Street St., 167}{8888 Town}{Country}
\phone{+1~(234)~567~890}
\email{marc.zuck@gmail.com}
\social[linkedin][www.linkedin.com/in/marc.zuck/]{marc the manager}
\photo[150pt][0pt]{pictures/picture}

\let\originalrecomputecvlengths\recomputecvlengths
\renewcommand*{\recomputecvlengths}{
\originalrecomputecvlengths
\setlength{\quotewidth}{0.8\textwidth}}

\usepackage{ragged2e}
\renewcommand*{\quotefont}{\large\slshape\justifying}
\renewcommand{\quotestyle}[1]{\quotefont\color{color1}#1}

\quote{this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote}

\begin{document}

\makecvtitle % Print the CV title

\end{document}

Anyone who can help here please ?

A: This approach uses minipages to organize header elements.

% !TeX TS-program = pdflatex

\PassOptionsToPackage{dvipsnames}{xcolor}
\documentclass[11pt,a4paper,sans]{moderncv}
\moderncvstyle{classic}
\moderncvcolor{blue}

\usepackage[scale=0.8]{geometry}
\usepackage[T1]{fontenc}
\usepackage{lmodern}

\usepackage{ragged2e}

\usepackage{showframe} % show margin <<<<<<<<<<<<<<<<<<<<<

\makeatletter
\renewcommand*{\makecvhead}{% changed <<<<<<<<<<<<<<<<<<<<<<
    \recomputecvlengths
    \def\phonesdetails{}
    \collectionloop{phones}{
    \protected@edef\phonesdetails{\phonesdetails\protect\makenewline\csname\collectionloopkey phonesymbol\endcsname\collectionloopitem}}
    \def\socialsdetails{}
    \collectionloop{socials}{
    \protected@edef\socialsdetails{\socialsdetails\protect\makenewline\csname\collectionloopkey socialsymbol\endcsname\collectionloopitem}}
    \newlength{\leftside}
    \setlength{\leftside}{0.95\textwidth-\@photowidth}
    \begin{minipage}{\leftside}{%
        \raggedright\namefont{\color{color2!50}\@firstname} {\color{color2}\@lastname}}
        \vspace*{2em}\\
        \titlestyle{\@title}
        \vspace*{2em}\\
        \addressfont\color{color2}
        \begin{tabular}{p{0.5\leftside}p{0.45\leftside}}
            \ifthenelse{\isundefined{\@addressstreet}}{}{\makenewline\addresssymbol\@addressstreet
            &
            \phonesdetails
            \\
            \ifthenelse{\equal{\@addresscity}{}}{}{\makenewline\@addresscity}
            &
            \ifthenelse{\isundefined{\@email}}{}{\makenewline\emailsymbol\emaillink{\@email}}
            \\
            \ifthenelse{\equal{\@addresscountry}{}}{}{\makenewline\@addresscountry}}
            &\ifthenelse{\isundefined{\@homepage}}{}{\makenewline\homepagesymbol\httplink{\@homepage}}
            \socialsdetails
            \ifthenelse{\isundefined{\@extrainfo}}{}{\makenewline\@extrainfo}
        \end{tabular}
    \end{minipage}\hfill
    \begin{minipage}{%
            \@photowidth}{\includegraphics[width=\@photowidth]{\@photo}}
    \end{minipage}\vspace*{2em}\\
    \ifthenelse{\isundefined{\@quote}}%
        {}%
        {\begin{minipage}{%
                \quotewidth}\centering\quotestyle{\@quote}
        \end{minipage}\vspace*{2em}\\
        }%
}% end makecvhead
\makeatother

\title{super mega manager of all R\&D departments, with many years of experience in e-commerce, administration and HR}
\name{John}{Doe}
\address{Street St., 167}{8888 Town}{Country}
\phone{+1~(234)~567~890}
\email{marc.zuck@gmail.com}
\social[linkedin][www.linkedin.com/in/marc.zuck/]{marc the manager}
\photo[150pt][0pt]{picture}

\renewcommand*{\recomputecvheadlengths}{%
\setlength{\quotewidth}{0.8\textwidth}}
\renewcommand*{\quotefont}{\large\slshape\justifying}
\renewcommand{\quotestyle}[1]{\quotefont\color{color1}#1}

\quote{This is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote, this is a very long quote}

\begin{document}

\makecvtitle

Some other text

\end{document}

If the photo is not present, use \photo[0pt][0pt]{picture}


text:
Q: Blackscreen after boot ubuntu 12.10 I have a dual boot (w7, ubuntu 12.10 ) laptop. Everything was OK since some weeks. Now I am unable to boot my ubuntu 99 times of a hundred.
The process start with the bios settings and all, then grub screen shows up normally ( with all the correct options ) then, when I choose ubuntu option screen turns black ( with back-light )  and that's all ...
I have tried with Ctrl+Alt+F1 to try to drop to the root console but nothing happens ...
IF I try enough times the logging screen shows up and from there everything goes smoothly.
This is my first serious issue with Ubuntu (and I'm using it since 8.04 version ) and I have no idea where to start investigating ...
This error has made my computer unusable so please, I need help ...
Thanks for all in advance.
P.S.:Since I updated to 12.10 while I am working normally from time to time a window pops up with a "System program problem detected". I haven't found a way to get more details about the problem and after reading some web sites seems something "normal" ( or at least common ) but I mention it here just in case.

A: I am not sure if this is the same problem I had, but this solved it for me:
in grub select the ubuntu entry and press e. now look for the words 'quiet splash'. delete them and type 'nomodeset' in stead. now press f10 to boot into ubuntu. I can not tell you what happens or why it works, but for me it did. I got my answer from here.

A: well it seems that the problem is the kernel version.
Last kernel update was 3.5.0-27 and it seems it has some problems with the video drivers of multiple graphic cards.
After reading this two bug reports I thought the kernel could be the problem and try to boot with the 3.5.0-26 ( thanks good that ubuntu stores the last used kernels just in case ), no problem since then. I have been able to boot my laptop 10 times from 10 tries so I think the problem was the kernel.
I do not know what the problem was exactly and the bug reports are not solved yet, so until then I will not update my system to the 3.5.0-27 kernel version.
Thanks for your answers


text:
Q: Gradle mixing versions 27.1.1 and 26.1.0 [Android Studio] For the build.gradle configuration, everything is ok.
compileSdkVersion 26
defaultConfig {
    applicationId "com.my.app"
    minSdkVersion 16
    targetSdkVersion 26
    multiDexEnabled true
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

dependencies {
implementation project(':market_licensing')
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.google.android.gms:play-services-ads:17.1.2'
implementation 'com.android.support:multidex:1.0.3'
implementation 'com.android.support:design:26.1.0'
implementation "com.android.support:appcompat-v7:26.1.0"
}

When I migrate to version 27,
compileSdkVersion 27
defaultConfig {
    applicationId "com.my.app"
    minSdkVersion 16
    targetSdkVersion 27
    multiDexEnabled true
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

dependencies {
implementation project(':market_licensing')
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.google.android.gms:play-services-ads:17.1.2'
implementation 'com.android.support:multidex:1.0.3'
implementation 'com.android.support:design:27.1.1'
implementation "com.android.support:appcompat-v7:27.1.1"
}

I have an error:

All com.android.support libraries must use the exact same version
  specification (mixing versions can lead to runtime crashes). Found
  versions 27.1.1, 26.1.0.

Why am I still showing a conflict with the old version 26.1.0? I do clean.

A: customtabs need to be provided in version 27.1.1 ...
implementation "com.android.support:customtabs:27.1.1"
implementation ("com.google.android.gms:play-services-ads:17.1.2") {
    exclude group: "com.android.support", module: "customtabs"
}

A: Try to clean and rebuild your project. Also if it does not work check whether all dependencies are the same and maybe change versions to a bit newer or older ones.
I also strongly recommend using androidX it's  feels really good to me


text:
Q: python: how do I give the option to the user to restart the program from the top if he chooses to do so? I made a mini mortgage calculator as practice (I am a beginner) and at the end of the code, I would like to ask the user if they want to recalculate from the beginning, making the program jump back to the first line of code, or give them the option to exit.
I have tried to add the line:
def main():
and then indent the rest of the program, so at the end I can use if and else method to either recall the program by simply saying
if ask == yes:
   main ()
however this does not seem to work. Whenever I add "main ()" at the top of my code, and click "run", the program doesnt run altogether. Just nothing happens. I have tried doing while loops but then im not sure what to put at the end.
def main():
  numbers = [61]
  for x_count in numbers:
  output = ""
  for count in range(x_count):
    output += "x"
  print(output)
  print("                          Mortgage Calculator                 ")
  print("*************************************************************")
  print("                                                             ")
  name = input("Enter your full name: ")
  price = int(input("Enter the price of the property: "))
  ask = input("Do you know your interest rate? Enter Y for yes, N for no: ")
  incentive = input("Have you owned a property in the past 5 years?")

that is only the beginning of the code. the end is:
end_code = input("Would you like to recalculate? press Y for yes, N for no: ")
if ask.upper == "Y"
     main ()
else
   breakpoint()
As evident, I was expecting the program to call the main() and then restart, but that does not work. However, the program does not even start when I use that method of restarting program.

A: Most apps have a "Main" loop.  If your program started with a simple:
def main():

    keepRunning=True

    while keepRunning:
        keepRunning = runMortgageCalculator()

At that point all the code you have now would go into runMortgageCalculator() and it would return a "true" to keep going and a "False" to end.
There, I think I got the python syntax right now, if not please enhance or comment.


text:
Q: UITabBarController with portrait / landscape views I have a subclass of UITabBarController which i am using so that i can rotate to use my app in landscape too.
How would i go about rotating my UI and getting each view controller to use a landscape view xib?
I have always just written apps before where returning YES for shouldAutorotate... handles it automatically for me... this isn't the case here now, as i'm using a custom view.
Thanks.

A: You don't need to subclass UITabBarController to get the autorotation behavior. Instead what you should do is have ALL the UIViewControllers that appear in your UITabBarController return YES for shouldAutorotateToInterfaceOrientation:. If even one of them does not, the UITabBarController will not autorotate.
As for the custom view, it is associated with a UIViewController, right? If so, then if your custom view implements layoutSubviews using the current view bounds to lay out all the subviews, then it should autorotate correctly as well.


text:
Q: terraform plan not working with azurerm provider I want to create a resource group in the azure cloud using terraform, for which I have to configure azurerm provider.
I created SPN using cli.
# az ad sp create-for-rbac --name spn_devops_terraform  --role="Contributor" --scopes="/subscriptions/XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXX"

The output includes credentials that you must protect. Be sure that you do not include these credentials in your code or check the credentials into your source control. For more information, see https://aka.ms/azadsp-cli
{
  "appId": "YYYYYY-YYYY-YYYY-YYYY-YYYYYYYYY",
  "displayName": "spn_devops_terraform",
  "password": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "tenant": "XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXX"
}

To test my SPN spn_devops_terraform, I logged in via cli
az login --service-principal -u YYYYYY-YYYY-YYYY-YYYY-YYYYYYYYY -p XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX --tenant XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXX

then executed
az vm list --output table

And i can see the list of all the VMS.
Now here is my main.tf file
terraform {
  required_providers {
    azurerm = {
      source = "hashicorp/azurerm"
      version = "3.0.2"
    }
  }
}

provider "azurerm" {
  features {}

  subscription_id = "XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXX" # copy pasted this from portal.
  client_id       = "YYYYYY-YYYY-YYYY-YYYY-YYYYYYYYY" # this is app_id
  client_secret   = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" # password
  tenant_id       = "XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXX"  # tenant

}

I initialized the terraform with "terraform init" command which goes fine.
But when i execute terraform plan it just hung for 10 mins and i have to press CTRL + C to stop it.
Please wait for Terraform to exit or data loss may occur.
Gracefully shutting down...
Stopping operation...
╷
│ Error: Unable to list provider registration status, it is possible that this is due to invalid credentials or the service principal does not have permission to use the Resource Manager API, Azure error: resources.ProvidersClient#List: Failure sending request: StatusCode=0 -- Original Error: context canceled
│
│   with provider["registry.terraform.io/hashicorp/azurerm"],
│   on main.tf line 10, in provider "azurerm":
│   10: provider "azurerm" {
│
╵

What i am going wrong? what is fix and if there is any command in CLI or GUI in portal where i can see what is happening?

A: Tested in my enviromemt getting the same kind of error.It looks like the Service Principal doesn't have the Contributor role assigned to it/Doesn't have access to the subscription.
You can define the scope of service principle while creating it.
$ az ad sp create-for-rbac --role="Contributor" --scopes="/subscriptions/SUBSCRIPTION_ID"

OR
Just go to the Subscription in the portal, select Access Control (IAM) and Add the Role assignment, Contributor to your Service Principal

You can refer this Terraform Document to Authenticating using a Service Principal with a Client Secret
Reference : Terraform unable to list provider registration status


text:
Q: json распарсить из php формирую вот такой json
return response()->json(['datam' => $smessage->created_at, 'photo' => Auth::user()->attributes->photo])

в js пробую распарсить так
var parse_data = JSON.parse(data);
alert(parse_data['datam']);

но выдает
VM1804:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)

A: Это потому что data не строка json, а обычный объект, можете увидеть это из примера:

try {
  JSON.parse({ datam: '123' })
} catch ({ message }) {
  console.log(message)
}


text:
Q: How to proxy nginx request while keeping same url I'm using a self hosted service stack app with this configuration. So when I browse mysite.com/json/reply/mytestmethod I get redirected to mysite.com:1337/json/reply/mytestmethod. the app works fine except looking for help in removing the port 1337 part and make it appear to come from the mysite.com domain.
Cheers!
server {
  listen 80;
  server_name mysite.com;

  root /var/www/mysite.com/html;
  index index.html;

  location / {
    proxy_set_header   X-Real-IP $remote_addr;
    proxy_set_header   Host      $http_host;
    proxy_pass         http://127.0.0.1:1337;
  }
}

A: If you want to strip the port you'll want to use a reverse proxy rather than redirect. In nginx a typical reverse proxy configuration looks like:
server {
    listen 80;
    server_name mysite.com;

    location / {
        proxy_pass http://localhost:1337/;
        proxy_redirect off;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;
    }
 }


text:
Q: Bootstrap 3 datatimepicker clears my value from textbox I have problem with bootstrap datetimepicker.
When my datatimepicker is active (javascript works), the textfield is empty.
When I will change of id for div with id="ada" and my datatimepicker isn't active, the data is printed correctly. It it MWE for my code (generated by asp.net mvc with razor).
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="Content/bootstrap.css" rel="stylesheet" />
    <link href="Content/site.css" rel="stylesheet" />
    <link href="Content/bootstrap-datetimepicker.css" rel="stylesheet" />

                <input class="form-control" data-val="true" data-val-date="The field DataPoczatku must be a date." data-val-required="The DataPoczatku field is required." id="katalog_DataPoczatku" name="katalog.DataPoczatku" type="date" value="2015-03-01 00:00:00" />

Somebody have idea how to keep the value of textbox with active datapicker?
https://jsfiddle.net/abbdzpg2/

A: You should give a date format YYYY-MM-DD in your input value and set a format value in your settings too. Check this fiddle. Is this the result you wanted?
$(document).ready(function () {
    $('#ada').datetimepicker({
        format: 'YYYY-MM-DD'
    });
});

        <input class="form-control" data-val="true" data-val-date="The field DataPoczatku must be a date." data-val-required="The DataPoczatku field is required." id="katalog_DataPoczatku" name="katalog.DataPoczatku" type="date" value="2015-03-01" />

A: If you want to set a default date for the timepicker, you need to do this in the jQuery script, rather than setting a value. This is because the add on overrides the default behaviour of the form control.
var date = new Date('2015-03-01');

$(document).ready(function () {
    $('#ada').datetimepicker({
        defaultDate: date
    });
});


text:
Q: Errors with BitByteArray I'm trying to create a 2 dimensional array and I need an eight bit Byte Array because I'm displaying audio waveforms. However I keep getting errors in the eightBitByteArray[t] and the sixteenBitByteArray[t]. Any suggestions on how I could fix this?
I've also tried replacing it with the file name but it doesn't seem to work.
    for (int t = 0; t < eightBitByteArray.length;) {
            for (int channel = 0; channel < numChannels; channel++) {
                int low = (int) eightBitByteArray[t];
                t++;
                int high = (int) eightBitByteArray[t];
                t++;
                int sample = getSixteenBitSample(high, low);
                toReturn[channel][sampleIndex] = sample;

A: You don't reset the value of t to 0 anywhere. So my guess would be that you are exceeding the size of eightBitByteArray at some point. You're also not checking if t ever exceeds the size of eightBitByteArray in the second increment of t.
But unless you post more details, like the exception, location, sample input data,etc. its hard to say. Also post some more code.


text:
Q: In a ring with identity, the maximal ideal is unique one? One of Propositions in Dummit's textbook says this:
In a ring with identity $1\neq 0$ every proper ideal is contained in a maximal ideal.
So can I conclude that the maximal ideal is unique in this case?
Or maybe not?

A: No. Take $R = C[0,1]$, then the maximal ideals are all of the form
$$
M_{x} := \{f \in C[0,1] : f(x) = 0\}
$$
One for each $x \in [0,1]$, so certainly not unique.

A: Nope.
Every ideal is contained in a maximal ideal (proven using Zorn's lemma), but in general this is definitely not unique.
Consider $(6) = 6\mathbb{Z}$ in $\mathbb{Z}$. $(6)$ is contained in both $(3) = 3\mathbb{Z}$ and $(2) = 2\mathbb{Z}$ (both of which are maximal in $\mathbb{Z}$.
[Note: $(2)$ and $(3)$ are maximal since $\mathbb{Z}/(2)$ and $\mathbb{Z}/(3)$ are fields.]

A: You cannot. The theorem just says "contained," not "properly contained," so any maximal ideal trivially satisfies this condition: it is contained in itself. For example, $\Bbb{Z}$ has infinitely many maximal ideals: one for each prime.
Rings with exactly one maximal ideal do, however, have a name: they are called local rings.


text:
Q: Adding FontAwsome Icon + Text gives me error I have this method with a textArea:
 DropdownExampleClearable = () => <Dropdown placeholder="Status" clearable options={options} selection />

And this is the Options that it has:
const options = [
 { key: 1, text: ( + "OK"), value: 1 },
 { key: 2, text: , value: 2 },
]

The first key will display '[Object object]OK'
The second key will display the desired Icon but if i add any text the icon wont show anylonger.
Any suggestions on how to get the icon+text to display would be much appreciated.

A: JSX is just sugar for React.createElement calls, so you can't add a string to that with + "OK".
You could instead wrap the icon and the text in another React element and use that.
const options = [
  { key: 1, text:  OK, value: 1 },
  { key: 2, text: , value: 2 }
]

A: Try this

  OK


text:
Q: Calculate the pushforward of a vector field Consider the vector fields
$X=xy\frac{\partial}{\partial x}+x^{2}\frac{\partial}{\partial z}$, and $Y=y\frac{\partial}{\partial y}$ on $R^{3}\rightarrow R$, and $f(x,y,z)=x^{2}y$.
Compute:  $f_{*}(X_{(1,1,0)})$
There is a similar question posted here, I read it but it did not answer my question, I also searched for the formula but I don't think it helped..
I got a solution saying:
$f_{*}(X_{(1,1,0)})=(\frac{\partial f}{\partial x} \frac{\partial f}{\partial y} \frac{\partial f}{\partial z})_{(1,1,0)}\begin{pmatrix}
1\\
0\\
1\end{pmatrix}=2\frac{d}{dt} \mid_{1}$, where $t$ denotes the canonical coordinates on $R$.
I understand that $(\frac{\partial f}{\partial x} \frac{\partial f}{\partial y} \frac{\partial f}{\partial z})_{(1,1,0)}$ is the Jacobian matrix of $f$ at point $(1,1,0)$, and I found that if I plug the point $(1,1,0)$ into $X$, and it will give me $\frac{\partial}{\partial x}+0 \frac{\partial}{\partial y}+\frac{\partial}{\partial z}$, so it will give me $\begin{pmatrix}
1\\
0\\
1\end{pmatrix}$. and thus multiplying two matrices will get me $2$
But why all of those become together? and why it produced
$2\frac{d}{dt} \mid_{1}$, and what is the canonical coordinates on $R$?

A: If you have a differentiable map $f:M\to N$, then its differential $Df$ at a given point $p$ is a linear map $T_pM\to T_{f(p)}N$. So far, so good.
Now the linear map $Df$ is represented by the Jacobian matrix given a system of coordinates. This matrix takes as input a $3$-coordinate vector and outputs a $1$-coordinate vector, which is a little bit more than just a real number because it lives in the tangent space to $\mathbb{R}$ at a particular point. Also, note that for a matrix to make sense you need to choose coordinates in the domain, and in the codomain. So there you are, $\frac{\partial}{\partial t}|1$ is the basis vector of the tangent space to $\mathbb{R}$ at the point $1$.
If your vector in $T_pM$ is given by $v=(v_x,v_y,v_z)$ then $Df_x(v)$ is by definition the dot product $\left(\frac{\partial f}{\partial x}|_p\,\,\frac{\partial f}{\partial y}|_p\,\,\frac{\partial f}{\partial z}|_p\right)\cdot(v_x\,\,v_y\,\,v_z)$ multiplied by this basis vector.
The canonical coordinates in $\mathbb{R}$ is simply the coordinate system induced by considering the identity map as a coordinate map.


text:
Q: jQuery Flot and graphTable Colors How can I change the line colors with the flot plugin and graphTable:
$('table.statics').graphTable({series: 'columns', position :
       'replace', height : '180px'});

But I would like to change the colors in the options of graphTable, something like:
$('table.statics').graphTable({series: 'columns', position :
       'replace', height : '180px',
       colors: ["#92d5ea", "#666699", "#be1e2d", "#ee8310", "#8d10ee"]});

And then each line in the resulting flot graph would have the corresponding colors from the column.

A: In flot you can specify the color for a particular series:
//series object
{
  data: rowData,
  label: label,
  color: '#92d5ea'
}

Looking through the graphTable plugin, there's a line like this twice:
tableData[tableData.length] = { label: label, data: rowData };

That's where it is creating the series object.  So you would have to figure out your color in that area and then set it.
EDIT:  If you want to be able to set it via the graphTable call, you'll have to edit the graphTable plugin and add a colors argument as a possibility.  Here's how:
//find the line after "var args = {" and add this
colors: null,

Then later, instead of
tableData[tableData.length] = { label: label, data: colData };

Put this:
var series = {label: label, data: colData };
if (args.colors && args.colors[j-args.dataStart]){
    series.color = args.colors[j-args.dataStart]
}
tableData[tableData.length] = series;

Note I am only showing how to deal with the columns section, not rows.  Now you can do something like this:
$('#table1').graphTable({series: 'columns', colors: ['red','red','blue']});

And the result looks like this (doesn't work in IE due to no excanvas).


text:
Q: Issue with Custom accordion I am trying to highlight the selected accordion tab background, its working but the CSS of selected accordion tab doesn't change selecting any other tab
The code and CSS is as follows

According to me the problem is with below statement:
$(".accordion-content").not($(this)).css({ "background-color": "#E4E4E4" });

he html is as

  first element

 Security

 Security

  second element

Lorem ipsum dolor sit amet mauris eu turpis.

Js Fiddle link

A: It is not a good idea to use $(this) repeatedly; Try following:
$this = $(this);

And then use your $this variable.
Also, you're binding click to (".accordion-toggle") element, so $(this) is .accordion-toggle. But then you check for a group of $(".accordion-content").not($(this)). Are those several classes on the same set of elements?

A: I think I get you now, you need to reset the background colour in your jQuery:
 $(document).ready(function ($) {
        $('#accordion').find('.accordion-toggle').click(function () {
            //stop us reusing $(this) as it's not efficent
            var $this = $(this);

            //First things first, reset all the accordion's colours back to default
            $("#accordion .accordion-toggle").css('background-color', '#E4E4E4');
            //Expand or collapse this panel
            $this.next().slideToggle('fast');

            //now set only the correct one to the new colour
            $this.css( "background-color", "#191970" );

            //Hide the other panels
            $(".accordion-content").not($this.next()).slideUp('fast');
        });
    });

Updated fiddle


text:
Q: How to add meta description/title to contact page in opencart The contact page of my site is https://example.com/contact_us . On google, it shows like
which is not very good.
It seems there is no way to edit from admin panel the meta title and meta description of this page. neither on theme panel.
So, how to edit this from core files?
catalog/view/theme/default/template/information/contact.tpl

seems not having any related, and don't see a way to edit loading header just for this one page
can you have any idea ?

A: I hope it's 100% working for you.
Find the controller Path of Page. you wish to edit and then do the below,

PATH : catalog\controller\information\contact.php

Find:
$this->document->setTitle($this->language->get('heading_title'));

Add After:
$this->document->setDescription('My description, this is where i type my text after i remove this text.');
$this->document->setKeywords('my, keyword, this, is, the place, holder, for, my, keywords');


text:
Q: Anyone has a good recommendation of a free pdf book on group theory? Anyone has a good recommendation of a free pdf book on group theory?
I am specially interested in its application for computer science, however, I do not want it to be less mathematically rigorous just because of that.
I found one that was good, but it only dealt with commutative groups throught the text :(

A: If you are fearless, Milne's notes on group theory are pretty good (they are meant to a first year graduate-level course in mathematics): http://www.jmilne.org/math/CourseNotes/gt.html

A: Have you ever seen this?
Schaum's outline of theory and problems of group theory

A: There are online copies of Artin's Algebra 2nd Ed

A: We used this (Judson) in my Algebra class. It's pretty good and offers numerous computational exercises using Sage and has sections on cryptography and other computational topics. I enjoyed it.
Note that this text covers more than just group theory and goes into rings, fields, modules, etc. It is meant as a first (and second) course in Algebra text.


text:
Q: Looking for function with specific properties I need a function $f$ that is arbitrarly times differentiable and which has integral
$$\int _a^b f(x) dx $$ strictly positive (where $a$ and $b$ are fixed), and for all derivatives, we have $$f^{(n)}(b)=f^{(n)}(a)=0.$$ I tried with $\sin$ and $\cos$, but was unsuccessful. Does anybody know such a function?

A: Look at Wikipedia, bump function.
The main tool is the function $f(x)=0$ for $x\le 0$, and $f(x)=e^{-1/x^2}$ for $x\gt 0$. This is everywhere differentiable, and all of its derivatives at $0$ are $0$.
Then the function $f(1-x^2)$ does what you want, with $a=-1$ and $b=1$. We can shift $-1$ to $a$ and $1$ to $b$ using an appropriate linear function.


text:
Q: Get children method's annotation in Java using reflection or something like this OBS: My code is java 8.
For example, I have this stacktrace:
MainClass:MethodA() calls
--------ClassB:MethodB() calls
------------ClassC:MethodC() @Cacheable calls
----------------ClassFinal:MethodD()
MethodA() -> MethodB() -> MethodC() -> MethodD();

In my example, ClassC:methodC() it's noted with @Cacheable.
I need get this annotation in ClassFinal:MethodD(), something like this:
    public void MethodD() {
        Cacheable cacheable = ...
    }

I already done this using reflection, but it isn't work with overload:
    public static <T extends Annotation> T getStacktraceAnnotation(Class<T> type) {
        int currStack = 0;
        T result = null;

        //
        //
        StackTraceElement[] stackTraceElementArray = Thread.currentThread().getStackTrace();

        //
        //
        for (java.lang.StackTraceElement curr : stackTraceElementArray) {
            try {
                Method[] methods = Class.forName(curr.getClassName()).getMethods();

                for (Method currMethod : methods)
                    if (currMethod.getName().equals(curr.getMethodName())) {
                        result = currMethod.getAnnotation(type);
                        if (result != null) break;
                    }
                //
                //
                if (result != null || currStack++ > 6) break;
            } catch(Exception exc) {
                // Nothing!
            }
        }
        //
        //
        return result;
    }

Real stacktace of my program:
fff.commons.serverless.abstracts.v2.AbstractCommonIntegrationHttp.sendGet(AbstractCommonIntegrationHttp.java:320)
fff.commons.serverless.abstracts.v2.Teste.a(Teste.java:14)
fff.commons.serverless.abstracts.v2.Teste.main(Teste.java:18)

Teste.a(Teste.java:14) is noted with @Cachable
And I need get this anottation in sendGet(AbstractCommonIntegrationHttp.java:320)
My annotation:
@Retention(RUNTIME)
@Target({ TYPE, METHOD })
@Inherited
public @interface Cacheable {
    int secs() default 15;
}

A: I strongly suggest using a StackWalker instead:
private static final StackWalker SW = StackWalker
        .getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);

public static <T extends Annotation> T getStacktraceAnnotation(Class<T> type) {
    return SW.walk(s -> s.map(sf -> getMethodAnnotation(type, sf)).filter(Objects::nonNull)
            .findFirst()).orElseThrow();
}

private static <T extends Annotation> T getMethodAnnotation(Class<T> annotationClass,
        StackFrame sf) {
    try {
        return sf.getDeclaringClass()
                .getDeclaredMethod(sf.getMethodName(), sf.getMethodType().parameterArray())
                .getAnnotation(annotationClass);
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(e);
    }
}

The StackWalker.StackFrame contains the information needed to distinguish between different overloads - namely the method type.
A StackTraceElement only contains the line number - which might be good enough if you parse the corresponding class file yourself - but this gets quickly out of hand.


text:
Q: Why is the ring homomorphism $\Gamma: D^{o}\rightarrow \text{End}_{M_n(D)}(D^n)$, where $D$ is a division ring, a bijection? It is said in this answer that for any division ring $D$, the following ring homomorphism is a bijection:
$\Gamma: D^{o}\rightarrow \text{End}_{M_n(D)}(D^n)=\{M_n(D)\text{-module endomorphisms of }D^n\}\\d\mapsto \theta_d\quad \text{s.t.}\quad \theta_d(x_1,\ldots,x_n)=(x_1d,\ldots,x_nd)$
I can see why it is an injective homomorphism (if $d\neq d'$, $(x_1 d,\ldots,x_n d) \neq (x_1 d',\ldots,x_n d')$) but I'm not sure about how to prove it is surjective too. How can I write every element of $\text{End}_{M_n(D)}(D^n)$ in that form?
Oh, I also wanted to know what does the notation $D^o$ exactly mean here.

A: Here $D^o$ refers to the opposite ring of $D$, i.e. $D$ but with its order of multiplication reversed.  This is needed in order for $\Gamma$ to be a ring homomorphism, since $\theta_{de}(x)=\theta_e(\theta_d(x))$ with the order of $e$ and $d$ reversed (right multiplication by $de$ means you first multiply by $d$ and then by $e$), so $\Gamma$ only preserves multiplication if you reverse the order of multiplication on the domain or codomain.
Surjectivity of $\Gamma$ is indeed nontrivial.  To prove it, suppose $f:D^n\to D^n$ is an $M_n(D)$-module homomorphism. Let $e_i$ denote the $i$th standard basis vector of $D^n$, and let $E_{ij}\in M_n(D)$ denote the matrix whose $ij$ entry is $1$ and all other entries are $0$.  Note that $E_{ij}e_j=e_i$ and $E_{ij}e_k=0$ if $k\neq j$.
Now write $f(e_1)=\sum a_ie_i$ for some $a_i\in D$.  Note that for each $k\neq 1$, we have $E_{jk}e_1=0$ and hence $$0=f(E_{jk}e_1)=E_{jk}f(e_1)=\sum_i a_iE_{jk}e_i=a_ke_j.$$  Thus $a_k=0$ for all $k\neq 1$.  That is, $f(e_1)=de_1$ where $d=a_1$.  For each $i$, we then have $$f(e_i)=f(E_{i1}e_1)=E_{i1}f(e_1)=dE_{i1}e_1=de_i.$$
Finally, for arbitrary $x=(x_1,\dots,x_n)\in D^n$, we have $x=\sum x_ie_i$ so $$f(x)=\sum x_if(e_i)=\sum x_ide_i=\theta_d(x).$$


text:
Q: How can I fix 'Maximum call stack size exceeded' AngularJS I am using AngularJs and Ui-Router and I am trying to set two different home pages, one for users that are logged in and the other for users that aren't. But I am getting the following error:
RangeError: Maximum call stack size exceeded

I ran console.trace() and I can see that there is an issue which is causing the states to loop infinitely (or something like that). BUt I have no idea how to fix it.
Here is the code that is generating the error.
.run(function ($rootScope, $state, $location, Auth) {
    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState) {
      if(fromState.name === "") {
        if (Auth.isLoggedIn()) {
            $state.go('main');
            event.preventDefault();
        } else {
          $state.go('welcome');
          event.preventDefault();
        }
      } else {
         if (toState.authenticate && !Auth.isLoggedIn()) {
             $location.path('/login');
             event.preventDefault();
         }
      }
    });

From what I can tell it seems to stem from if(fromState.name === "")

A: Use $state.go("main", {}, {notify:false}); for not notify to "$stateChangeStart"event.
  // NOT authenticated - wants any private stuff
  if(shouldLogin)
  {
    $state.go("main", {}, {notify:false});
    event.preventDefault();
    return;
  }

  // authenticated (previously) comming not to root main
  if(Auth.isLoggedIn)
  {
    var shouldGoToMain = fromState.name === ""
                      && toState.name !== "main" ;

    if (shouldGoToMain)
    {
        $state.go("main", {}, {notify:false});
        event.preventDefault();
    }
    return;
  }

A: I've created an example, playing with default pages and auth/unauth user. Similar issue could be seen here
Firstly this would be the listener:
app.run(function ($rootScope, $state, $location, Auth) {

    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState) {

      var shouldLogin = toState.data !== undefined
                    && toState.data.requireLogin
                    && !Auth.isLoggedIn ;

      // NOT authenticated - wants any private stuff
      if(shouldLogin)
      {
        $state.go('login');
        event.preventDefault();
        return;
      }

      // authenticated (previously) comming not to root main
      if(Auth.isLoggedIn)
      {
        var shouldGoToMain = fromState.name === ""
                          && toState.name !== "main" ;

        if (shouldGoToMain)
        {
            $state.go('main');
            event.preventDefault();
        }
        return;
      }

      // UNauthenticated (previously) comming not to root public
      var shouldGoToPublic = fromState.name === ""
                        && toState.name !== "public"
                        && toState.name !== "login" ;

      if(shouldGoToPublic)
      {
          $state.go('public');console.log('p')
          event.preventDefault();
      }

      // unmanaged
    });
});

What is happening?

*

*We check if user is logged in. If not, but requires access to not public stuff... we redirect to login

*user is logged in but not going directly to main... we transfer him

*user is not logged in, but not going to public ... we redirect

*else... let it be

And here are states:
  $stateProvider
    // available for anybody
    .state('public',{
        url : '/public',
        template : '
public
',
    })
    // just for authenticated
    .state('main',{
        url : '/main',
        template : '
main for authenticated
',
        data : {requireLogin : true },
    })
    // just for authenticated
    .state('other',{
        url : '/other',
        template : '
other for authenticated
',
        data : {requireLogin : true },
    })
    // the log-on screen
    .state('login',{
        url : '/login',
        templateUrl : 'tpl.login.html',
        controller : 'LoginCtrl',
    })

Check plunker here or here


text:
Q: Method reference in Java unil BiFunction I have question about passing method reference as argument in java (util) functions.
I have two functions
Function<Value, Output> f1 = (val) -> {
    Output o = new Output();
    o.setAAA(val);
    return o;
};

Function<Value, Output> f2 = (val) -> {
    Output o = new Output();
    o.setBBB(val);
    return o;
};

I want to merge them into one function which should looked like
BiFunction<MethodRefrence, Value, Output> f3 = (ref, val) -> {
    Output o = new Output();
    Output."use method based on method reference"(val);
    return o;
};

I want to use this function like
f3.apply(Output::AAA, number);

Is it possible ? I can't figure out correct syntax, how to make such a function.

A: It looks like you want a function like
BiFunction<BiConsumer<Output,Value>, Value, Output> f = (func, val) -> {
    Output o = new Output();
    func.accept(o, val);
    return o;
};

which you can invoke like
f.apply(Output::setAAA, val);
f.apply(Output::setBBB, val);

A: I'm not quite sure what you mean with "method reference", but I think you want something like this:
BiFunction<Integer, Value, Output> f3 = (ref, val> -> {
    switch(ref) {
        case 1: return f1.apply(value);
        case 2: return f2.apply(value);
        default: throw new IllegalArgumentException("invalid index");
    }
}

You can replace the Integer with anything you'd like, as long as you also change the switch-statement, maybe use an if/else.


text:
Q: Requesting photo access from preview on iOS When opening images using presentPreviewAnimated: share menu contains "Save Image" option. It works fine if user gave access to photos before (and if user explicitly disabled access there's no such option at all), but otherwise app crashes. I can check permission before opening file, but it would be wrong if the user doesn't need to save it.
How can I check if user wants to save image and permission request is needed?

A: Solved by adding NSPhotoLibraryAddUsageDescription to plist, thanks to this post.


text:
Q: How to open iTerm2 version 3 in Forklift I am looking for a solution which can open iTerm2 version 3 as the default terminal. For iTerm2 version 2 there were multiple AppleScripts on the internet which worked well for opening the current Forklift dir in an iTerm tab.
In iTerm3 this no longer works, as the scripting changed slightly. I also don't know any possible way to debug what is wrong, as

*

*I cannot run the applescript file in standalone, as it depends on ForkLift variables.

*I don't see any place where ForkLift would log it's output. In Console at least I didn't find it.

A: The iTerm support has now been built in and can be selected in the settings.


text:
Q: SQL While que recorre una tabla Amigos estoy tratando de recorrer una tabla desde SQL pero por alguna razón no obtengo los datos de cada fila de mi tabla. Alguién me puede decir que estoy haciendo mal?

declare @count int = 0,
  @countb int = 1
set @count = (select count( * ) from stats_ddl)
while @countb <= @count
begin
declare @fechaMov varchar(50) = (select top(1) fecha + hora + importe from stats_ddl)
print 'fecha' + @fechaMov + ' ' + convert(varchar, @countb)
set @countb = @countb + 1
end

A: Amigo intenta hacer esto, debes clonar tu tabla en una tabla temporal e iterar:
DECLARE @count INT;

CREATE TABLE #stats_ddl(
    fecha DATETIME,
    hora TIME,
    importe DECIMAL
);

INSERT INTO #stats_ddl
SELECT * FROM stats_ddl

SELECT @count = COUNT(*) FROM #stats_ddl;

WHILE @count > 0
BEGIN
    DECLARE @fechaMov VARCHAR(50) = (SELECT TOP(1) fecha + hora + importe FROM #stats_ddl);
    PRINT 'fecha' + @fechaMov + ' ' + CONVERT(VARCHAR, @count);
    DELETE TOP (1) FROM #stats_ddl
    SELECT @count = COUNT(*) FROM #stats_ddl;
END

DROP TABLE #stats_ddl;


text:
Q: Joomla get content by ajax How to get joomla content using ajax? (I want to show content of specyfic page in popup), this is my code: (called by ajax)
$option = JRequest::getCmd('option');
    $view = JRequest::getCmd('view');
    if ($option=="com_content" && $view=="article") {
      $ids = explode(':',JRequest::getString('id'));
      $article_id = $ids[0];
      $article =& JTable::getInstance("content");
      $article->load($article_id);
      echo '<h2>'.$article->get("title").'</h2>';
      echo $article->get("introtext"); // and/or fulltext
    }

This works fine only for artilces, but the problem is when for example I want to show category, or component

A: Please see your if condition it checks if option is equal to com_content & view is equal to article only. If view contains category it won't work. So add the conditions in if statement so that your code gets executed.
for category you need to add view=category & like for other components as well.


text:
Q: c# wpf datagrid add row I need to insert values in a table that have different columns from time to time. The columns and row data are updated from MySql. Each row values are in single MySql cells with the following format:
ColumnName{Delimiter}Value{BigDelimiter}Column2Name{Delimiter}Value2...

So I split the cell strings to get the column header and value, as the user can rearrange columns, modify, delete or insert new ones. I searched for a solution, though I get nothing but empty rows:
    private void GetDataTableValues()
    {
        if (dtData.Value != null)
        {
            try
            {
                LoadFields();
                dgwDataMain.Items.Clear();
                dgwDataMain.Columns.Clear();
                foreach (Fields field in fields)
                {
                    DataGridTextColumn column = new DataGridTextColumn();
                    column.Header = field.name;
                    column.Binding = new Binding(field.name);
                    dgwDataMain.Columns.Add(column);
                }

                if (connection.State == System.Data.ConnectionState.Broken || connection.State == System.Data.ConnectionState.Closed)
                    connection.Open();

                command.Parameters.Clear();
                DateTime dt = dtData.Value ?? DateTime.Now;
                command.Parameters.Add("@date", MySqlDbType.Date, 50).Value = dt.ToString("yyyy-MM-dd");
                command.CommandText = "SELECT value,team FROM sessions WHERE date=@date";

                List<string> teams = new List<string>();
                foreach (Control ctrl in panDataFilter.Children)
                    if ((ctrl as CheckBox).IsChecked == true)
                        teams.Add(Convert.ToString((ctrl as CheckBox).Content));

                using (MySqlDataReader reader = command.ExecuteReader())
                {

                    while (reader.Read())
                    {
                        bool v = false;
                        if (teams.Contains(reader[1].ToString()) || teams.Count == 0)
                            v = true;
                        if (v)
                        {
                            DatabaseObject obj = new DatabaseObject();
                            List<string> str2 = new List<string>(reader[0].ToString().Split(new string[] { "</s&p>" }, StringSplitOptions.None).ToList());
                            obj.Items = new List<string>(str2.Count);
                            foreach (string str in str2)
                            {
                                List<string> item = new List<string>(str.Split(new string[] { "<&p>" }, StringSplitOptions.None).ToList());
                                int index = dgwDataMain.Columns.Single(c => c.Header.ToString() == item[0].ToString()).DisplayIndex;
                                obj.Items.Insert(index, item[1].ToString());
                            }
                            dgwDataMain.Items.Add(obj);
                        }
                    }
                }
            }
            catch (MySqlException ex)
            {
                MessageBox.Show(ex.ErrorCode.ToString() + ": " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
        }
    }

    public class DatabaseObject
    {
        public List<string> Items = new List<string>();
    }

A: Please use Observablecollection to bind the data grid. By using observablecollection easily you can add or delete item and not required to reset the data source of  data grid.
Sample Code:

observableCollection myClass = new
  observableCollection();
      myClass.add(Class)

A: to delete extra row from datagrid is, just make property...
Canuseraddrows="false";


text:
Q: What happens when I ping 127.0.0.1 It might seem a little stupid but I'm curious to know what really happens when I ping the loop-back IP address, ping 127.0.0.1.
Does OS treat it in a special way?

A: The 127.0.0.0/8 is a CDIR netblock reserved by IANA and it's called Loopback. This traffic is routed by kernel to a a special network adapter called loopback adapter. It never hits the OSI Model Layer 1, as any local traffic.
For most all OS data travels across the network kernel services until the IP stack. At this point the data will be send back without hitting the physical layer and the real NIC hardware.
This work is done almost entirely from the host system's CPU, which means a great simplification compared to the physical network transmission. Modern OS kernels are able to detect the loopback traffic and grant speeds over than fastest nowadays physical adapters (> 50GBps).

A: I do not think that OS treats this IP any different from the rest except that it points back to local machine.
http://www.rolo.org/127-0-0-1.html


text:
Q: git diff fatal: ambiguous argument unknown revision or path not in working tree I am running git fetch origin in my production code and then am trying to a Git diff with my current branch with origin/master. I am facing this error while running the command:

fatal: ambiguous argument unknown revision or path not in working tree

Please find below the command used and the actual error.
Command tried:
git fetch origin
git diff --name only release/test origin/master

Expected output:
git diff should work

Actual output:
[localhost] local: git diff --name-only release/test origin/master |   ambiguous argument 'release/test': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'

How can we correct the issue with my Git diff command?

A: You need to make sure you don't have:

*

*Either a path within your Git repository folder which would match the branch name, that is a folder release/test

*or, as noted by philant, a branch name matching the path of the file being diffed,

*or a tag matching the branch name: git tag -l (Listing release/test)

Adding -- would make sure the two branch names are interpreted as literals, not options. In this case (git diff), as paths, not commits or other git diff options.
git diff --name-only release/test origin/master --

In your case, this should fail unless you actually have paths/folders named release/test and origin/master.
So git diff [<options>] <commit> <commit> remains the correct syntax.
You only need to make sure there is no path or tag already named like one of those two commits.

A: The solution was first to checkout the branch, and then git diff commands would work.
$ git diff --name-only master...release/v1.1

fatal: ambiguous argument 'master...release/v1.1': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'

$ git diff --name-only master release/v1.1 --

fatal: bad revision 'release/v1.1'

$ git checkout release/v1.1

Switched to a new branch 'release/v1.1'
Branch 'release/v1.1' set up to track remote branch 'release/v1.1' from 'origin'.

$ git diff --name-only master release/v1.1

foo
bar


text:
Q: Protocol Conformance Check How can I perform conformance check against protocol with AssociatedType. Xcode shows error:

Protocol 'MyListener' can only be used as a generic constraint because
  it has Self or associated type requirements

My ultimate goal is to extract "MyListener.section" from an array of weakObjects, where the handler matches the function argument.
Note. The NSPointerArray of weakObjects is suppose to capture different types of MyListeners.
public class MyHandler<O,E> {
    var source = [O]()
    var dest = [E]()
}
public protocol MyListener:class {
    var section: Int {get}
    associatedtype O
    associatedtype E
    var handler: MyHandler<O,E>? { get }
}

public class MyAnnouncer {
    private let mapWeakObjects: NSPointerArray = NSPointerArray.weakObjects()
    public func add<L: MyListener>(listener: L) {
        let pointer = Unmanaged.passUnretained(listener).toOpaque()
        mapWeakObjects.addPointer(pointer)
    }
    public func search<O, E> (h:MyHandler<O,E>) -> [Int] {
        _ = mapWeakObjects.allObjects.filter { listener in
            if listener is MyListener { // Compilation failed
            }
            if let _ = listener as? MyListener { //Compilation error
            }
            if listener is MyListener.Type { //Compilation failed
            }
        }
        return [] // ultimate goal is to extract corresponding [MyListener.section].
    }
}

A: Unfortunately, Swift doesn't support protocols with AssociatedType to conformance.
You should try to use Type Erasure. One of the way is to implement type erasure by creating new AnyType class.
Here is another way to release type erasure (example from the internet)
protocol SpecialValue { /* some code*/ }

protocol TypeErasedSpecialController {
  var typeErasedCurrentValue: SpecialValue? { get }
}

protocol SpecialController : TypeErasedSpecialController {
  associatedtype SpecialValueType : SpecialValue
  var currentValue: SpecialValueType? { get }
}

extension SpecialController {
  var typeErasedCurrentValue: SpecialValue? { return currentValue }
}

extension String : SpecialValue {}

struct S : SpecialController {
  var currentValue: String?
}

var x: Any = S(currentValue: "Hello World!")
if let sc = x as? TypeErasedSpecialController { // Now we can perform conformance
  print(sc.typeErasedCurrentValue)
}


text:
Q: Beautiful triangle problem Circle, inscribed in $ABC$, touches $BC, CA, AB$ in points $A', B', C'$. $AA' BB', CC'$ intersect at $G$. Circumcircle of $GA'B'$ crosses the second time lines $AC$ and $BC$ at $C_A$ and $C_B$. Points $ A_B, A_C, B_C,B_A, C_A, C_B$ are concyclic.

Looks straightforward,  but I'm struggling to get something out of the given. I tried proving that two points and one line and two points and some other are concyclic and then combining three similar resul together, but not much yet.

A: This is a coordinate-based approach, making heavy use of tools from projective geometry.
Without loss of generality, you can choose the coordinate system in such a way that the inscribed circle is the unit circle. On that you can use a rational parametrization, i.e. choose $a,b,c\in\mathbb R$ such that $A'=(1-a^2,2a)/(1+a^2)$ and likewise for $B'$ and $C'$. Or, even better, use homogeneous coordinates for these:
$$
A'=\begin{pmatrix}1-a^2\\2a\\1+a^2\end{pmatrix}\qquad
B'=\begin{pmatrix}1-b^2\\2b\\1+b^2\end{pmatrix}\qquad
C'=\begin{pmatrix}1-c^2\\2c\\1+c^2\end{pmatrix}
$$
From that, everything else follows. The tangent at a point on the circle is simply its polar line, which you get by multiplication with the matrix of the unit circle, namely the matrix
$$U=\begin{pmatrix}1&0&0\\0&1&0\\0&0&-1\end{pmatrix}$$
You can join points using lines, and intersect lines to obtain points, simply by computing the cross product.
$$A=(U\cdot B')\times(U\cdot C')$$
and likewise for $B$ and $C$, the other two corners of the triangle. Then you get
$$G=(A\times A')\times(B\times B')$$
A circle through three points can be constructed as a conic through these points and the special points $I=(1,i,0)$ and $J=(1,-i,0)$ which have complex coordinates and lie on the line at infinity. Since they also lie on every circle, they are often called the ideal circle points. So we construct the matrix of the circle $\bigcirc GA'B'$ in several steps:
\begin{align*}
M_1 &= (A'\times I)\cdot(B'\times J)^T &
M_2 &= (A'\times J)\cdot(B'\times I)^T \\
M_3 &= M_1 + M_1^T & M_4 &= M_2 + M_2^T \\
M_5 &= (G\cdot M_3\cdot G)M_4 - (G\cdot M_4\cdot G)M_3 &
M_C &= iM_5
\end{align*}
$M_1$ and $M_2$ describe degenerate conics through $A',B',I,J$. $M_3$ and $M_4$ are the same except using symmetric matrices. $M_5$ is a linear combination which also passes through $G$, so that's the circle. $M_C$ is a real matrix describing the same circle, avoiding all the purely imaginary entries of $M_5$.
To intersect that circle with $AC$ (which is the same line as $B'C$) you compute
$$C_A=(C^T\cdot M_C\cdot C)B'-2(B'^T\cdot M_C\cdot C)C$$
This is still a homogeneous coordinate vector of a point, e.g. some $(x,y,z)$. Dehomogenize that to $(x/z, y/z)$ then take the norm of that:
\begin{align*}
\lVert C_A\rVert =& \frac{\sqrt s}{t} \\
s =& \phantom+ (a^4b^4 + a^4c^4 + b^4c^4) \\&
- 2\,abc\,(a^3b^2 + a^2b^3 + a^3c^2 + b^3c^2 + a^2c^3 + b^2c^3) \\&
+ 3\,a^2b^2c^2\,(a^2 + b^2 + c^2) \\&
+ 11\,(a^4b^2 + a^2b^4 + a^4c^2 + b^4c^2 + a^2c^4 + b^2c^4) \\&
+ 16\,abc\,(a^2b + ab^2 + a^2c + b^2c + ac^2 + bc^2) \\&
- 20\,(a^3b^3 + a^3c^3 + b^3c^3) \\&
- 20\,abc\,(a^3 + b^3 + c^3) \\&
- 42\,a^2b^2c^2 \\&
- 2\,(a^3b + ab^3 + a^3c + b^3c + ac^3 + bc^3) \\&
+ 3\,(a^2b^2 + a^2c^2 + b^2c^2) \\&
+ (a^4 + b^4 + c^4) \\
t =&\phantom+ (a^2 + b^2 + c^2) \\&
- (ab + ac + bc) \\&
+ (a^2b^2 + a^2c^2 + b^2c^2) \\&
- abc\,(a + b + c)
\end{align*}
This is the radius for one of the six points of your claimed circle. The other five can be obtained using the same computation, starting from a permutation of the three initial points. So the result will be the same except for a permutation of the parameters $a,b,c$. But the formula stated above is invariant under such a permutation, therefore all six points lie on a circle as claimed. Its center is the center of the coordinate system, i.e. the incenter of the triangle. Its radius will be the fraction described by the lengthy expressions stated above.

A: Consider $A$'s relationship with various circles.
Since $B^\prime$ and $C^\prime$ are points of tangency of lines through $A$ with the incircle, we have
$$|AB^\prime| = |AC^\prime| \qquad (\star)$$
Further, by the "Power of a Point" Theorem,
$$|AA_B||AC^\prime| = \operatorname{pow}(A\;,\;\bigcirc GB^\prime C^\prime) = |AA_C||AB^\prime|$$
Also,
$$|AB_A||AC^\prime| = \operatorname{pow}(A\;,\;\bigcirc A^\prime G C^\prime) = |AG||AA^\prime| = \operatorname{pow}(A\;,\;\bigcirc A^\prime B^\prime G) = |AC_A||AB^\prime|$$
Together with $(\star)$, these imply
$$|AA_B| = |AA_C| \qquad\text{and}\qquad |AB_A| = |AC_A|$$
This makes $\square A_B A_C B_A C_A$ an isosceles trapezoid, whose bases, $A_BA_C$ and $B_AC_A$, have the bisector of $\angle A$ as their common perpendicular bisector. The incenter, $I$, of $\triangle ABC$ lies on that bisector, so we can write
$$|IA_B| = |IA_C| \qquad\text{and}\qquad |IB_A| = |IC_A|$$
Identical arguments considering points $B$ and $C$ lead to corresponding relations
$$|IB_C| = |IB_A| \qquad |IC_B| = |IA_B| \qquad\text{and}\qquad|IC_A|=|IC_B|\qquad|IA_C|=|IB_C|$$
Necessarily, $I$ is equidistant from all six points $A_B$, $A_C$, $B_C$, $B_A$, $C_A$, $C_B$. $\square$


text:
Q: stuck on "starting your workflow run" on Github Actions I wanted to test "github action" feature but it is not starting and its is stuck.It just says "Starting your workflow run..."
Is there something wrong in my build.yml file
This is my build.yml file:
name: CI

on:
  pull_request:
    branches:
      - master

  workflow_dispatch:

env:
  POSTGRESQL_VERSION: 13.1
  POSTGRESQL_DB: students_info
  POSTGRESQL_USER: postgres
  POSTGRESQL_PASSWORD: password
  JAVA_VERSION: 1.15

jobs:
  build:
    runs-on: ubuntu-16.04
    services:
      postgres:
        image: postgres:13.1
        env:
          POSTGRES_DB: ${{ env.POSTGRESQL_DB }}
          POSTGRES_USER: ${{ env.POSTGRESQL_USER }}
          POSTGRES_PASSWORD: ${{ env.POSTGRESQL_PASSWORD }}
        ports:
          - 5432:5432
        options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-java@v1.4.3
        with:
          java-version: ${{ env.JAVA_VERSION }}
      - name: Maven Clean Package
        run: |
          ./mvnw --no-transfer-progress clean package -P build-frontend

PS:I have tried with ubuntu-latest as well

A: There is currently a problem with GitHub Actions:
https://www.githubstatus.com/incidents/zbpwygxwb3gw


text:
Q: find first pair element (int) on a vector and get second (struct) SOLVED. see below
I'm running a service like this:
int pgsService::startService(int sockfd){
    listen(sockfd,5);
    int c = accept(sockfd, (struct sockaddr *)&cli_addr,&clilen);
    clients.push_back(std::make_pair(sockfd,cli_addr));
    std::cout << "Accepted:" << c << "\tIP:" << inet_ntoa(cli_addr.sin_addr) << std::endl;
    return c;
}

Constructor:
pgsService::pgsService(int *fd,int port) {
    bzero((char *) &serv_addr, sizeof(serv_addr));
    *fd = socket(AF_INET,SOCK_STREAM,0);
    assert(*fd>0);
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = INADDR_ANY;
    serv_addr.sin_port=htons(port);
    bind(*fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
    clilen = sizeof(cli_addr);
}

private members:
private:
        struct sockaddr_in serv_addr, cli_addr;
        int sfd;
        socklen_t clilen;
        std::vector<std::pair<int, struct sockaddr_in> > clients;
};

CompareFirst struct:
struct CompareFirst
{
  CompareFirst(int val) : val_(val) {}
  bool operator()(const std::pair<int,struct sockaddr_in>& elem) const {
    return val_ == elem.first;
  }
  private:
    int val_;
};

Which starts an instance of a service binding a local port.
This port will serve to chat-like service in a .NET client side application but the server side I'm doing all in C++.
So, after I pgsService server = pgsService(&sockfd,port); I call int client = server.startService(sockfd);
Described above.
The constructor is only binding at setting the structs etc to the socket server.
When there is a connection:
testing code only:
write(client,hello.c_str(),hello.length());
void *buf = malloc(512);
memset(buf,0,512);
read(client,buf,512);
std::cout << "From:" << inet_ntoa(server.getClientInfo(client).sin_addr) << ":"<< server.getClientInfo(client).sin_port << "\t - " << (char*)buf << std::endl;
free(buf);
shutdown(client,2);
exit(0);

It outputs like:
$ ./pgs_service
Accepted:4      IP:127.0.0.1
GETING:0.0.0.0
GETING:0.0.0.0
From:0.0.0.0:0   - LOL

I'm trying to hold the clients data information in a vector here:
clients.push_back(std::make_pair(sockfd,cli_addr));

The getClientInfo method is:
struct sockaddr_in pgsService:: getClientInfo(int client){
    std::vector< std::pair <int, struct sockaddr_in> >::iterator it = std::find_if(clients.begin(),clients.end(),CompareFirst(client));
    std::cout << "GETING:" << inet_ntoa(it->second.sin_addr) << std::endl;
    return (it->second);
}

So I store in the clients vector that accepts another object of type std::pair.
I push into stack and when I need to get the struct I simply call getClientInfo and it finds using find_if.
The problem is that I believe that the return value is not the actual struct because it sometimes returns some integers like: 83.0.0.0 and then 0.0.0.0 and then 30.0.0.0 . Seems I'm accessing regions of memory I shouldn't and Luckily the program isn't crashing.
I'm doing something wrong? Where? I think it is the way I'm push into the vector OR the way I'm getting the data back.
SOLUTION: When I push_back I make "make_pair" with sockfd and I shouldn't. I must push 'c'.

A: I am assuming quite a few things here.

*

*You have CompareFirst defined somewhere.

*Between subsequent calls
to startService I am assuming you are mem-setting cli_addr to 0.

I don't see anything fundamentally wrong with your use of the vector and the std::pair construct in terms of populating the vector after making a pair. The trick however maybe ensuring semantic correctness. Can you check whether cli_addr is in-fact populated correctly after accept returns?
Also, instead of pushing the server fd, shouldn't you be pushing the fd returned by accept - in your case c? IMO, a better way to accomplish what you are doing is using an associative data-structure like a map or an un-ordered map. Also, for better design, you should evaluate mechanisms such as select to handle i/o since your accept calls are essentially going to block.
Yet another issue is not checking the return value of the find_if. You should always compare the iterator to clients.end() in order to ensure it is a valid iterator.
Hope this helps.


text:
Q: Mayer-Vietoris Sequence with Pairs Applied to (Oriented) Connected Sum of Manifolds I was trying to figure out why the (oriented) connect sum of two oriented manifolds should be oriented. Here the oriented connect sum $M_1\# M_2$ of two $n$-manifolds $M_1$ and $M_2$ is taken to be the manifold gotten by gluing the two manifolds with interior of closed disks $B_1^0$ and $B_2^0$ removed via an orientation reversing homeomorphism. An $n$-manifold $M$ is orientable if its top homology group relative to its boundary $H_n(M, \partial M)$ is non-trivial, in fact, isomorphic to $\mathbb{Z}$. An orientation is a choice of the generators of this group (c.f. Knots and Links by Rolfsen).
Let's take $M_j$ to be manifolds without boundary to make it easier. I approached this problem by applying Mayer-Vietoris sequence with pairs. On P152 of Hatcher's Algebraic Topology, it says "If one has
a pair of spaces $(X, Y ) = (A \cup B, C \cup D)$ with $C \subset A$ and $D \subset B$ , such that $X$ is the
union of the interiors of $A$ and $B$, and $Y$ is the union of the interiors of $C$ and $D$,
then there is a relative Mayer–Vietoris sequence"
\begin{equation}
\cdots \rightarrow H_n(A\cap B, C\cap D) \xrightarrow{\Phi} H_n(A, C) \oplus H_n(B, D)\xrightarrow{\Psi} H_n(X, Y) \xrightarrow{\partial}\cdots
\end{equation}
I applied this with $A = M_1\setminus B_1, B = M_2\setminus B_2, C = \partial B_1, D = \partial B_2$. Note that both $M_i$ should be enlarged a bit such that the interior is a cover of $M_1\# M_2$. I got
\begin{equation}
0\rightarrow H_n(S^{n-1}\times I)\xrightarrow{\Phi_n} H_n(M_1\setminus B_1, \partial B_1)\oplus H_n(M_2\setminus B_2, \partial B_2)\xrightarrow{\Psi_n} H_n(M_1\# M_2)\xrightarrow{\partial_n} H_{n-1}(S^{n-1}\times I)\xrightarrow{\Phi_{n-1}} H_{n-1}(M_1\setminus B_1, \partial B_1)\oplus H_{n-1}(M_2\setminus B_2, \partial B_2)\rightarrow\cdots,
\end{equation}
by the fact that $(M_1\setminus B_1)\cap(M_2\setminus B_2) \cong S^{n-1}\times I$, $\partial B_1 \cap \partial B_2 = \emptyset$ and interior of $\partial B_1 \cup \partial B_2$ is also empty.
Now consider $\Phi_{n-1}$. This maps the generator of $H_{n-1}(S^{n-1}\times I)$ to the generators of $H_{n-1}(\partial B_j)$, so $\Phi_{n-1} = 0$. Therefore by exactness, $\partial_n$ is surjective. Since $H_{n-1}(S^{n-1}\times I) \cong \mathbb{Z}$, $H_n(M_1\# M_2)\not= 0$, and in fact, $H_n(M_1\# M_2) \cong \mathbb{Z}$. Since we do subtraction for the map $\Psi_n$ if $\Phi_n$ is taken to be positive embeddings in both components, the gluing homeomorphism should be orientation reversing.
Up to here everything was good, until I observed that I have turned the above sequence to be
\begin{equation}
0\rightarrow 0 \rightarrow \mathbb{Z}\oplus \mathbb{Z}\xrightarrow{\Psi_n} \mathbb{Z}\xrightarrow{\cong} \mathbb{Z}\xrightarrow{0} \cdots.
\end{equation}
Then, $\Phi_n$ will be an injective homomorphism by exactness, which is impossible.
My first question is, what's the problem above? Did I apply Mayer-Vietoris with pairs correctly?
If we use homology instead of relative homology for the Mayer-Vietoris, the sequence should be
\begin{equation}
0\rightarrow 0 \rightarrow 0 \oplus 0\xrightarrow{\Psi_n} \mathbb{Z}\xrightarrow{\cong} \mathbb{Z}\xrightarrow{0} \cdots.
\end{equation}
Now everything makes sense. However, I am wondering if there is a rigorous but elementary way to see $H_n(M_j\setminus B_j) = 0$. On one hand, this is intuitively true by triangulation, but it's hard to make it rigorous. On the other hand, using Lefschetz Duality seems to be an overkill.
Any help would be greatly appreciated!


text:
Q: Preventing scroll event when clicking an anchor bookmark Clicking the anchor bookmark triggers a scroll event.
How to trigger the callback only when the user scroll happens and not when clicking the bookmark links?

Note: a poorly worded question with an answer was closed, but I believe it could still be useful to the community because I didn't see a similar question answered on StackOverflow

A: Shomz solution relies on the anchor element being in the scrolling context of the document. If the element is not in the scrolling context of the document the offset check may fail:

    anchor

I think there are other solutions as well:
debounce
Detect when an anchor link was clicked (hashchange/onclick) and debounce the scroll event.
var debounce = false;
window.addEventListener("hashchange", function () { // also add one for `onclick`
    debounce = true;
    setTimeout(function () {
        debounce = false;
    }, 1);
});
window.addEventListener("scroll", function () {
    if (debounce) {
        return;
    }
    // .. handle scroll
});

onwheel
Depending on why exactly you don't want to trigger your scroll handler when you navigate to an anchor, you could consider attaching it only to the onwheel event. This means that other means of scrolling (touch, anchors, arrow keys, Page Down, etc.) wont trigger your handler.

A: While it's not possible to prevent the actual event from firing (because it's a part of the browser code and it works like that by design), what can be done is to extend your check conditions - in addition to $(window).scrollTop() > 0 that was originally there, you can also check whether there is a hash in the window location, and if there is, check if the scrolled amount is different from the vertical offset of the element referenced by the URL hash.
Something like this:
$(window).scroll(function(){
    if($(window).scrollTop() > 0 &&            // if it's scrolled and
       (!window.location.hash ||               // if there's no hash or
       $(window.location.hash).offset() &&     // there is, but the scroll is elsewhere
       $(window.location.hash).offset().top != $(window).scrollTop())
   ) {
        alert('scroll');                       // trigger the callback
    }
});

Live code:

$(window).scroll(function(){
    if($(window).scrollTop() > 0 &&
       ($('#c:checked').length == 0 ||
         (!window.location.hash ||
         $(window.location.hash).offset() &&
         $(window.location.hash).offset().top != $(window).scrollTop()
         )
       )
     ) {
        $('div').addClass('on');
        setTimeout(function(){
          $('div').removeClass('on');
        }, 1000)
    }
});
p {margin: 500px 0;}
div {position: fixed; top: 0; right: 0; opacity: 0.1; transition: all .2s linear; padding: 4px 8px}
div.on {opacity: 1; background: #cfc;}

<input id="c" type="checkbox" checked="checked">Prevent scroll callback on link clicks

Link to the anchor below

Anchor here

Scroll triggered


text:
Q: Stable marriage with contracts: is it known? Consider the following generalization of the classical Stable Marriage Problem. The rough idea is that instead of merely specifying who marries whom, a matching now chooses a set of "marriage contracts" (out of a given set, which may be large since a man and a woman can choose between several different contracts for marrying each other); correspondingly the men and the women rank not their potential partners but rather the potential contracts available to them (e.g., a given man $m$ can prefer marrying a woman $w_1$ via a contract $c_1$ to marrying a woman $w_2$ via a contract $c_2$, but at the same time prefer marrying $w_2$ via $c_2$ to marrying $w_1$ via a different contract $c_3$). In detail, the generalized problem is stated as follows:

Contracted Stable Marriage Problem. Suppose that we have a population of $k$ men and $k$ women
  (for some $k \in \mathbb{N}$).
  Assume furthermore that a finite set $C$ of "contracts" is given.
  Each contract involves exactly one man and exactly
  one woman.
  (Think of the contracts as marriage contracts, each prepared for some man and some woman, but not signed.)
Assume that, for each pair $\left(m, w\right)$ consisting of a man $m$
  and a woman $w$, there is at least one contract
  that involves $m$ and $w$.
Suppose that each person has a preference list of all the
  contracts that involve him/her; i.e., he/she ranks
  all contracts that involve him/her in the order of
  preferability.
  (No ties are allowed.)
A matching shall mean a subset $K$ of $C$ such
  that each man is involved in exactly one contract in $K$,
  and such that each woman is involved in exactly one
  contract in $K$.
  Thus, visually speaking, a matching is a way to marry off
  all $k$ men and all $k$ women to each other (in the
  classical meaning of the word -- i.e., heterosexual and
  monogamous)
  by having them sign some of the contracts in $C$
  (of course, each person signs exactly one contract).
If $p$ is a person and $K$ is a matching, then the
  unique contract $c \in K$ that involves $p$ will be called
  the $K$-marriage contract of $p$.
If $K$ is a matching and $c \in C$ is a contract, then
  the contract $c$ is said to be rogue (for $K$) if

*

*this contract $c$ is not in $K$,

*the man involved in $c$ prefers $c$ to his
     $K$-marriage contract, and

*the woman involved in $c$ prefers $c$ to her
     $K$-marriage contract.
Thus, roughly speaking, a rogue contract is a contract
  $c$ that has not been signed in the matching $K$, but that
  would make both persons involved in $c$ happier than
  whatever contracts they did sign in $K$.
A matching $K$ is called stable if there exist
  no rogue contracts for $K$.
The problem now asks you to find a stable matching.

Theorem. A stable matching always exists.
The proof of the above theorem is a fairly straightforward modification of the classical proof of the Gale-Shapley Stable Marriage Theorem (which is discussed in several places, the most readable one perhaps being Section 6.4 of Eric Lehman, F. Thomson Leighton, Albert R. Meyer, Mathematics for Computer Science, revised 16th April 2017). In generalizing it, I was motivated by an elegant solution of a graph-theoretical exercise suggested by Alex Postnikov (Exercise 3 on UMN Spring 2017 Math 5707 midterm #2; see its Second Solution for Postnikov's argument).
But I am left wondering: Is the above Theorem, and the problem it answers, known? I suspect it has further applications, which the (standard) Stable Marriage Theorem is a tad too narrow to handle, as the latter treats a marriage as uniquely determined by the two partners involved.
One thing the added generality seems well-equipped to model is "matching with dowry"; i.e., a marriage should come with a payment from one partner to the other, and the preferability of the marriage depends on this payment. (At least if the set of all possible payments is finite, this is easily obtained as a particular case of the Contracted Stable Marriage Problem by formulating a contract for each possible payment.) This rather unromantic modification appears suited for various real-life applications of the Stable Marriage Problem, given that few of them involve actual marriages. At least this case is probably known?

A: There is a humongous literature on "matching with contracts", starting with:

Hatfield, John William, and Paul R. Milgrom. "Matching with
  contracts." The American Economic Review 95.4 (2005): 913-935.

The existence result of that paper is actually a special case of the earlier, even up to the basic proof approach (via Tarski's fixed point theorem).

Fleiner, Tamás. "A fixed-point approach to stable matchings and some
  applications." Mathematics of Operations Research 28.1 (2003):
  103-126.

It was also shown in

Echenique, Federico. "Contracts versus salaries in matching." The
  American Economic Review 102.1 (2012): 594-601.

that the model of Hatfield and Milgrom is equivalent to the model in

Kelso Jr, Alexander S., and Vincent P. Crawford. "Job matching,
  coalition formation, and gross substitutes." Econometrica: Journal of
  the Econometric Society (1982): 1483-1504.

There exists also generalizations that are genuinely new and the matching with contracts model is pretty much the state of the art of stable matching theory in economics. There is also a large and even older literature on matching with transferable utility or imperfect transferable utility, which covers the "dowry case". This material can even be found in the classic textbook

Roth, Alvin E., and Marilda A. Oliveira Sotomayor. "Two-sided
  matching, volume 18 of Econometric Society Monographs." (1990),

where you can find further references.


text:
Q: Error: Non-exhaustive patterns in Haskell I have some code that deals with a list of lists (that represents a matrix). Each cell is an N or a B. I want to represent the matrix with the number of Ns for each line. For example: [[B,B,N],[N,N,N]] is represented by [1,3].
Here's my code:
data Case = B|N deriving (Show, Eq)
type Grille =[[Case]]

g0,g1 :: Grille
g0 = [[B,B,B,B,B,B,N],[B,B,N,B,N,B,B],[N,B,N,N,N,N,N],[B,B,B,N,N,B,N],[N,N,N,B,B,B,B],[B,B,B,N,N,B,N]]
g1 = [[B,B,B,B,B,B,B],[B,B,N,N,N,B,B],[B,B,N,N,N,N,N],[B,B,B,N,N,N,N],[N,N,N,B,B,B,B],[B,B,B,N,B,B,B]]

projH :: Grille -> [Int]
projH [[]] = []
projH (x:xg) = testCase(x) ++ projH(xg)

testCase :: [Case] -> [Int]dans une ligne
testCase [] = [0]
testCase (x:xs)
    | x == N = [head(testCase(xs))+1]
    | otherwise = testCase(xs)

The problem is in the function projH, I'm obviously missing a pattern, but I do handle the case with [[],...] with the testCase function and the [[]] case. I don't know why it throws me this error:
*Main> projH g0
[1,2,6,3,3,3*** Exception: devoir.hs:(17,1)-(18,39): Non-exhaustive patterns in function projH

A: projH [] = []

instead of your
projH [[]] = []

As the case you wrote is already handled by the other statement by assigning x = [] and xg = []


text:
Q: Terrible Performance with WCF and certificates (mutual authentication) Guys / Gals we are having terrible performance with our website that uses WCF as the application later. We are using message level security and certificates (mutual authentication). We are caching the channel factory in the application object:
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)

        Dim loChannelFactor As New ChannelFactory(Of OurReference.IWCFChannel)("ClientEndpoint")
        loChannelFactor.Open()
        Application.Add("ChannelFactory", loChannelFactor)
End Sub

In every page that we need data we do the following:
Dim Proxy = DirectCast(voWebApp("ChannelFactory"), ChannelFactory(Of OurInfoReference.IOurInfoChannel)).CreateChannel

Proxy.DataCall()

If roWCFService IsNot Nothing Then
        CType(roWCFService, ICommunicationObject).Close()
        roWCFService = Nothing
End If

Also i have set establishsecuritycontext = true.
We are not wanting to cache the proxy because of having to mess with a faulted proxy state. As far as i know caching the channel stack should be enough anyways. When i turn on tracking i'm seeing a bunch of SCT commands instead of just for the first call like i would expect. Does anyone know whats going on. Are we caching the channel factory incorrectly?
thanks,
Ncage

A: Looks like you could solve it using a certificate from a ceritificate authority:
"MakeCert is a tool provided by Microsoft to create test certificates that can be used during the development of a product (For developing and testing purposes only). These certificates have also performance problems, certain cryptographic operations may perform slowly when they are used. Certificates issued from a true Certificate Authority do not have this problem, and it is a know issue."
http://weblogs.asp.net/cibrax/archive/2006/08/08/Creating-X509-Certificates-for-WSE-or-WCF.aspx
Edit: May be the extra activity is due to initial handshake when creating of a session. WCF default is per call, that is a new session is created for each call. You could try marking your contract with:
[ServiceContract(Session = true)]
That may maintain the session and avoid the initial handshake.

A: I remember a similar issue however it was a good 18 months ago. I found this whilst having a quick look for how i resolved the issue. It may help, I will edit my response when I find what I was looking for!

A: The additional SCT/RST calls are establishing the security context. If you recreate the proxy on each call, a security context is unneccesary overhead. Turn it off.
The way you use the factory is fine. However, your error handling and closing of the proxy is not. Make sure that you close or abort the proxy in any case. Check msdn for the recommended pattern.
Also can you provide some figures about how bad performance is?


text:
Q: Scrum : Different Product owner and Project Manager I have created a short document of two authors : Ken Swchaber and Jeff Sutherland. At definition in this document about Product Owner:

The Product Owner is the sole person responsible for managing the
  Product Backlog

I see that Product owner is very like to Project  Manager in normal software development process.
So, what does a real difference, or just the same.

A: The Product Owner and a Project Manager are quite different.
On a traditional project, a Project Manager, as the title implies, manages a project.
However, on a Scrum project, the Development Team manages their own work.
The Product Owner, while responsible for maximizing the value of the product and the work of the Development Team, is the sole person responsible for managing the Product Backlog.
Product Backlog Management includes:

*

*Clearly expressing Product Backlog items;

*Ordering the items in the Product Backlog to best achieve goals and missions;

*Ensuring the value of the work the Development Team performs;

*Ensuring that the Product Backlog is visible, transparent, and clear to all, and shows
what the Scrum Team will work on next;

*Ensuring the Development Team understands items in the Product Backlog to the level needed.

Hope that helps. More details available in this article on the need for Product Owners

A: The difference is subtle, because we tend to infer a lot from the phrase "manage the backlog".
While a PM is often responsible for coordinating HOW the initiative should be accomplished, the Product Owner is responsible for understanding WHAT the product show do and works with the team to make sure this is reflected in the list of items (often described in business terms as features) called the Product Backlog.
In Scrum, the Development Team (composed of all skills needed to produce a complete increment in an iteration) is responsible for determining HOW to accomplish the items selected for completion in an iteration.

A: I think you ask this because you don't understand so much about agile.
Project Manager : he decides EVERYTHING, and tester, developers... often don't talk together, they must talk with project manager, and project manager will give this idea to other. for example : developer says : "I have add this feature A". and project manager will says to tester : "Hey, you should add a unit test for feature A", for example.
Product Owner : yeah, Project Manager can be a Product Owner, or, your customer can be product owner, too. It means : Product Owner : the person who can control the flow how the software is !
More over, product owner : he just looks how you work and give some talk to control the FLOW, not control your activity.