text:
Q: How to deal with bibliography items containing long URLs? A picture is worth a thousand macros:

I don't blame LaTeX for having difficulty in formatting this entry.
What can I do, however, to alleviate the effects and avoid the Word-like indentation?
A related question suggested by the site is How to get long \texttt sections to break which indeed produces a better aligned entry:

While I like the sane alignment, I'm not not very happy with the switch to a monospaced font (while it works in the regular text, in bibliographical entries it attracts too much attention and takes too much space).
Any other suggestions?
The entry for the above test bibitem is:
\begin{thebibliography}

\bibitem{anything-here}
"Lorem Ipsum Society,
\emph{dolor sit amet, consectetur}, May 2010
retrieved on Oct 16, 2010 from http://www.lorem-ipsum.com/whatever-here/about\%20something/here\%20takes/space\%20in\%20a\%20long/url\%20foobar.aspx

\end{thebibliography}

A: I think that \raggedright might be your friend here. You don't get justified entries, of course, but that can often look much better than having many underfull lines.
Before trying that, you can try to convince the various url handling packages to break lines. I have
\usepackage[hyphens]{url}
\ifpdf
\usepackage[breaklinks=true,pdfborder={0 0 0},bookmarksopen]{hyperref}
\else
\usepackage[pdfborder={0 0 0},bookmarksopen]{hyperref}
\usepackage[hyphenbreaks]{breakurl}
\fi

in one paper I wrote. I can't remember the rationale for using url and hyperref, but I must have had a reason at one point.
The microtype package might be able to help you get better breaks too.

A: Preamble:
\usepackage{url} % hyperref works too
\urlstyle{same}  % (sf also works, for something more subtle than tt)

Then insert urls as:
\url{http://www.example.com/~lev/my%20long%20url}

A: I had a similar problem which I solved using the following:
\usepackage{url}
\urlstyle{same}
\def\UrlBreaks{\do\/\do-}

I had in the URL too many - and /, but I guess you could make it work to break at % as well.


text:
Q: How to translate this conditional statement from Python to JS I'm making a little web-app based off some python code I ran a while ago, part of the python code involved this conditional statement
if poi in [r1.a.pos(), r1.b.pos()] and poi in [r2.a.pos(), r2.b.pos()]:
                        intersection_found = False
elif poi in [r1.a.pos(), r1.b.pos()]:

where poi and .pos() are tuples of the form (x, y)
I was wondering what the best way of doing this is in Javascript. Rightnow I have positions stored as an object in the form {x: 0, y:0}
Since you cant directly compare objects like this I was wondering how else I could do it, thank you for your help

redpajama_set_name: RedPajamaStackExchange


text:
Q: can i use two differnet variavbles in single this.state? I have two variables which i have to pass into "this.state" so that i can use 2 different state variables into two functionalities.
for example:
this state:{ data:'abc'},{series:100}
series: this.state.series
data:this.state.data
can someone help me how to sort it out!
Thanks in advance

A: You can do it this way:
this.setState({ data: 'abc', series: 100 })

then, you can get it with:
this.state.series
this.state.data

or in a cleaner way:
const { series, data } = this.state


text:
Q: Looping over grouped data using the nls function in R I have a grouped dataset. I have my data grouped by GaugeID. I have an nls function that I want to loop over each group and provide an output value.
library(tidyverse)
library(stats)

# sample of data (yearly), first column is gauge (grouping variable), year, then two formula inputs PETvP and ETvP

# A tibble: 10 x 4
   GaugeID  WATERYR  PETvP  ETvP
   <chr>      <dbl>  <dbl> <dbl>
 1 06892000    1981  0.854 0.754
 2 06892000    1982  0.798 0.708
 3 06892000    1983  1.12  0.856
 4 06892000    1984  0.905 0.720
 5 06892000    1985  0.721 0.618
 6 06892000    1986  0.717 0.625
 7 06892000    1987  0.930 0.783
 8 06892000    1988  1.57  0.945
 9 06892000    1989  1.15  0.739
10 06892000    1990  0.933 0.805
11 08171300    1981  0.854 0.754
12 08171300    1982  0.798 0.708
13 08171300    1983  1.12  0.856
14 08171300    1984  0.905 0.720
15 08171300    1985  0.721 0.618
16 08171300    1986  0.717 0.625
17 08171300    1987  0.930 0.783
18 08171300    1988  1.57  0.945
19 08171300    1989  1.15  0.739
20 08171300    1990  0.933 0.805

# attempted for loop
for (i in unique(yearly$GaugeID)) {
   myValue = nls(ETvP[i] ~ I(1 + PETvP[i] - (1 + PETvP[i]^(w))^(1/w)), data = yearly,
    start =  list(w = 2), trace = TRUE)
}

I get the following error
Error in model.frame.default(formula = ~ETvP + i + PETvP, data = yearly) :
  variable lengths differ (found for 'i')

I haven't found much information regarding looping with the nls function. Essentially, I am producing curves and need the value of the curve (w) to output for each gauge.
It works if I assign the formula to just one gauge (if I subset the data, i.e for the first gauge), but not when I try to use it on the entire data frame with grouped data.
For example, this works
# gaugeA
# A tibble: 10 x 4
   GaugeID  WATERYR  PETvP  ETvP
   <chr>      <dbl>  <dbl> <dbl>
 1 06892000    1981  0.854 0.754
 2 06892000    1982  0.798 0.708
 3 06892000    1983  1.12  0.856
 4 06892000    1984  0.905 0.720
 5 06892000    1985  0.721 0.618
 6 06892000    1986  0.717 0.625
 7 06892000    1987  0.930 0.783
 8 06892000    1988  1.57  0.945
 9 06892000    1989  1.15  0.739
10 06892000    1990  0.933 0.805

test = nls(ETvP ~ I(1 + PETvP - (1 + PETvP^(w))^(1/w)), data = gaugeA,
    start =  list(w = 2), trace = TRUE)

1.574756    (4.26e+00): par = (2)
0.2649549   (1.46e+00): par = (2.875457)
0.09466832  (3.32e-01): par = (3.59986)
0.08543699  (2.53e-02): par = (3.881397)
0.08538308  (9.49e-05): par = (3.907099)
0.08538308  (1.13e-06): par = (3.907001)
> test
Nonlinear regression model
  model: ETvP ~ I(1 + PETvP - (1 + PETvP^(w))^(1/w))
   data: gaugeA
    w
3.907
 residual sum-of-squares: 0.08538

Number of iterations to convergence: 5
Achieved convergence tolerance: 1.128e-06

Any ideas on how I can get the subset results for my entire grouped dataframe? It has over 600 different gauges in it. Thank you in advance.

A: Any of the following will work:
Using summarise:
df %>%
  group_by(GaugeID) %>%
  summarise(result = list(nls(ETvP ~ I(1 + PETvP - (1 + PETvP^(w))^(1/w)),
                              data = cur_data(),
                start =  list(w = 2)))) %>%
  pull(result)

[[1]]
Nonlinear regression model
  model: ETvP ~ I(1 + PETvP - (1 + PETvP^(w))^(1/w))
   data: cur_data()
    w
3.607
 residual sum-of-squares: 0.01694

Number of iterations to convergence: 5
Achieved convergence tolerance: 7.11e-08

[[2]]
Nonlinear regression model
  model: ETvP ~ I(1 + PETvP - (1 + PETvP^(w))^(1/w))
   data: cur_data()
    w
1.086
 residual sum-of-squares: 0.1532

Number of iterations to convergence: 5
Achieved convergence tolerance: 2.685e-07

Using map:
df %>%
  group_split(GaugeID) %>%
  map(~nls(ETvP ~ I(1 + PETvP - (1 + PETvP^(w))^(1/w)),
           data = .x,
           start =  list(w = 2)))

A: I usally prefer purrr and dplyr for looping functions on grouped data.
I cant edit the data, but maybe this works:
library(dplyr)
library(purrr)

yearly %>% group_by(GaugeID) %>% summarise(test = nls(ETvP ~ I(1 + PETvP - (1 + PETvP^(w))^(1/w)), data = gaugeA, start =  list(w = 2), trace = TRUE)

A: A single model can be formulated eliminating loops.  Ensure that GaugeID is a factor, subscript w by GaugeID in the formula and provide a starting value list whose w component is a vector with a starting value for each level of GaugeID.
df$GaugeID <- factor(df$GaugeID)
fo <- ETvP ~ 1 + PETvP - (1 + PETvP^(w[GaugeID]))^(1/w[GaugeID])
st <- list(w = rep(2, nlevels(df$GaugeID)))
fm <- nls(fo, df, start = st)

fm
summary(fm)

data.frame(GaugeID = levels(df$GaugeID), coef(summary(fm)), check.names = FALSE)


text:
Q: Reading a variable number of lines from a file I am trying to read a variable number of lines from a file, hopefully using InputStream object. What I'm trying to do (in a very general sense) is as follows:
Pass in long maxLines to function
Open InputStream and OutputStream for reading/writing
WHILE (not at the end of read file AND linesWritten < maxLines)
   write to file

I know InputStream goes on bytes, not lines, so I'm not sure if that's a good API to use for this. If anyone has any reccomendations on what to look at in terms of a solution (other API's, different algorithm) that's be very helpful.

A: You can have something like this
       BufferedReader br = new BufferedReader(new FileReader("FILE_LOCATION"));
       while (br.readLine() != null && linesWritten < maxLines) {
         //Your logic goes here
        }

A: Have a look at these:
Buffered Reader and
Buffered Writer
//Read file into String allText
InputSream fis = new FileInputStream("filein.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line, allText = "";
try {
    while ((line = br.readLine()) != null) {
        allText += (line + System.getProperty("line.separator")); //Track where new lines should be for output
    }
} catch(IOException e) {} //Catch any errors
br.close(); //Close reader

//Write allText to new file
BufferedWriter bw = new BufferedWriter(new FileWriter("fileout.txt"));
try {
    bw.write(allText);
} catch(IOException e) {} //Catch any errors
bw.close(); //Close writer


text:
Q: Apache Zeppelin prefix not found I am following the instructions from https://zeppelin.apache.org/docs/0.7.0-SNAPSHOT/interpreter/jdbc.html#create-a-new-jdbc-interpreter
When I try to add a new interpreter following the above instructions, I get 'Prefix not found' error. I also binded the interpreter as shown in the link. One thing I noticed though, when I create an interpreter named mysql and selected jdbc from the interpreter group, the interpreter is showing up as mysql %jdbc in the bind options whereas in the link referred above the screenshot is showing as mysql %mysql. Why is there a difference?


text:
Q: Is there a similar equivalent to get for lists as there is for dicts in python I'm sure this must have been asked, but I can't seem to find an answer.
Is there a list ~equivalent of get for dictionary. ie to return None if the value is not found at relevant list index.
currently for a list I'm doing
try:
   quote = quotes_results[0]
except IndexError:
   quote = None

for a dictionary I could do,
quote = quotes_results.get('result')
and it will return None if there is no value at that key.
This is instead of doing
try:
    quote = quotes_results['results']
except KeyError:
    quote = None


text:
Q: Finding Duplicate Dates by a certain ID in a single table Here is what my data looks like
ID          Date             Other Field
123        1/2/2017        a
123        1/3/2017        b
123        1/3/2017        c
123        1/5/2017        d
123        1/6/2017        e
123        1/6/2017        f
456        2/4/2017        g
456        2/4/2017        h
456        2/5/2017        i
456        2/6/2017        j

I am looking to identify when there is a date that is duplicated by ID, i would like to return the entire record. The results would look like
ID        Date          Other Field
123      1/3/2017      b
123      1/3/2017      c
123      1/6/2017      e
123      1/6/2017      f
456      2/4/2017      g
456      2/4/2017      h

I am not sure how to identify duplicate dates within a single table, then return those records only individually.
Any help is greatly appreciated!

A: select
t1.* from
table t1
join
(select id,date,count(*) from
table t2
group by id,date
having count(*)>=2
) t2
on t1.id=t2.id and t1.date=t2.date

A: What database are you using? If it supports window functions (e.g. Oracle or PostgreSQL), then:
select
  id, "date", other_field
from
(
  select
    tbl.*,
    count(*) over (partition by id, "date") date_cnt
  from tbl
)
where date_cnt >= 2


text:
Q: Query Overpass API for roads in a specific country I'm trying to construct a query of all 'highway=' ways in a specific area in overpass. I've been defaulting to using the {{bbox}} - but I really would prefer to do it by country.
I've tried using 'nominatimArea:' instead of {{bbox}} but I get a parse error ' line 8: parse error: ')' expected - '(' found. ' on the below:
/*
This shows the roads in nepal.
*/

[out:json];

(
  way ["highway"~"motorway|trunk|primary|motorway_link|trunk_link|primary_link|unclassified|tertiary|secondary|track|path"]({{nominatimArea:Nepal}});
);

out meta;
>;
out skel qt;

ALSO ... if I try this...I only (weirdly) get one area - no ways (maybe the relations are a mess?)
/*
This shows the roads in nepal.
*/

[out:json];

(area[name="Nepal"];
  way(area) ["highway"~"motorway|trunk|primary|motorway_link|trunk_link|primary_link|unclassified|tertiary|secondary|track|path|residential|service"];
);

out meta;
>;
out skel qt;

Returns this one item (and it is an area NOT a way)
Note: I know this is a large query - but I really just need the url to the raw JSON (like this) - not the actual overpass map result.

A: Got it.
/*
This shows the roads in nepal.
*/

[out:json];

area[name="नेपाल"];
 (way["highway"~"motorway|trunk|primary|motorway_link|trunk_link|primary_link|unclassified|tertiary|secondary|track|path|residential|service|secondary_link|tertiary_link"](area);
);

out meta;
>;
out skel qt;


text:
Q: Doing upsert in ORACLE DB and doesnt work I am doing an insert condition in oracle that when the record based on job and subjob doesnt exists, it shall insert otherwise, if it exists then it should update the rest of the value.
this is my procedure,
CREATE OR REPLACE PROCEDURE WELTESADMIN.SP_JOB_INS
(
    JOB_V VARCHAR2,
    SUBJOB_V VARCHAR2,
    STARTDATE_V DATE,
    ENDDATE_V DATE,
    JOBWEIGHT_V NUMBER
)
AS BEGIN INSERT INTO PROJECT_SPAN (JOB, SUBJOB, STARTDATE, ENDDATE, WEIGHT) VALUES (JOB_V, SUBJOB_V, STARTDATE_V, ENDDATE_V, JOBWEIGHT_V);
EXCEPTION WHEN DUP_VAL_ON_INDEX THEN
UPDATE PROJECT_SPAN SET STARTDATE = STARTDATE_V, ENDDATE = ENDDATE_V, WEIGHT = JOBWEIGHT_V WHERE JOB = JOB_V AND SUBJOB = SUBJOB_V;
END;
/

and this is from PHP Call,
$insertJobSpanSql = "BEGIN SP_JOB_INS(:JOB, :SUBJOB, :SDATE, :EDATE, :WT); END;";
            $insertJobSpanParse = oci_parse($conn, $insertJobSpanSql);
            oci_bind_by_name($insertJobSpanParse, ":JOB", $jobValue);
            oci_bind_by_name($insertJobSpanParse, ":SUBJOB", $subJobValue);
            oci_bind_by_name($insertJobSpanParse, ":SDATE", $startDateValue);
            oci_bind_by_name($insertJobSpanParse, ":EDATE", $endDateValue);
            oci_bind_by_name($insertJobSpanParse, ":WT", $jobWeightValue);
            $insertJobSpanRes = oci_execute($insertJobSpanParse);

            if ($insertJobSpanRes){
                oci_commit($conn);
            } else {
                oci_rollback($conn);
            }

problem is it keeps inserting new row with the same job and subjob value. it should be an update to the new value.

A: First of all, I recommend to use MERGE in such cases:
CREATE OR REPLACE PROCEDURE WELTESADMIN.SP_JOB_INS
(
    JOB_V VARCHAR2,
    SUBJOB_V VARCHAR2,
    STARTDATE_V DATE,
    ENDDATE_V DATE,
    JOBWEIGHT_V NUMBER
) AS
BEGIN
  merge into PROJECT_SPAN ps
  using (select JOB_V, SUBJOB_V, STARTDATE_V, ENDDATE_V, JOBWEIGHT_V
           from dual) new_val
     on (ps.SUBJOB = new_val.SUBJOB_V and ps.JOB = new_val.JOB_V)
   when matched then update
    set STARTDATE = new_val.STARTDATE_V,
        ENDDATE = new_val.ENDDATE_V,
        WEIGHT = new_val.JOBWEIGHT_V
   when not matched then insert (JOB, SUBJOB, STARTDATE, ENDDATE, WEIGHT)
 values (new_val.JOB_V, new_val.SUBJOB_V, new_val.STARTDATE_V,
         new_val.ENDDATE_V, new_val.JOBWEIGHT_V );
END;
/

If it still not updating values, use package DBMS_OUTPUT or logging into a table to make sure, that new and old JOB and SUBJOB really the same.

A: Oracle raises  DUP_VAL_ON_INDEX when a DDL statement violates a primary key or unique key constraint.  So for your code to work you need to define a primary key on (job, subjob) or else build a unique index on that pair.
Oracle provides an easier way of implementing upserts, in the form of the MERGE statement:
CREATE OR REPLACE PROCEDURE WELTESADMIN.SP_JOB_INS
(
    JOB_V VARCHAR2,
    SUBJOB_V VARCHAR2,
    STARTDATE_V DATE,
    ENDDATE_V DATE,
    JOBWEIGHT_V NUMBER
)
AS BEGIN
    merge into project_span ps
        using ( select job_v, subjob_v, startdate_v, enddate_v, jobweight_v from dual ) q
        on (ps.job = q.job_v
            and ps.subjob = q.subjob_v)
    when not matched then
        insert (job, subjob, startdate, enddate, weight)
        values (q.job_v, q.subjob_v, q.startdate_v, q.enddate_v, q.jobweight_v);
    when matched then
        update
        set startdate = q.startdate_v
            , enddate = q.enddate_v
            , weight = q.jobweight_v
           ;
END;

The MERGE statement is in the documentation. Find out more.


text:
Q: Algorithm to print asterisks for duplicate characters I was asked this question in an interview:
Given an array with the input string, display the output as shown below
Input
INDIA

Output
INDA
****
*

I iterated through the array and stored each character as a key in std::map with value as number of occurrence. Later I iterate the map and print the asteriks and reduce the value in the map for each character.
Initially, I was asked not to use any library. I gave a solution which needed lot of iterations. For every character, iterate the complete array till the index to find previous occurrences and so on.
Is there any better way, e.g. better complexity, such as faster operation, by which this can be achieved?

A: Essentially what you are asking is how to implement map without using the STL code, as using some kind of data structure which replicates the basic functionality of map is pretty much the most reasonable way of solving this problem.
There are a number of ways of doing this. If your keys (here the possible characters) come from a very large set where most elements of the set don't appear (such as the full Unicode character set), you would probably want to use either a tree or a hash table. Both of these data structures are very important with lots of variations and different ways of implementing them. There is lots of information and example code about the two structures around.
As @PeterG said in a comment, if the only characters you are going to see are from a set of 256 8-bit chars (eg ASCII or similar), or some other limited collection like the upper-case alphabet you should just use an array of 256 ints and store a count for each char in that.

A: If the alphabet under consideration is fixed, it can be done in two passes:

*

*Create an integer array A with the size of the alphabet, initialized with all zeros.

*Create a boolean array B with size of the input, initialize with all false.

*Iterate the input; increase for every character the corresponding content of A.

*Iterate the input; output a character if its value it B is false and set its value in B to true. Finally, output a carriage return.

*Reset B.

*Iterate input as in 4., but print a star if if the character's count in A is positive, then decrease this count; print a space otherwise.

*Output a carriage return; loop to 5 as long as there are any stars in the output generated.

A: The following code works correctly. I am assuming that you can't use std::string and take note that this doesn't take overflowing into account since I didn't use dynamic containers. This also assumes that the characters can be represented with a char.
#include <iostream>

int main()
{
    char input[100];
    unsigned int input_length = 0;
    char letters[100];
    unsigned int num_of_letters = 0;
    std::cin >> input;
    while (input[input_length] != '\0')
    {
        input_length += 1;
    }
    //This array acts like a hash map.
    unsigned int occurrences[256] = {0};
    unsigned int max_occurrences = 1;
    for (int i = 0; i < input_length; ++i)
    {
        if ((occurrences[static_cast<unsigned char>(input[i])] += 1) == 1)
        {
            std::cout<< " " << (letters[num_of_letters] = input[i]) << " ";
            num_of_letters += 1;
        }
        if (occurrences[static_cast<unsigned char>(input[i])] > max_occurrences)
        {
            max_occurrences = occurrences[static_cast<unsigned char>(input[i])];
        }
    }
    std::cout << std::endl;
    for (int row = 1; row <= max_occurrences; ++row)
    {
        for (int i = 0; i < num_of_letters; ++i)
        {

            if (occurrences[static_cast<unsigned char>(letters[i])] >= row)
            {
                std::cout << " * ";
            }
            else
            {
                std::cout << "   ";
            }

        }
        std::cout << std::endl;
    }
    return 0;
}

A: This is interesting. You shouldnt use a stl::map because that is not a hashmap. An stl map is a binary tree. An unordered_map is actually a hash map. In this case we dont need either. We can use a simple array for char counts.
void printAstr(std::string str){
 int array[256] ;// assumining it is an ascii string
 memset(array, 0, sizeof(array));
 int astrCount = 0;
 for(int i = 0; i < str.length()-1; i++){
     array[(int) str[i]]++;
     if(array[(int) str[i]] > 1) astrCount++;
 }
std::cout << str  << std::endl;
for(int i = 0;  i < str.length()-1;i++) std::cout << "* ";
std::cout << std::endl;
while(astrCount != 0){
   for(int i= 0; i< str.length() - 1;i++){
       if(array[(int) str[i]] > 1){
          std::cout << "* ";
          array[(int) str[i]]--;
          astrCount--;
       }else{
        std::cout << " ";
       }
   }
   std::cout << std::endl;
}

}
pretty simple just add all values to the array, then print them out the number of times you seem them.
EDIT: sorry just made some logic changes. This works now.

A: here is another one:
You can see it working HERE
#include <stdio.h>
int main()
{
    int i,j=0,f=1;
    char input[50]={'I','N','D','I','A','N','A','N'};
    char letters[256]={0};
    int counter[256]={0};
    for(i=0;i<50;i++)
    {
        if(input[i])
         counter[input[i]]++;
         if(counter[input[i]]==1)
         {
            putchar(input[i]);
            letters[j]=input[i];
            j++;
         }
    }
    putchar('\n');
    while(f)
    {
        f=0;
        for(i=0;i<j;i++)
            if(counter[letters[i]])
            {
                putchar('*');
                counter[letters[i]]--;
                f=1;
            }
            else
            {
                putchar(' ');
            }
        putchar('\n');
    }
    return 0;
}

A: The question is marked as c++ but It seems to me that the answers not are all quite C++'ish, but could be quite difficult to achieve a good C++ code with a weird requirement like "not to use any library". In my approach I've used some cool C++11 features like in-class initialization or nullptr, here is the live demo and below the code:
struct letter_count
{
    char letter = '\0';
    int count = 0;
};

int add(letter_count *begin, letter_count *end, char letter)
{
    while (begin != end)
    {
        if (begin->letter == letter)
        {
            return ++begin->count;
        }
        else if (begin->letter == '\0')
        {
            std::cout << letter; // Print the first appearance of each char
            ++begin->letter = letter;
            return ++begin->count;
        }

        ++begin;
    }

    return 0;
}

int max (int a, int b)
{
    return a > b ? a : b;
}

letter_count *buffer = nullptr;

auto testString = "supergalifragilisticoespialidoso";

int len = 0, index = 0, greater = 0;

while (testString[index++])
    ++len;

buffer = new letter_count[len];

for (index = 0; index < len; ++index)
    greater = max(add(buffer, buffer + len, testString[index]), greater);

std::cout << '\n';

for (int count = 0; count < greater; ++count)
{
    for (index = 0; buffer[index].letter && index < len; ++index)
        std::cout << (count < buffer[index].count ? '*' : ' ');

    std::cout << '\n';
}

delete [] buffer;

Since "no libraries are allowed" (except for <iostream>?) I've avoided the use of std::pair<char, int> (which could have been the letter_count struct) and we have to code many utilities (such as max and strlen); the output of the program avobe is:
supergaliftcod
**************
* *******   *
*     ***   *
*       *
        *
        *

A: My general solution would be to traverse the word and replace repeated characters with an unused nonsense character.  A simple example is below, where I used an exclamation point (!) for the nonsense character (the input could be more robust, some character that is not easily typed, disallowing the nonsense character in the answer, error checking, etc).  After traversal, the final step would be removing the nonsense character.  The problem is keeping track of the asterisks while retaining the original positions they imply.  For that I used a temp string to save the letters and a process string to create the final output string and the asterisks.
#include <iostream>
#include <string>

using namespace std;

int
main ()
{
  string input = "";
  string tempstring = "";
  string process = "";
  string output = "";
  bool test = false;

  cout << "Enter your word below: " << endl;
  cin >> input;

  for (unsigned int i = 0; i < input.length (); i++)
  { //for the traversed letter, traverse through subsequent letters
    for (unsigned int z = i + 1; z < input.length (); z++)
    {
        //avoid analyzing nonsense characters
        if (input[i] != '!')
        {
          if (input[i] == input[z])
          { //matched letter; replace with nonsense character
            input[z] = '!';
            test = true;    //for string management later
          }
        }
    }
    if (test)
    {
      tempstring += input[i];
      input[i] = '*';
      test = false; //reset bool for subsequent loops
    }
  }

  //remove garbage symbols and save to a processing string
  for (unsigned int i = 0; i < input.size (); i++)
    if (input[i] != '!')
      process += input[i];

  //create the modified output string
  unsigned int temp = 0;
  for (unsigned int i = 0; i < process.size (); i++)
    if (process[i] == '*')
    { //replace asterisks with letters stored in tempstring
      output += tempstring[temp];
      temp++;
    }
    else
      output += process[i];

   //output word with no repeated letters
  cout << output << endl;

  //output asterisks equal to output.length
  for (unsigned int a = 0; a < output.length (); a++)
    cout << "*";

  cout << endl;

  //output asterisks for the letter instances removed
  for (unsigned int i = 0; i < process.size (); i++)
    if (process[i] != '*')
      process[i] = ' ';

  cout << process << endl << endl;
}

Sample output I received by running the code:
Enter your word below:
INDIA
INDA
****
*

Enter your word below:
abcdefgabchijklmnop
abcdefghijklmnop
****************
***

A: It is possible just using simple array to keep count of values.
#include<iostream>
#include<string>

using namespace std;

int main(){

    string s;
    char arr[10000];
    cin>>s;
    int count1[256]={0},count2[256]={0};
    for(int i=0;i<s.size();++i){
        count1[s[i]]++;
        count2[s[i]]++;
    }
    long max=-1;
    int j=0;
    for(int i=0;i<s.size();++i){
        if(count1[s[i]]==count2[s[i]]){ //check if not printing duplicate
            cout<<s[i];
            arr[j++]=s[i];
        }
        if(count2[s[i]]>max)
            max=count2[s[i]];
        --count1[s[i]];
    }
    cout<<endl;
    for(int i =1; i<=max;++i){
        for(int k=0;k<j;++k){
            if(count2[arr[k]]){
                cout<<"*";
                count2[arr[k]]--;
            }
            else
                cout<<" ";
        }
        cout<<endl;

    }

}


text:
Q: Prevent linux from auto scan and mapping partitions on some disk TL;DR
Linux scan disk (for example /dev/sdc) and add files to address partitions on that disk (for example /dev/sdc1) - how can I tell Linux to not do that for some disk?
Long story:
I used VM (QEMU+KVM) to install other OS on physical HDD - "/dev/sdc" (different from host, of course). Before installation disk was cleared (all partitions removed). First installation has failed. I have stop VM and launched GParted on host and it showed warning about corrupted file-systems on that disk. I noticed that in "/dev/" appeared "sdc1" and etc. Next installation succeed, and I noticed that there was no "sdc1" and etc. Host side GParted showed warning that partitions on "/dev/sdc" is not mapped. So I came to conclusion that linux partition mapping may be reason for corrupted file-system in this case. How can I temporary disable that feature?

A: Linux shows you device files for partitions when the disk has partitions. If the disk has partitions, there's no point in telling Linux not to show them to you: whatever problem you're having, this could only hide the problem, not solve it.
If you change the partition table while the disk is connected, the kernel might not notice and might keep acting on old data. After changing the partition table in any way, run the command partprobe /dev/sdc to re-read the partition table on /dev/sdc. You may need to unmount volumes that made use of the old partition table before doing this. The disk corruption you saw may have been a result of different parts of the system using conflicting information about the disk because you didn't run partprobe.
There's rarely a good reason to create a filesystem directly on a disk device, rather than create a partition on the disk and a filesystem on the partition. So run gparted or fdisk or gdisk, create a partition, make sure that partprobe is called, and re-do the installation starting from a consistent view of the disk.


text:
Q: Probability problem involving hyper-geometric distribution So, I have the following problem:
"$n$ balls are chosen randomly and without replacement from an urn containing $N$ white balls and $M$ black balls. Give the probability mass function of the random variable $X$ which counts the number of white balls chosen. Show that the expectation of $X$ is $\frac{Nn}{(M+N)}$.
Hint: Do not use the hypergeometric distribution. Instead, write $X = X_1 + X_2 + ... + X_N$ where $X_i$ equals $1$ if the $i$th white ball was chosen."
If I could simply use the hypergeometric distribution, finding the probability mass function would be easy, and it would be the following: $$ P(X=k) = \frac{{N\choose k} {M\choose n-k}}{{N+M\choose n}} $$
Now, the teacher doesn't want us to use this. I guess that his technique makes computations easier when it comes to finding the expected value (because we would have: $E(X) = E(X_1) + E(X_2) + ... + E(X_N)$ (because of the linearity of the expected value).
Now my problem is that I do not know how to find $P(X_i = 0) \text{ and }  P(X_i = 1)$
PS: I get it that to compute the expected value, trying to find out $p(X_i = 0) $ is not very useful, as $E(X_i) = 0 \cdot P(X_i = 0) + 1 \cdot P(X_i=1)$, however, I still want to understand how I could compute it.

A: Okay... So I managed to do it on my own. For those of you who are interested here's the solution:
$$P(X_i = 0) = \frac{N+M-1}{N+M} \cdot \frac{N+M-2}{N+M-1} \cdot \ \ ... \ \ \cdot \frac{N+M-n}{N+M-(n-1)} $$ which, when simplified gives: $$P(X_i=0) = \frac{N+M-n}{N+M} $$
The way to think about this is the following.  $X_i=0$ denotes the fact of not picking the $i$th white ball. So, in the $n$ draws, we're allowed to pick any other ball. Therefore, during the first draw, we can pick $N+M-1$ balls (as we don't want to pick the $i$th white ball), and the probability to do so is $p = \frac{N+M-1}{N+M}$.
When we do the second draw we are allowed to pick $N+M-2$ balls (as we can't pick the $i$th white ball AND since there's only $N-M-1$ balls in the urn after the first draw),and the probability to do so is $p = \frac{N+M-2}{N+M-1}$
Applying the same logic to the $n$ draws we come to the conclusion that $P(X_i=0) = \frac{N+M-n}{N+M} $
Now, we have $$P(X_i =1) = 1-P(X_i=0) \\ = \frac{n}{M+N}$$
Finally, to get the expected value of $X$, first we notice that $E(X_i) = P(X_i=1)$ (see post for more details), then from the linearity of the expected value, we have that $$E(X) = E(X_1)+E(X_2)+...+E(X_N)\\= \sum_{i=1}^{N} E(X_i)\\=\frac{N\cdot n}{N+M}$$ which is the correct solution.
Side note: A more formal way of finding $P(X_i=0)$ is the following:
First we need to recall that for two events $E$ and $F$, $P(E\cap F) = P(F)\cdot P(E|F) $
Now, let $D_j$ denote the the fact of not picking the $i$th ball at the $j$th draw. Thus we have that $$P(X_i=0) = P(D_1 \cap D_2 \  \cap \  ... \  \cap  \ D_{n}) \\ = P(D_1)\cdot  P(D_2|D_1) \cdot P(D_3|D_1 \cap \  D_2) \cdot \ ... \ \cdot P(D_n|D_1 \cap D_2 \  \cap \  ... \  \cap  \ D_{n-1})$$ which is exactly what we computed.


text:
Q: Box Scroldown with page I'want that my box scroll down with my page but this script seem dosn't work her's my code:
CSS
/* Print and Download Buttons */
#box {top: 271px;}
a.print{ background:#ffffff url(images/bg-print.jpg) no-repeat top center; border:1px solid #ccc; display:block; height:24px; padding:2px;
         position:absolute; right:765px; text-indent:-9999px; top:271px; width:24px; z-index:110; }

a.download{ background:#ffffff url(images/bg-download.jpg) no-repeat top center; border:1px solid #ccc; display:block; height:24px; padding:2px;
            position:absolute; right:765px; text-indent:-9999px; top:300px; width:24px; z-index:111; }

    a.print:hover, a.download:hover{ padding-right:12px; }

HTML Code :

            Print CV
            Download CV

And this is my costum.js
    window.onload = function() {

  function getScrollTop() {
    if (typeof window.pageYOffset !== 'undefined' ) {
      // Most browsers
      return window.pageYOffset;
    }

    var d = document.documentElement;
    if (d.clientHeight) {
      // IE in standards mode
      return d.scrollTop;
    }

    // IE in quirks mode
    return document.body.scrollTop;
  }

  window.onscroll = function() {
    var box = document.getElementById('box'),
        scroll = getScrollTop();

    if (scroll <= 300) {
      box.style.top = "300px";
    }
    else {
      box.style.top = (scroll + 2) + "px";
    }
  };

};

A: You have set position:absolute on the a tags not box so setting top will not affect its position. Move position to the div and it should work fine:
/* Print and Download Buttons */
#box {
    position:absolute;
    right:765px;
    top:271px;
}

a.print {
    background:#f00;
    border:1px solid #ccc;
    display:block;
    height:24px;
    padding:2px;
    text-indent:-9999px;
    width:24px;
    z-index:110;
}

a.download {
    background:#c00;
    border:1px solid #ccc;
    display:block;
    height:24px;
    padding:2px;
    position:absolute;
    text-indent:-9999px;
    width:24px;
    z-index:111;
}

a.print:hover, a.download:hover {
    padding-right:12px;
}


text:
Q: Set EditingArea in HTMLEditor (ajax control) I have a HTMLEditor (ajax control).
I want to set the size of EditingArea inside HTMLEditor to look like an A4 size paper.
Can I set the margins on all four sides of the HTMLEditor? If yes, than how to do it?
Is there any other way I can make my HTMlEditor look like an A4 size paper (the way MS Word document pages are shown)?
Code:
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="PILWP.aspx.cs"  Inherits="_Default" %>

<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit.HTMLEditor" tagprefix="cc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Untitled Page</title>

    <form id="form1" runat="server">

                   <asp:Label ID="Label1" runat="server" style="font-weight: 700"
                Text="High Court"></asp:Label>
             :
            <asp:DropDownList ID="DropDownList1" runat="server">
                <asp:ListItem Value="04">Panaji</asp:ListItem>
            </asp:DropDownList>

            <asp:Label ID="Label2" runat="server" style="font-weight: 700"
                Text="Stamp/Regn"></asp:Label>
            :<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True"
                onselectedindexchanged="DropDownList2_SelectedIndexChanged">
                <asp:ListItem Value="50">Register</asp:ListItem>
                <asp:ListItem Value="31">Stamp</asp:ListItem>
                <asp:ListItem Selected="True"><-- Select --></asp:ListItem>
            </asp:DropDownList>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
                ControlToValidate="DropDownList2" ErrorMessage="Select Stamp/Reg"
                InitialValue="<-- Select -->">*</asp:RequiredFieldValidator>

            <asp:Label ID="Label3" runat="server" style="font-weight: 700" Text="Type :"></asp:Label>
            <asp:DropDownList ID="DropDownList3" runat="server">
            </asp:DropDownList>
              <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
                ControlToValidate="DropDownList3" ErrorMessage="Select case type"
                InitialValue="<-- Select -->">*</asp:RequiredFieldValidator>

            <asp:Label ID="Label4" runat="server" style="font-weight: 700" Text="No. :"></asp:Label>
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server"
                ControlToValidate="DropDownList3" ErrorMessage="Select case type"
                InitialValue="<-- Select -->">*</asp:RequiredFieldValidator>

            <asp:Label ID="Label5" runat="server" style="font-weight: 700" Text="Year"></asp:Label>

            <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server"
                ControlToValidate="TextBox2" ErrorMessage="Enter Year">*</asp:RequiredFieldValidator>
            <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
                ControlToValidate="TextBox2" ErrorMessage="Enter year"
                ValidationExpression="^\d{4}$">YYYY</asp:RegularExpressionValidator>

            <asp:Label ID="Label6" runat="server" style="font-weight: 700"
                Text="Order Date"></asp:Label>
            <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
            <asp:Label ID="Label14" runat="server" Text="dd/mm/yyyy"></asp:Label>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server"
                ControlToValidate="TextBox3" ErrorMessage="Enter proper format">*</asp:RequiredFieldValidator>
            <asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server"
                ControlToValidate="TextBox3" ErrorMessage="Enter valid date"

                ValidationExpression="^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$">dd/mm/yyyy</asp:RegularExpressionValidator>

        <asp:ValidationSummary ID="ValidationSummary1" runat="server"
            style="margin-left: 50px" />

            <asp:Button ID="Button1" runat="server" onclick="Button1_Click"
                style="margin: 0 0 0 126px; font-weight: 700" Text="GO" />

    <cc1:Editor ID="Editor1" runat="server" AutoFocus="true" Height="400px"
        style="margin: 0 0 0 100px; text-align: center" Width="800px"  />

                                                                                <asp:TextBox
            ID="TextBox4" runat="server" Height="66px" TextMode="MultiLine" Visible="False"
            Width="183px"></asp:TextBox>

        <asp:Button ID="Button2" runat="server" onclick="Button2_Click"
            Text="pdf preview" />

        <asp:Button ID="Button3" runat="server" onclick="Button3_Click"
            Text="Temp save" />

    <asp:ScriptManager ID="ScriptManager1"
  runat="server" >

   </asp:ScriptManager>
    <asp:HiddenField ID="HiddenField1" runat="server" />
    <asp:HiddenField ID="HiddenField2" runat="server" />
    <asp:HiddenField ID="HiddenField3" runat="server" />
    <asp:HiddenField ID="HiddenField4" runat="server" />
    <asp:HiddenField ID="HiddenField5" runat="server" />
    <asp:HiddenField ID="HiddenField6" runat="server" />
    <asp:HiddenField ID="HiddenField7" runat="server" />

    </form>

A: Can you paste the html markup produced by the editor..you should be  able to set the format..by overriding the css classed used in the control by your own..


text:
Q: Undefined SP.ClientContext I always get undefined on my SP.ClientContext.get_current()
I have tried with this code:
SP.SOD.executeFunc('sp.js','SP.ClientContext',runthiscode);

function runthiscode(){

SP.SOD.executeFunc('SP.UserProfiles.js','SP.UserProfiles',initialize);

}

And this code:
ExecuteOrDelayUntilScriptLoaded(initialize, "SP.UserProfiles.js");

I use this code for all scripts
<script type="text/javascript">
 if (window.jQuery == undefined)
 document.write(unescape('%3Cscript src="../style library/scripts/jquery-2.0.3.js"    type="text/javascript"%3E%3C/script%3E') );
 document.write(unescape('%3Cscript src="/_layouts/15/SP.js" type="text/javascript"%3E%3C/script%3E') );
 document.write(unescape('%3Cscript src="/_layouts/15/SP.UserProfiles.js" type="text/javascript"%3E%3C/script%3E') );
</script>

The script is working if the newform.aspx is in edit page, then it autofill my columns from mysite information.
Update!
I got SP.js working, but not for userprofiles.js this is the code that is working for now:
var ctx = new SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(ctx);

ctx.add_requestFailed(function (sender, args) {
alert('Request failed: ' + args.get_message());
});

function example () {
}
window.onload = example;

So what can the problem be with the userprofiles ?
Update,
With this code above i cant push the button save

A: You can load your JS files directly, you don't need to do document.write
<script type="text/javascript" src="/_layouts/15/SP.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.userprofiles.js"></script>

For your, js code, try loading those within dom ready.
$(document).ready(function () {
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
        SP.SOD.executeFunc('SP.UserProfiles.js', 'SP.UserProfiles', initialize);
    });
});

A: Maybe it's because all the SharePoint JavaScript-Files are not ready when you try to access your context. Instead of document.ready or similar, try this:
_spBodyOnLoadFunctionNames.push("myCustomFunctionName"); //waits for all SP-Scripts

function myCustomFunctionName() {
     // My custom functionality
}

A: Based on Khristopher's example for workflows, I was able to get this working for user profiles in display and edit modes:
<script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(function () {
    ExecuteOrDelayUntilScriptLoaded(function () {
        SP.SOD.registerSod('SP.ClientContext', SP.Utilities.Utility.getLayoutsPageUrl('sp.js'));
        SP.SOD.registerSod('SP.UserProfiles', SP.Utilities.Utility.getLayoutsPageUrl('SP.UserProfiles.js'));
        SP.SOD.loadMultiple(['SP.ClientContext', 'SP.UserProfiles'], function () {
            var clientContext = SP.ClientContext.get_current();
            var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
        userProfileProperties = peopleManager.getMyProperties();
        clientContext.load(userProfileProperties);
        clientContext.executeQueryAsync(onSuccess, onFail);
        });
    }, "sp.js");
}, "sp.runtime.js");

function onSuccess() {
  alert(userProfileProperties.get_displayName());
}

function onFail(sender, args) {
  alert("Error: " + args.get_message());
}
</script>

A: This works for me when I am working with WorkflowServices. I imagine that it would be very similar for your UserProfiles example:
ExecuteOrDelayUntilScriptLoaded(function () {
    ExecuteOrDelayUntilScriptLoaded(function () {
        SP.SOD.registerSod('SP.ClientContext', SP.Utilities.Utility.getLayoutsPageUrl('sp.js'));
        SP.SOD.registerSod('SP.WorkflowServices.WorkflowServicesManager', SP.Utilities.Utility.getLayoutsPageUrl('SP.WorkflowServices.js'));
        SP.SOD.loadMultiple(['SP.ClientContext', 'SP.WorkflowServices.WorkflowServicesManager'], function () {
            var context = SP.ClientContext.get_current();
            var web = context.get_web();
            var servicesManager = SP.WorkflowServices.WorkflowServicesManager.newObject(context, web);
            var instanceService = servicesManager.getWorkflowInstanceService();
        });
    }, "sp.js");
}, "sp.runtime.js");


text:
Q: How to capture CCAvenue Payment Response in Angular I successfully made payment request to CCAvenue payment gateway using my Angular App. Now I need to capture response received from CCAvenue in my Angular App and need to send it to my server side for further processing. How will I accomplish this using a Typescript file?
From the CCAvenue integration document we need to submit redirect URL along with our other input parameters and CCAvenue will post the status of the order along with the parameters to this URL.
And from their sample asp.net implementation document, to deal the response they have coding like this-
    protected void Page_Load(object sender, EventArgs e)
    {
        string workingKey = "";//put in the 32bit alpha numeric key in the quotes provided
         here
        CCACrypto ccaCrypto = new CCACrypto();
        string encResponse = ccaCrypto.Decrypt(Request.Form["encResp"],workingKey);
        NameValueCollection Params = new NameValueCollection();
        string[] segments = encResponse.Split('&');
        foreach (string seg in segments)
        {
            string[] parts = seg.Split('=');
            if (parts.Length > 0)
            {
                string Key = parts[0].Trim();
                string Value = parts[1].Trim();
                Params.Add(Key, Value);
            }
        }

        for (int i = 0; i < Params.Count; i++)
        {
            Response.Write(Params.Keys[i] + " = " + Params[i] + "<br>");
        }

     }

And what i am trying to accomplish in my angular app's typescript file is-
In my app's typescript file i will receive call back from CCAvenue and need to send this response data received after processing the payment to my Server side using http call and in my server side i will do the decryption and will respond to my client with appropriate output message.
I already wrote something like this
 ngOnInit(): void {

    this.dataservice.postFeed("paymentresponse", (req,res) => {

     const { encResp } = req.body;
   });
}

With the above code i am getting response back from CCAvenue to my ngOnInit method, but i need to pass or get its response data for sending it to my server side. So how will get this response data from CCAAvenue call back in angular app's typescript?


text:
Q: Bash on Ubuntu on Windows start parameter Hei,
I want to start the bash.exe on windows with start parameters, and let the shell open.
I found the msdn page for this, but if I try to run it with e.g. bash -c "ls" , the bash is already closed after.
I want to have a link on my desktop where I put in a login command for ssh. So the shell should stay open, and not perfom the command then exit.

A: From man bash
   -c        If the -c option is present, then commands are read from the first non-option
             argument command_string.  If there are arguments  after  the  command_string,
             they are assigned to the positional parameters, starting with $0.

So, with -c, the shell is not interactive. If you want an interactive shell after the initial command is run, start another interactive bash shell from running bash shell.
With your example, it will be:
bash -c 'ls; exec bash'


text:
Q: Does Android do All the things that Java can do? I know android not includes all of java's library.
but I just want to know can I add the jars to replace with  some of java's lib. not included in Android?
thank you all in advance.


text:
Q: How does 1Password hook into this Dropbox screen? This screenshot shows an 1Password UI in another app.
What API does 1Password use to hook into this?

A: This screenshot shows a part of the Dropbox app where the Dropbox app developers have integrated the 1Password App Extension. You can find information on the 1Password App Extension here:
https://blog.agilebits.com/2014/07/30/introducing-the-1password-app-extension-for-ios-8-apps/
It's available on GitHub here:
https://github.com/AgileBits/onepassword-app-extension


text:
Q: Explicit template instantiation through a typedef If I have
typedef Foo<float> Foof;

why can't I explicitly instantiate the template like this
template class Foof;

and is there a workaround apart from typing Foo<float>?

A:
and is there a workaround apart from typing Foo?

No, unfortunately there isn't. You have to type Foo<float>. As to why, see 14.7.2 clause 3 of the C++ standard for the rule (I don't know the rationale behind the rule though).


text:
Q: Number of zeros of Wronskian Is there some relation between the number of zeros of a Wronskian and properties of given functions?
Having Wronskian (e.g. $2$ x $2$)
$$W(x)=\left|\begin{array}{c}f_1(x) & f_2(x)\\f'_1(x) & f'_2(x)\end{array}\right|$$
For example, the number of zeros, i.e., $W(x)=0$ is at most the number of zeros of the functions $f_1(x), f_2(x), \dots$, or anything similar.
I am trying to find any bound on number of zeros of any general Wronskian based on the functions. I am not interested in any sharp bound. Is there a result in literature regarding this problem?

A: I don't think, you can conclude anything. Let us take a few examples.
Example $1$: Take $f_{1}(x) = x+1$ and $f_{2}(x) = x^{2}+1$
Then Wronskian, $W(x)=\begin{vmatrix} f_{1}(x) & f_{2}(x) \\ f'_{1}(x) & f'_{2}(x) \end{vmatrix} =\begin{vmatrix} x+1 & x^{2}+1 \\ 1 & 2 x \end{vmatrix} =x^{2}+2 x-1$
Now $W(x)=0 \implies x^{2}+2 x-1=0 \implies x= -1 \pm \sqrt{2}$
Clearly, there is no similarity of roots of $W(x)=0$ with $f_{1}(x)=0$ and $f_{2}(x)=0$. Now if you conclude that the number of roots of $W(x)=0$ is lcm (least common multiple) of the number of roots of $f_{1}(x)$ and $f_{2}(x)$, then take a look on the next example.
Example $2$: Take $f_{1}(x) = x+1$ and $f_{2}(x) = x-1$
Then Wronskian, $W(x) =\begin{vmatrix} x+1 & x-1 \\ 1 & 1 \end{vmatrix} = 2 $.
In this case if you make $W(x) =0$, then it a inconsistent and therefore how can you apply your previous finding to conclude this type of problem ?
Example $3$: Take $f_{1}(x) = \sin x$ and $f_{2}(x) = 2 \sin x$
Clearly, these two functions are linearly dependent and so here $W(x) =0$, again you can't apply your previous finding to conclude any thing.


text:
Q: My custom React hook is being called in an infinite loop I wrote a custom hook called useApi - I am calling it within Main.tsx. It is being called FROM Main.tsx in an infinite loop. I know this because I put a console.log message right under the line where I implemented it. Also, useApi->go() is being run, but its not remembering any of its own state, which also tells me its being called all over again straight from Main.tsx
Why is this happening?
What I've noticed so far:
I can terminate this infinite loop by commenting out line 120 of useApi.tsx (setAccessKeyIsValid(true). But this is strange because there is nothing subscribed to this state variable anywhere that would trigger this loop action.  Why is this happening?
Main.tsx:
import React, {useState, useEffect} from 'react';
import useApi from './hooks/useApi';
import Modal from 'react-modal'
import Vim from './Vim';
import './Main.css';
import './modal.css';
Modal.setAppElement('#root')

function Main():JSX.Element {

  const [postId,updatePostId] = useState<number|null>(null)
  const [content, updateContent] = useState<string>('default text');
  const [auth, updateAuth] = useState<boolean>(false)
  const [authModalIsOpen, setAuthModal] = useState(false)
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')

  const apiUrl = 'http://127.0.0.1:8000/'

  function openAuthModal(){ setAuthModal(true) }
  function closeAuthModal(){
    if(auth){ setAuthModal(false) }
  }

  const opts = {
    username: 'asdfsdf',
    password: 'asdfsfsfsdfs',
    payload: {
      path: 'notes/',
      method: 'GET',
      body: null,
    },
    complete: (res:{})=>{console.log(res)},
    fail: ()=>{}
  }

  const [options, setOptions] = useState(opts)

  useApi(options)
  console.log('why am I reloading again?')

  function loadPost(pid:number):string|null{
    // fetch from API, load post content
    console.log('I can access:'+postId)
    return null;
  }

  return (
    <div className='main'>
      <Vim key={postId} content={content} />

      <Modal
        isOpen={authModalIsOpen}
        onRequestClose={closeAuthModal}
        className='Modal'
        overlayClassName='Overlay'
        >
        <form onSubmit={(e)=>{
          e.preventDefault()
          console.log(username)
        }}>
            <input name='username' onChange={(e)=>{
              setUsername(e.target.value)
            }}/>
            <input type="password" name='password' onChange={(e)=>{
              setPassword(e.target.value)
            }}/>
            <button type="submit">Login</button>
          </form>
        </Modal>
    </div>
  )
}

export default Main

useApi.tsx:
import {useState, useEffect, useCallback} from 'react'

interface IProps {
    username:string,
    password:string,
    payload:IPayload,
    complete: (result:{})=>void,
    fail: ()=>void
}

interface IPayload {
    path:string,
    method:string,
    body:{}|null,
}

function useApi(props:IProps){

    const [accessKey, setAccessKey] = useState('')
    const [refreshKey, setRefreshKey] = useState('')
    const [refreshKeyIsValid, setRefreshKeyIsValid] = useState<null|boolean>(null)
    const apiUrl = 'http://127.0.0.1:8000/api/'
    const [accessKeyIsValid, setAccessKeyIsValid] = useState<null|boolean>(null)
    const [results, setResults] = useState<null|{}>(null)

    const go = useCallback(()=>{
        const {body, method, path} = props.payload
        console.log('executing GO:'+accessKey)
        const options = {
            method: method,
            headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer '+accessKey,
            },
            ... (body !== null) && { body: JSON.stringify(body) }
        }
        console.log(options)
        fetch(apiUrl+path,options)
        .then(response=>{
            if(response.status===401){
                console.log(response.status)
                setAccessKeyIsValid(false)
            } else {
                response.json()
                .then(response=>{
                    setResults(response)
                })
            }
        })
    },[])

    useEffect(()=>{
        if(results){
            props.complete(results)
        }
    },[results])

    useEffect(()=>{
        if(accessKeyIsValid===false){
            console.log('access key is false')
            // We tried to make a request, but our key is invalid.
            // We need to use the refresh key
            const options = {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', },
                body: JSON.stringify( {'refresh': refreshKey} ),
            }
            fetch(apiUrl+'token/refresh/', options)
            .then(response=>{
                if(response.status === 401 || response.status === 400){
                    setRefreshKeyIsValid(false)
                    // this needs to trigger a login event
                } else {
                    response.json()
                    .then(response=>{
                        setRefreshKeyIsValid(true)
                        setAccessKey(response.access)
                        setAccessKeyIsValid(true)
                    })
                }
            })
        }
    },[accessKeyIsValid])

    useEffect(()=>{
        if(accessKeyIsValid===true){
            // Just refreshed with a new access key. Try our request again
            // go()
        }
    },[accessKeyIsValid, accessKey])

    useEffect(()=>{
        if(refreshKeyIsValid===false){
            console.log('refresh key is now valid')
            // even after trying to login, the RK is invalid
            // We must straight up log in.
            const options = {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    username: props.username,
                    password: props.password,
                 })
            }
            fetch(apiUrl+'token/', options)
            .then(response=>{
                console.log(response.status)
                if(response.status === 401 || response.status ===400){
                    props.fail()
                    console.log('total fail')
                }
                else {
                    console.log('login works')
                    response.json()
                    .then(response=>{
                        setAccessKey(response.access)
                        setRefreshKey(response.refresh)
                        setRefreshKeyIsValid(true)
                        setAccessKeyIsValid(true) // Commenting this out disables the loop
                    })
                }
            })
        }

    },[refreshKeyIsValid])

    return go()
};

export default useApi

A: I think what's going on is a combination of all three comments:

*

*effects that update their own dependencies.

*executing go() rather than returning it.

*creating go as a closure that never updates its accessToken.

You're executing go on every state change, but executing it with an empty accessKey because the useCallback does not have accessToken in its dependency array.  You get an invalid response, so you set accessKeyIsValid to false.  This triggers your other effects and eventually you get to the line that you commented out, where you set accessKeyIsValid to true.  But that state change triggers a re-render so go() runs again and sets it back to false, continuing the loop.


text:
Q: Angular JS - Update ng-model when one input is inside ng-view and other input inside ng-include This question is an extension of Angular JS - Update input options with other input options
I have two ng-model inputs (input options), one is inside a ng-view and the other is inside a ng-include. I want to keep both updated when changing, so the value displayed by both is always the same.
The code is working when both inputs are in the same level. When one input is inside ng-include, I manage to get it working by adding $parent to the ng-model scope, but when placing the other input inside the ng-view I cannot manage to get it working. You can check my code in this plunkr

A: EDIT: I felt mean with my previous response, since it was basically "You're wrong, do it my way", so here is an explanation of the problem.
You have a div with ng-ctrl set on it. This div now has a scope with an instance of myCtrl.
ng-include creates a child scope, which inherits from its parent scope (the previously created myCtrl scope). This scope will not have direct references to selectedCountry or countries, but angular will automatically search parent scopes for values when it doesn't find them. This is important. (This is how JavaScript prototypical inheritance works. More info here.)
You also have an ng-view, which in your route provider you've told has its controller set to myCtrl. This means it is going to create a seperate myCtrl scope, which is also a child of the outer myCtrl scope. Because it is a child of the outer myCtrl scope, like your ng-include scope, angular would usually search its parent for properties it can't find on the immediate scope.
However this is where it gets complicated. In this case, because it is also another instance of myCtrl, it created new properties for selectedCountry and countries on itself and thus does not need to search its parent for the properties when you reference them. Angular matches objects by reference, and not by a deep object comparison, therefore these objects are considered to be different and selecting something from list A changes selectedCountry to a reference of an object which doesn't exist on list B.
This is why you were forced to use $parent, to try and point to the same references as the scope outside it, which your ng-include is automatically referencing through its parent.
The second problem with your code, is whilst you used $parent for the selectedCountry value, you did not use $parent for the countries array, and so it is using the array of objects that were re-created on the child myCtrl to fill your select box. Again, even though the objects have the same values, angular compares by reference for ng-options. So the Modor on select A is not the same as Modor on select B.
As an additional note, there is a third problem you could have created had you not set $parent on selectedCountry for menu.html and checkout.html. Whilst initially it would search the parent for selectedCountry, if you changed the select, it would create a property on the child scope instead of bubbling up to the parent, and thus from then on it would no longer match the parent's version of selectedCountry.
So, to summise, the way you've coded it you have two choices.
The crap choice:

*

*$parent.everything

*Here is a Plunkr of $parent fixing everything (please don't do this)

The responsible choice:

*

*Use controllerAs to prevent scoping problems forever

*Here is a Plunkr of how I would do it with controllerAs
A short guide for controllerAs is here
TL;DR; if you don't want to read guide

*

*In your html -> ng-controller="myCtrl as myCtrl"

*Also in your html -> myCtrl.countries

*If it was a route/directive, set this property -> controllerAs: 'myCtrl'

*In your Controller, instead of $scope.stuff -> this.stuff

*

*Note: this is for property/function assignment. If you're using a $scope function like $watch, that is still done on $scope.

Just as an extra tip, this is my bible for coding in angular. Follow these guidelines and your code will be immaculate and prevent you from these kind of pitfalls.


text:
Q: MongoDB - Retrieve only the matching subdocument AND the root document Edit:
Problem solved, see below.
I have the following document:
db.clients.insert({
    _id: ObjectId("524d720d8d3ea014a52e95bb"),
    company: "Example",
    logins: [
        {
            "name": "John Smith",
            "username": "test",
            "password": "eF9wnBEys0OzL5vmR/OHGCaekHiw/Miy+XvbDdayxeo=",
            "email": "a@a.com",
            "last": null,
            "roles": ["CONFIG"]
        },
        {
            "name": "Guest",
            "username": "guest",
            "password": "K/gYODb7XPo0erySvL276DyPi4+stPPK4jM3pJ8aaVg=",
            "email": "a@a.com",
            "last": null,
            "roles": []
        }
    ]
});

And now, I want to authenticate my clients, using this document. But, I don't want to retrieve every sub logins, I want only the one which match.
That's why I'm using an aggregate:
db.clients.aggregate(
    {
        "$project": {
            "login": "$logins",
            "_id": 0
        }
    },
    {
        "$unwind": "$login"
    },
    {
        "$group": {
            "_id": "$login.username",
            "login": {
                "$first": "$login"
            }
        }
    },
    {
        "$match": {
            "login.username": "test",
            "login.password": "eF9wnBEys0OzL5vmR/OHGCaekHiw/Miy+XvbDdayxeo=",
        }
    }
);

Which works fine, giving me:
{
        "result" : [
                {
                        "_id" : "test",
                        "login" : {
                                "name" : "John Smith",
                                "username" : "test",
                                "password" : "eF9wnBEys0OzL5vmR/OHGCaekHiw/Miy+XvbDdayxeo=",
                                "email" : "a@a.com",
                                "last" : null,
                                "roles" : [
                                        "CONFIG"
                                ]
                        }
                }
        ],
        "ok" : 1
}

But now, the tricky part is that I would like to retrieve also the root document fields. Such as _id and company for example.
But no matter what I try, I can't manage to do it. Do you have a solution? :)

Edit:
Ok, in fact it wasn't that hard. I'm sorry!
db.clients.aggregate(
    {
        "$project": {
            "login": "$logins",
            "_id": "$_id",
            "company": "$company"
        }
    },
    {
        "$unwind": "$login"
    },
    {
        "$group": {
            "_id": "$login.username",
            "login": {
                "$first": "$login"
            },
            "clientId": {
                "$first": "$_id"
            },
            "company": {
                "$first": "$company"
            },
        }
    },
    {
        "$match": {
            "login.username": "test",
            "login.password": "eF9wnBEys0OzL5vmR/OHGCaekHiw/Miy+XvbDdayxeo=",
        }
    }
);

A: A bit shorter variant:
db.clients.aggregate(
  {$match:{"logins.username":"test"}},
  {$unwind:"$logins"},
  {$match:{"logins.username":"test","logins.password":"eF9wnBEys0OzL5vmR/OHGCaekHiw/Miy+XvbDdayxeo="}}
)

Output is:
{
        "result" : [
                {
                        "_id" : ObjectId("524d720d8d3ea014a52e95bb"),
                        "company" : "Example",
                        "logins" : {
                                "name" : "John Smith",
                                "username" : "test",
                                "password" : "eF9wnBEys0OzL5vmR/OHGCaekHiw/Miy+XvbDdayxeo=",
                                "email" : "a@a.com",
                                "last" : null,
                                "roles" : [
                                        "CONFIG"
                                ]
                        }
                }
        ],
        "ok" : 1
}

A: You can do this with a find and the $ positional projection operator as well:
db.clients.find({
        "logins.username": "test",
        "logins.password": "eF9wnBEys0OzL5vmR/OHGCaekHiw/Miy+XvbDdayxeo=",
    }, {
        "logins.$": 1,
        "company": 1
    })

The $ in the projection contains the index of the logins array element that was matched in the query.
Output:
{
  "_id": ObjectId("524d720d8d3ea014a52e95bb"),
  "company": "Example",
  "logins": [
    {
      "name": "John Smith",
      "username": "test",
      "password": "eF9wnBEys0OzL5vmR/OHGCaekHiw/Miy+XvbDdayxeo=",
      "email": "a@a.com",
      "last": null,
      "roles": [
        "CONFIG"
      ]
    }
  ]
}


text:
Q: How to get all the dates displayed in a QCalendarWidget I am using a QCalendarWidget in my application, and I overloaded the updateCells method to put a red background on every dates which meet certain conditions.
My problem is I don't know how to get the first date displayed in the calendar (not the first date in the month), and the last date displayed.
Example: in february, the first date displayed is january the 25th, and the last date displayed is march the 7th.
There isn't any useful method in QCalendarWidget and I can't think of an algorithm for this.
Do you have any idea how to do this ?

A: As you've got access to the currently shown month and year, you can use the QDate::dayOfWeek on the first and last date of the shown contents. Taking QCalendarWidget::firstDayOfWeek into account, you aught to be able to decide how far back and forth you have to go.

A: QCalendarWidget class is a combination of more simple widgets, you can see Qt source code for help. Just use loop to get all dates between:
class myQCalendar(QCalendarWidget):
    """custum QCalendarWidget"""
    def __init__(self, parent=None):
        self.table = self.findChild(QTableView)

    def return_first_last_dates(self) -> Tuple[QDate, QDate]:
        # first row(0) and col(0) - headers, so we use second(1,1)
        first_date = self.date_by_index(
            self.table.model().index(1, 1))
        last_date = self.date_by_index(
            self.table.model().index(6, 7))
        return first_date, last_date
        # self.table.model().dateForCell(1,1) didn't work in python
        # maybe it will work in c++

    def date_by_index(self, index: QModelIndex) -> QDate:
        """ Return QDate by index of model of QTableView """
        date = self.selectedDate()
        day = int(index.data())
        mnth = date.month()  # current month always the same as current date
        if day > 15 and index.row() < 3:  # qcalendar always display 6 rows( and 0 - is header)
            mnth = date.month() - 1
        if day < 15 and index.row() > 4:
            mnth = date.month() + 1
        return QDate(date.year(), mnth, day)


text:
Q: I want to search a field but use partial text to locate record. Code now finds record but I have to enter entire text for record to be found. Access Private Sub cmdSearch_Click()
On Error Resume Next

    Dim strNDetails As String
    Dim strSearch As String

'Check txtSearch for Null value or Nill Entry first.

    If IsNull(Me![txtSearch]) Or (Me![txtSearch]) = "" Then
        MsgBox "Please enter a value!", vbOKOnly, "Invalid Search Criterion!"
        Me![txtSearch].SetFocus
    Exit Sub
End If
'---------------------------------------------------------------

'Performs the search using value entered into txtSearch
'and evaluates this against values in strStudentID

    DoCmd.ShowAllRecords
    DoCmd.GoToControl ("NDetails")
    DoCmd.FindRecord Me!txtSearch

    NDetails.SetFocus
    NDetails = NProvider.Text
    txtSearch.SetFocus
    strSearch = txtSearch.Text

'If matching record found sets focus in strStudentID and shows msgbox
'and clears search control

    If NDetails Like "*" = strSearch Then
        MsgBox "Match Found For: " & strSearch, , "Congratulations!"
        NDetails.SetFocus
        txtSearch = ""

    'If value not found sets focus back to txtSearch and shows msgbox
        Else
           MsgBox "Match Not Found For: " & strSearch & " - Please Try Again.", _
            , "Invalid Search Criterion!"
            txtSearch.SetFocus
    End If
End Sub

A: Try with:
If NDetails Like "*" & strSearch & "*" Then


text:
Q: Destroy data based on HTML class name in Rails I'm building a simple todo list using Rails (3.2.5).
I show all of the users todo items in an unordered list, each list item being the todo itself. By clicking on the todo item the user marks it as completed. Using jQuery I give the li a class of done so I can change its styling. By clicking on a "Clear completed" button I want the completed items to be destroyed (and deleted from the database).
How can this be done?
NB: I'm basically trying to recreate this app using Rails: http://davidpdrsn.com/todos/

A: Supposing the model is called Todo and the completed column is called completed, you can write one of these in the controller:
Todo.destroy_all(:completed => true)
Todo.where(:completed => true).destroy_all

If you need help with how to manage the ajax request/response, here there is a good start (sorry, I don't want to give you the solution, IMHO you should make your way by yourself)
Resources: ActiveRecord#Base::destroy_all

A: You can do it using a remote form
So you would have something like
you would have a form with remote: true for each item or you could have only one form and submit it with JQuery.
class TodoController
  def set_completed
    @todo = Todo.find(params[:id])
    @todo.done = true  # you could move this to your model and do something like @todo.done! and that would save it automatically
    @todo.save
  end

  def  destroy_completed
    @todos_to_delete = Todo.where(done: true)# here you could also move it to your model and do it like Todo.completed
    @todos_to_delete.destroy_all
  end
end

and you would render the response with the js for formatting, or even removing items on your list, like
views/todo/set_completed.erb.js
$("#item_<%= @todo.id %>").addClass("completed");


text:
Q: What ist a ContactList in ActiveCampaign? What is a ContactList in ActiveCampaign API v3 which is returned on a GET request?
GET api/3/contacts?include=contactLists.list,organization

I could not find any information on the contact list neither in the API nor the web application (https://User-Account.activehosted.com) itself. However, the lists are documented and are accessible via the web application.
Thank you for any help

A: ContactList is the list into which the contact is added which you can see here https://User-Account.activehosted.com/admin/main.php?action=list. By default, the contacts won't be added to any of the lists unless you have explicitly specified any list when adding the contact or you have to manually add the contact to a list from the contacts page (https://User-Account.activehosted.com/app/contacts).
Hope that answers your question. Please ask if you have any doubts.


text:
Q: Awk Issue with multiple expression Any one can help me what is the issue with below code
back ground :- i have a fixed width file with header , i am trying to count the nulls in the file.
i have a null pattern $col_null_patt=\s , then i am trying to substring the column from file using column start and column_length and trying to do regex match
Issue :-
awk: cmd. line:1: BEGIN {m = ENVIRON["RE"]} c=substr($0,m,p);if($n ~ "^" m "$"{N++} END{print N+0}
awk: cmd. line:1:                                            ^ syntax error

code is below
 thres=$( RE="$col_null_patt"
           awk  -v m="$col_start" -v p="$col_len"
           'BEGIN {n= ENVIRON["RE"]}
            c=substr($0,m,p);
            if(NR >1 && c ~ "^" n "$"{N++} END{print N+0}' "$cp_input")

A: thres=$(
  RE="$col_null_patt" awk -v m="$col_start" -v p="$col_len" '
    # condition                action
    BEGIN                      {re = ENVIRON["RE"]}
                               {c = substr($0,m,p)}
    NR > 1 && c ~ "^(" re ")$" {N++}
    END                        {print N+0}
    ' < "$cp_input"
)

*

*You need VAR=value awk... for a VAR environment variable to be passed to awk. With VAR=value␤awk, you're just defining a $VAR shell variable and then calling awk (and the VAR will only be in awk's environment if it has been exported beforehand)

*Remember statements in awk follow the condition { action } pattern. If you want c=substr($0,m,p) to be executed for every input record, you need to put it in an action part with a condition part the evaluates to true or without a condition part.

In any case, note that \s (to mean any one whitespace character) is not standard and understood by very few awk implementations. col_null_patt='[[:space:]]' would be standard and more portable. Or col_null_patt='[[:space:]]*' to match any amount (including null) of whitespace.


text:
Q: Next Previous Post in wordpress with previous / next link with title? I recently tried the previous post and the next post button link. I do that with image in the left and right side of the site.Its working perfect.But i didn't know how to do this
For Example:

                        <?php next_post('%', ' ', 'no');
                        ?>

                        <?php previous_post('%', '  ', 'no');
                        ?>

Is it Possible to Show the Previous Post and Next Post Link with Under Title in every Bottom of the Post. Here is the Screenshot.

A:
    <?php
        $prev_post = get_previous_post();
        $id = $prev_post->ID ;
        $permalink = get_permalink( $id );
    ?>
    <?php
        $next_post = get_next_post();
        $nid = $next_post->ID ;
        $permalink = get_permalink($nid);
    ?>
       <?php previous_post_link( '%link', __( '← Previous', 'twentyeleven' ) ); ?>

<a href="<?php echo $permalink; ?>"><?php echo $prev_post->post_title; ?>

       <?php next_post_link( '%link', __( 'Next →', 'twentyeleven' ) ); ?>

<a href="<?php echo $permalink; ?>"><?php echo $next_post->post_title; ?>

A: I hope you are using this code in single.php from where the whole of the post is displayed. For displaying the links (Next/Prev), you need to check the function.
get_template_part()

in the same file (Single.php of your theme). In my case function in single.php has been passes parameters like

<?php get_template_part( 'content-single', get_post_format() ); ?>

So, you will open the "content-single.php" according to the parameters specified in the function and paste the same code

<?php next_post('%', ' ', 'no');
?>

<?php previous_post('%', '  ', 'no');
?>

below
<?php the_title(); ?>

I hope this will solve your problem.


text:
Q: How to execute a function several times asynchronously and get first result I have a function get_data(request) that requests some data to a server. Every time this function is called, it request data to a different server. All of them should return the same response.
I would like to get the response as soon as possible. I need to create a function that calls get_data several times, and returns the first response it gets.
EDIT:
I came up with an idea of using multithreading.Pipe(), but I have the feeling this is a very bad way to solve it, what do you think?:
def get_data(request, pipe):
    data = # makes the request to a server, this can take a random amount of time
    pipe.send(data)

def multiple_requests(request, num_servers):
    my_pipe, his_pipe = multithreading.Pipe()

    for i in range(num_servers):
        Thread(target = get_data, args = (request,his_pipe)).start()

    return my_pipe.recv()

multiple_requests("the_request_string", 6)

I think this is a bad way of doing it because you are passing the same pipe to all threads, and I don't really know but I guess that has to be very unsafe.

A: I think redis rq will be good for it. get_data is a job what you put in the queue six times. Jobs executes async, in the docs your also can read how to operate with results.


text:
Q: Can 'convert to comment' be tweaked to deal with HTML links Currently when converting an answer to a comment that contains links as <a href=""> rather than in markdown this breaks the conversion:

I know this is likely to be quite uncommon and can be manually fixed but it would still save some time if the conversion could be done fully in the first instance?

Similar questions but using markdown rather than HTML

*

*Convert to Comment Moderator ability doesn't handle default link format status-completed

*Certain links get broken when automatically converting trivial answers into comments

A: Thanks for bringing this issue up. At this time I have to side with Robert Harvey and agree that users should be using Markdown as opposed to HTML. Comments do not and will not support HTML, so in the rare case that an answer with HTML is converted to a comment, the comment will remain broken until further edits are made.


text:
Q: Pass shell parameters to awk regex I have the following script
#!/bin/bash
file="path/to/file"
/usr/bin/awk '/chapter:/ {f=0} /chapter: 25/ {f=1} f' $file

how can I use a variable's value instead of 25 ?
something like this:
#!/bin/bash
file="path/to/file"
num=25
/usr/bin/awk '/chapter:/ {f=0} /chapter: <num>/ {f=1} f' $file

p.s.

*

*/usr/bin/awk -v n="$num" '/chapter:/ {f=0} /chapter: n/ {f=1} f' $fileis not working

*I cannot use any other tool for that, because awk is the fastest one for what I want o do

any ideas?

A: You're on right track here but for the 2nd part of building the regex. You can use:
awk -v n="$num" '/chapter:/{f=0} $0 ~ "chapter: " n {f=1} f' file

You need to build the regex using variable n and use ~ operator for regex matching.


text:
Q: Sending Primary Key of object via Ajax How to send primary key(pk) of the SELECTED object via AJAX. I tried {{pk}}, but unsuccessful. I am getting an error "Uncaught error" unexpected token}
{% extends 'homepage.html' %}
{% load staticfiles %}

{% block teacher_diary %}
<script language="JavaScript"  src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $('#grade_list').change(function(){
        var element = document.getElementById("grade_list");
        var value = element.options[element.selectedIndex].value;
    $.ajax({
        url: "get_subject/",
        type: "get",
        data: {
            'grade_id': value.{{ pk }}
        },
        dataType: "json"
    });

})});
</script>
<select id="grade_list">
    {% for grade in grades %}
        <option >{{ grade }}</option>
    {% endfor %}
</select>

A: Your variable identified as value does not have any attribute called {{pk}}. The use of double curly braces is reserved for server side processing of the template before the HTML is sent to the client. There is no notion of Django objects on the client side. Hopefully this makes intuitive sense.
As far as the solution, here is something that I might do. First, give each option a custom attribute data-pk that stores the pk from the server side.
<select id="grade_list">
    {% for grade in grades %}
        <option data-pk={{grade.pk}} >{{ grade }}</option>
    {% endfor %}
</select>

Then, access the pk as such using JavaScript (If you choose to use JQuery, there are easier ways).
    var element = document.getElementById("grade_list");
    var value = element.options[element.selectedIndex];
    $.ajax({
        url: "get_subject/",
        type: "get",
        data: {
            'grade_id': value.getAttribute("data-pk");
        },
        dataType: "json"
    });


text:
Q: Spirit of Stack Exchange being eroded on some of the smaller SE sites? Is the "spirit of SE" being eroded on some of the smaller sites?  By "spirit" I mean "don't ever be rude to anyone, ever" and "use the vote buttons, vote early, vote often."
See, for example (but I'm sure there are many more all over SE), some of the comments on https://math.stackexchange.com/questions/63817/limit-with-nothing-but-x-and-triangles.
I'm sad that the thread is locked (meaning nothing can be voted down or flagged as abusive) but nothing has been deleted.
Should SE have a consistent "spirit" across all SE sites, or is it okay for them to go their own way?

A: The "spirit of Stack Exchange" is defined by the about page and the FAQ page. These pages are identical across sites, except for the site name and description, and for the first section of the FAQ (which site moderators can edit). For historical reasons, the content is slightly different on the original Trilogy (Stack Overflow, Super User and Server Fault).
In particular, "Civility is required at all times; rudeness will not be tolerated. Be nice. (…) Be honest." is in the FAQ on all sites.
Beyond that, when it comes to interpretation of these rules or to additional rules, each site has its own peculiarities. Each site targets a different community, which comes with its own cultural assumptions. This manifests itself in the attitude towards some topics such as homework or suspected non-disclosure agreement violations. It also manifests itself in the use of Stack Exchange features, for example some sites tend to hunt and delete obsolete comments while others delete comments only when they meet a high threshold of inappropriateness (Math.SE is in the latter category).
Without knowing the specific situation, I would guess that the question was locked to still the unending discussion in comments and kept pending resolution in the meta discussion. That discussion has been inactive for a long time, so I guess it's time to move on.
Note that you can flag locked posts; I've done so.


text:
Q: Finite morphism "with the right number of equations" Suppose that $X$ is a scheme, say smooth, connected of finite type over a field of characteristic zero, $Y \to X$ is a smooth morphism of relative dimension $d$, and $f_1, \dots, f_d \in \mathcal{O}(Y)$ are $d$ global sections. Let $Z = Z(f_1, \dots, f_d) \subset Y$ be the closed (not necessarily reduced) subscheme defined by the global sections. Assume that the composite $Z \to X$ is finite.
What can be concluded in this situation? As far as I understand if $Z$ happened to be integral then it would be Cohen-Macaylay and flat over $X$. Is there something that can be said in greater generality? What if I assume that $X$ is the spectrum of a Henselian local ring, for example?
Related question: Are finite correspondances flat?

A: Let z be a point of Z. Because f : Z --> X is finite, then OZ,z is an OX,f(z)-algebra of the same dimension. By assumption, OY,z is an OX,f(z)-algebra of relative dimension d.
By the theory of regular sequences (see the refernce in the comments), the sequence fi,z in OY,z, of stalks of the functions fi, is regular if the relative dimension of OY,z over OZ,z = OY,z/(fi,z) is equal to d. This is the case because of the assumptions. Therefor I conclude that the sequence is regular. This means that the embedding Z --> Y is a regular embedding. This implies that f : Z --> X is flat. Q.E.D.


text:
Q: How to recover older iTunes backups for iPhone? I have an iPhone 5. I made a backup copy last week with my iTunes. I discovered that I had erased some notes so I wanted to restore the backup from iTunes. When I plugged the phone to the PC, iTunes asked me to update the iOS software in order to proceed with the restore process. I did the update but also a new backup over the old one was made.
When I look for the backups available to restore it only shows the one from yesterday but not the one from last week. Is it possible to recover older backups from iTunes even if they have been overwritten by the latest backups?

A: iTunes uses an incremental process to save the iPhone backup, If you're lucky enough you can check the directory %AppData%\Roaming\Apple Computer\MobileSync\Backup (Windows 7) to see if your old backup is there (check the dates on the files). If you find any, you can move the newest one to another location and try another restore from iTunes.

A: It's not possible since iTunes replace the latest backup when it creates a new one.
Take a look at apple documentation to see where backup are located on your computer. If you have made a backup of your hard drive before the 'yesterday' save was created you should be able to retrieve your old backup.
What you should have done instead of update :

*

*Say no to update (or download the update then install later)

*Restore from itunes

*Once the iPhone is restored, choose configure as a new iPhone, in order to not override the save you want to use with a freshly created one)

*Restore your iPhone from your old save (ie the 'yesterday' save)

One ultimate solution to your problem :
Notes on iPhone are related to an account by default icloud is used, if you have change this setup, take a look at the account you have setup. For example if your notes are save on google you can find notes inside gmail in a folder (maybe called notes). You may be able from this account to retrieve your deleted notes.


text:
Q: How to avoid using Backspace character with push_back? I'm making a software as an ATM, so when the user try to enter the password the user only sees *******, but when trying to delete it doesn't delete a character. It just adds a new one. Here's my code:
string password2 = "";

cout << "PASSWORD: ";

ch = _getch();
while(ch != 13) //character 13 is enter
{
   password2.push_back(ch);
   cout << '*';
   ch = _getch();
}

And also, I try to use pop_back(); but it doesn't work either. Can anybody help me please?

A: Just did a little magic and created this:
I must admit, I don't like the style... But it "works" !
#include<iostream>
#include<string>
#include <conio.h>

bool verify_pass(const std::string& pass)
{
    std::string input = "";
    char ch = '0';
    while(true)
    {
        ch = getch();
        if(ch == '\b')
        {
            if(input.size() > 0)
            {
                input.erase(input.begin() + input.size() - 1);  // erase last char
                std::cout << "\b \b";
            }
        }
        else if(ch != '\r\n' && ch != '\n' && ch != '\r')
        {
            input += ch;
            std::cout << '*';
        }
        else
            break;
    }
    return input == pass;
}

int main()
{
    std::string insecurePass = "1234";
    std::cout << "Enter Password: ";

    if(verify_pass(insecurePass))
        std::cout << "\nCorrect!\n";
    else
        std::cout << "\nFalse!\n";

}

By the way, you can use the vector like I used the string, but use push_back instead of += and pop_back() should work too instead of my method with erase.


text:
Q: Making Gradient Images Quickly with C++ I'm currently working with Python to create images of gradients. However, for my uses I'm afraid that Python may just be too slow. I know that Python can be extended with C++ with relative ease.
So what are some quick ways to produce images of gradients in C++?

A: Writing a bitmap manually is quite easy. For a Windows Bitmap you need a 54 byte header and then an array of colour values. (.bmp file specs)
So, create a file, write the header, supply the pixel array. For a gradient generating the colour values should be fairly simple.
.pgm/.ppm files are even easier as they have much simpler headers.


text:
Q: filter in kendoUI drag and drop I have a splitter. In this splitter, I am implementing drag and drop functionality for the list view. Each list view is loaded in "table" format.
I want to drag my list view from left to right.
For the 1st list view, I have this code :
var listViewOptions = {
    template: kendo.template(
        $("#Firsttemplate").html()
    ),
    dataSource: listdatSource,
};

var sourceListView = $("#First").kendoListView(listViewOptions).data("kendoListView");

var draggableOptions = {
    filter: "table",
    hint: function (e) {
        return $('
' + e.html() + '
');
    }
}

sourceListView.element.kendoDraggable(draggableOptions);

In the filter, if I give "table" / "tbody" the whole content of list view is dragging in a row format and after dropping it is in the right side of splitter and is displaying in a single row. I want to display in the same format as in the leftside.
Can you tell me how to do this?
Thanks

A: somejQueryElement.html() gives you the inner HTML code of your element. Thus, if you filter on table elements, your argument e of the hint function is the table and e.html() is the content of the table.
If you want to have your table, you have to add reencapsulate the element in table tags :
var draggableOptions = {
    filter: "table",
    hint: function (e) {
        return $('

' + e.html() + '

');
    }
}


text:
Q: Cannot bind click() event to HTML control Here's my setup.  I'm using .NET:

*

*I have a Main.aspx lets call it.  That page inherits a master page and the Master Page as usual includes the jQuery library and other includes that we use for jQuery that are global in scope

*In Main.aspx is an HTML plain vanilla IFrame:

*In that IFrame is another .aspx page.  Lets call it for all tense and purposes Sub.aspx

*In Sub.aspx I've got the following code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <link href="Content/Styles/Site.css" rel="stylesheet" type="text/css" />
        <title></title>

    <form id="form1" runat="server">

                    <input type="image" id="btnLogin" src="images/loginBtn.jpg" />

    </form>


text:
Q: Print preview xulrunner So I'm having this problem with opening print preview in xulrunner.
I open print preview but i can't get the navigation toolbar.
This is the code from PrintUtils.js where the toolbar is created:
var XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
        printPreviewTB = document.createElementNS(XUL_NS, "toolbar");
        printPreviewTB.setAttribute("PrintPreview", true);
        printPreviewTB.id = "print-preview-toolbar";
        printPreviewTB.className = "toolbar-primary";

And later it does this:
var navToolbox = this._callback.getNavToolb
    navToolbox.parentNode.insertBefore(printPreviewTB, browser);

I'm providing the navToolbox, that's the place where the toolbar is inserted but it doesn't show. As I said, print preview opens perfectly, pages formatted and everything but without toolbar.
Anyone have any idea why?

A: Ok, i found soulution, if anyone is interested.
So when enternig printPreview you have to pass an object with 5 functions:
getSourceBrowser, getPrintPreviewBrowser, getNavToolbox, onEnter and onExit.
With getNavToolbox you pass the reference to toolbar (placeholder) where you want to place standard navigation toolbar (with print button, zoom, and others).
I have done all that but you have to bind to that toolbar, like this :
toolbar.style.MozBinding = url('chrome://global/content/printPreviewBindings.xml#printpreviewtoolbar')";

I'm doing that in the onEnter function.
But i also had problem with the enterPrintPreview function from PrintUtils.js.
In this part of code:
var printPreviewTB = document.getElementById("print-preview-toolbar");
        if (printPreviewTB) {
          printPreviewTB.updateToolbar();
          tmptoolbar.updateToolbar();
          var browser = this._callback.getPrintPreviewBrowser();
          browser.collapsed = false;
          browser.contentWindow.focus();
          return;
        }

printPreviewTB.updateToolbar(); throws error.
I fixed this by getting the reference to the toolbar that i passed in getNavToolbox function and then calling updateToolbar on him, like this:
var printPreviewTB = document.getElementById("print-preview-toolbar");
        if (printPreviewTB) {
          var tmptoolbar = this._callback.getNavToolbox();
          tmptoolbar.updateToolbar();
          var browser = this._callback.getPrintPreviewBrowser();
          browser.collapsed = false;
          browser.contentWindow.focus();
          return;
        }

And now everything works fine.


text:
Q: After selecting a picture from the image picker in SwiftUI, unable to click on 'Done' button After select a picture from the image picker, I am unable to click on the 'Done' button. Can anyone explain why?
struct AddTodoView: View {
    @Environment(\.managedObjectContext) private var viewContext

    @Binding var showAddTodoView: Bool

    @State private var displayImagePicker = false //
    @State private var photoImage: Image?//
    @State private var photoUIImage: UIImage?//

    func getImage(){//
        if let image = photoUIImage{
            photoImage = Image(uiImage: image)
        }
    }

    @State private var name: String = ""
    @State private var selectedCategory = 0
    var categoryTypes = ["family","personal","work"]

    var body: some View {

        VStack{
            Text("Add Todo").font(.largeTitle)
            TextField("To Do name",text: $name)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .border(Color.black).padding()

            Text("Select Category")
            Picker("",selection: $selectedCategory){
                ForEach(0 ..< categoryTypes.count){
                    Text(self.categoryTypes[$0])
                }
            }.pickerStyle(SegmentedPickerStyle())
            //
            Button("Select Photo"){
                self.displayImagePicker = true
            }.padding()//
            photoImage?.resizable().scaledToFit()//

        }.padding()
        .sheet(isPresented: $displayImagePicker, onDismiss: getImage){//
            ImagePickerViewController(image: self.$photoUIImage)//
        }//

        Button(action: {
            print("pressed")
        },
        label: {
            Text("Done")
        })
    }
}

Seems that the focus has gone again from the main view to the image picker view. i.e. the print("pressed") in the Button doesn't get called.
Below's my ImagePickerViewController.
struct ImagePickerViewController: UIViewControllerRepresentable{

    @Binding var image: UIImage?

    class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate{
        var parent: ImagePickerViewController
        init(_ parent: ImagePickerViewController){
            self.parent = parent
        }

        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info:[UIImagePickerController.InfoKey : Any]){
            if let uiImage = info[.originalImage] as? UIImage{
                parent.image = uiImage
            }
            picker.dismiss(animated: true)
        }
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    func makeUIViewController(context: Context) -> some UIViewController {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = context.coordinator
        return imagePicker
    }

    func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {

    }

}

can't figure out what's wrong.

A: oh yes, its working fine. problem was due to another line of code.


text:
Q: Passing data from Firebase Database into another ViewController not working and segue wont work consequently I am trying to use data from my Firebase Database to set variables in my destination view controller and I can't really figure out if it is an issue with threading(not using the right queue) or I am not calling the perform segue with identifier the right way.
Here is my prepare for segue function.
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    ProfileService.sharedInstance.getPreparedForProfilePage(completionHandler: { (un, sn, pi, pb) in

        DispatchQueue.main.async {
            if segue.identifier == SEGUE_TO_PROFILE {
                if segue.destination.isKind(of: ProfileVC.self) {
                    let destination = segue.destination as! ProfileVC
                    destination.userName = un
                    destination.formattedScreenName = sn

                    do {
                        let pi_url = URL(string: pi)
                        let imgData = try Data(contentsOf: pi_url!)
                        let profImg = UIImage(data: imgData)
                        destination.profileImage = profImg
                        }
                    catch {}

                    do {
                        let pb_url = URL(string: pb)
                        let imgData = try Data(contentsOf: pb_url!)
                        let profBanner = UIImage(data: imgData)
                        destination.profileBannerImage = profBanner
                    }
                    catch {}
                    self.shouldSegue = true
                }

            }
        }

    })
}

the tuple's values from the completion handler are all strings (the last two image url strings) which is from my singleton class where I do the Firebase query and they work fine after making print statements. but the segue just doesn't seem to work.