text:
Q: select x no. of items from a long array and display more on scroll in a tableview I need to display say 10 items from a list of 500 items which is stored in an array, and when the user scrolls to the bottom most cell of the tableview the next 10 items are loaded in the same tableview so now the tableview has 20 items and this continues until it has been scrolled 50 times and the tableview has 500 items

A: Actually, you can just store the 500 items in the array and set the long array as the data source for your tableview. When the user scrolls down to the bottom cell, the delegates will pretty much take care of reloading new items from the array.
However, if you really want to do the whole pagination thing, you can use the willDisplayCell method to determine if the cell about to be displayed is the last cell.
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {

 // let say currentArray (which is your data source) only has 10 items
 // currentArray = [0,0,0,0,0,0,1,1,1,1]

 // if cell indexPath.row is the same index as max element of currentArray
 // it is the last cell in the table
 if indexPath.row == currentArray.count - 1 {

   // get next 10 items
   let nextTenItemsArray = [1,2,3,4,5,6,7,8,9,0]
   currentArray = currentArray + nextTenItemsArray
 }

}

Do note that my codes are just to illustrate the underlying logic needed to achieve what you asked in the question.


text:
Q: Redirect to a custom path on failure to upate I have a route set up like this -
  match "/:id" =>"car#edit", :as => :edit_car
  match "/:id/thanks" =>"cars#thanks", :as => :thanks

www.myurl.com/12345 will go to the edit action of car.
My update action looks like this
def update
  @car = Car.find(params[:id])
  respond_to do |format|
    if @car.update_attributes(params[:car])
      format.html { redirect_to(thanks_path(@car)) }
    else
      format.html { render action: "edit" }
    end
  end
end

On a successful update it redirects to www.myurl.com/12345/thanks - which is good - works as expected.
However, when it has errors while updating it renders the edit action as -
  www.myurl.com/cars/12345

I'd like it to rerender the edit action as -
  www.myurl.com/12345

I'd like make sure that error messages are still sent through. Is this possible?

A: The route you're seeing is the edit action of the resource route, not your separately defined edit action. Hence it includes the controller in the path.
If you want that the path not include the cars controller you can include this in the route definition:
resources :cars, :path => '/'

From experience I advise that you don't do that as things get messy when you want to expand your application.
I suggest you do away with the defined edit action and edit your cars from the show action of your resource route. Also, you could display the success message from the update action without redirecting by having an update view file.
If you do want to redirect you can modify resource routes as so:
resources :cars, :path => '/' do
   member do
     get 'thanks'
   end
end

redpajama_set_name: RedPajamaStackExchange


text:
Q: Non totally disconnected compact perfect set Let $K$ be a non-empty compact set of reals without isolated points. Considering the usual topology, is it possible that $K$ is not totally disconnected (i.e., the singletons are not the unique connected sets) and not regular closed (i.e., the closure of the interior of $K$ is not $K$ itself)?

A: How about $C\cup [1,2],$ where $C$ is the usual Cantor set?


text:
Q: Validation on AJAX edit/update I have AJAX to create new items and update them in my view.
My model validation holds it from being saved or submitted when I create a new one.
However, when I update an existing field, it only stops saving it but it renders the ajax update form with the "new" data which gives the impression that it is being saved.
When I refresh afterwards I see the changes got rollbacked. But this is only half of the behaviour I want.
I need the submit button to be disabled. How can I achieve this?
My form is styled like this:
<%= f.text_field :name, required: true, class: "mdl-textfield__input" %>

and my validations in model look like this :
validates_presence_of :name

My edit.js.erb
$("#education_<%=@employee_education.id%>").replaceWith("<%= j render('new_employee_education_form')%>");

My update.js.erb
$("#edit_employeeeducation_<%= @employee_education.id %>").replaceWith('<%= j render partial: "employeeeducation", locals: {employee_education: @employee_education} %>');

A: Perhaps you could add some front end form validation using a jquery plugin eg formvalidator.net. You could use this prevent the form being submitted in the first place if the data is not correct.
Alternatively in your update.js.erb you should send some feedback to the user about why there is a problem with the data.


text:
Q: Navigating through SQL rows in JAVA I'm trying to navigate through rows after a select statement was made.
Currently, i'm using this:
for the -> (next) button:
if(dataset_all.isLast());
                dataset_all.first();
            dataset_all.next();

and for the <- (prev) button:
if(dataset_all.isFirst());
                dataset_all.last();
            dataset_all.previous();

somehow, it's not working. It says that it reached the end of the column when it didnt.
Is it right? Or the problem is elsewhere?
Forgot to mention that the "dataset_all" variable is the ResultSet.
thanks in advance

A: Actually, I worked it out.
I did this:
for the -> (next) button:
if(!dataset_all.next())
    dataset_all.first();

And for the <- (previous) button:
if(!dataset_all.previous())
        dataset_all.last();

it worked all right! Shouldnt it?


text:
Q: escape hashs (#) passed as argument to use them in inner macro I am using nested macros using the xparse package, my ultimate goal being to have a custom macro factory. I have simplified my current problem here.
I want to give a pattern as an argument, like in this example:
\DeclareDocumentCommand\Foo{O{\emph{##1}} O{dummy} m}{{%
    \def\@style##1{#1}%
    \@style{#3}%
}}
Hello \Foo{world}!
This is \Foo[\color{blue}\textbf{#1}]{nice}!

However, if I add one level of nesting, everything breaks:
\NewDocumentCommand\DeclareFoo{O{\emph{##1}}}{%
    \DeclareDocumentCommand\Foo{O{dummy} m}{{%
        \def\@style####1{#1}%
        \@style{##2}%
    }}%
}
\DeclareFoo% gets the #1 of \Foo instead of \@style
Hello \Foo{world}!
\DeclareFoo[\color{blue}\textbf{#1}]% same
This is \Foo{nice}!
\DeclareFoo[\color{red}\textbf{##1}]% this works but I would rather use only one "#"
This is \Foo{not nice}!

\DeclareFoo is supposed to be a black box, and the user is not supposed to guess the number of nesting levels (please do not mark this as a duplicate).
Is there a way to escape the # inside #1 argument?
I tried \StrSubstitute from the xstring package to double the number of # in #1,
but couldn't make it work...

A: For comparison: what we need to do in OpTeX:
\fontfam[lm]

\def\Foodeclared{}
\optdef\DeclareFoo[]{\ea\def \ea\Foodeclared \ea{\the\opt}}
\optdef\Foo[]#1{{\em \Foodeclared \the\opt #1}}

\DeclareFoo
Hello, \Foo{world}!

Hello, \Foo[\bf]{world}!

\DeclareFoo[\Blue\bf]%
This is \Foo{nice}!

\DeclareFoo[\Red\bf]%
Is this \Foo{nice, too}?

Is this \Foo[\Green\caps\rm]{nice, too}?

Is this \Foo{nice, too}?

\bye

The result is the same as in the Ulrich's answer.

A: With the \DeclareFoo definition, the default optional argument must have an extra pair of # tokens: O{\emph{####1}}, in order to make the default \emph case work.  Nonetheless, even here, you still need to use the ##1 notation when specifying a separate optional argument,  as in \DeclareFoo[\color{red}\textbf{##1}], because ##1 is required in \DeclareFoo to act as #1 in a subsequent invocation of \Foo.
\documentclass{article}
\usepackage{xcolor}
\begin{document}
\DeclareDocumentCommand\Foo{O{\emph{##1}} O{dummy} m}{{%
    \def\@style##1{#1}%
    \@style{#3}%
}}
Hello \Foo{world}!
This is \Foo[\color{blue}\textbf{#1}]{nice}!

\NewDocumentCommand\DeclareFoo{O{\emph{####1}}}{%
    \DeclareDocumentCommand\Foo{O{dummy} m}{{%
        \def\@style####1{#1}%
        \@style{##2}%
    }}%
}
\DeclareFoo% works
Hello \Foo{world}!
\DeclareFoo[\color{red}\textbf{##1}]% this works but I would rather use only one "#"
This is \Foo{required}!

\DeclareFoo[\color{blue}\textbf{#1}]% gets the #1 of \Foo instead of \@style
This \Foo{would be nice, but} doesn't work because \#\#1 is needed
  in DeclareFoo to produce \#1 in Foo!
\end{document}

A: In this specific case there are some "workarounds":

*

*In case you can tolerate some "global namespace pollution" you can do this

\documentclass{article}
\usepackage{xcolor}
\begin{document}

\makeatletter
\NewDocumentCommand\DeclareFoo{O{\emph{##1}}}{%
    \def\@foo@helper@style##1{#1}%
    \DeclareDocumentCommand\Foo{O{dummy} m}{%
        \@foo@helper@style{##2}%
    }%
}%

\DeclareFoo% gets the #1 of \Foo instead of \@style
Hello \Foo{world}!
\DeclareFoo[\color{blue}\textbf{#1}]%
This is \Foo{nice}!
\DeclareFoo[\color{red}\textbf{#1}]%
This is \Foo{not nice}!

\end{document}

As long as the helper macro's name is "sufficiently unique" it should not be a problem.

*

*As a alternative solution you can "pass" the content through the macro definition by storing it in an macro/token register:

\documentclass{article}
\usepackage{xcolor}
\begin{document}

\makeatletter
\ExplSyntaxOn
\NewDocumentCommand\DeclareFoo{O{\emph{##1}}}{
    \tl_set:Nn \@foo@helper@body {#1}
    \DeclareDocumentCommand\Foo{O{dummy} m}{
        \group_begin:
        \exp_args:NnV \use:n {\def\@foo@helper@style####1} \@foo@helper@body
        \@foo@helper@style{##2}
        \group_end:
    }
}
\ExplSyntaxOff

\DeclareFoo% gets the #1 of \Foo instead of \@style
Hello \Foo{world}!
\DeclareFoo[\color{blue}\textbf{#1}]%
This is \Foo{nice}!
\DeclareFoo[\color{red}\textbf{#1}]%
This is \Foo{not nice}!

\end{document}

The \exp_args:NnV \use:n is a bit ugly, but basically it executes the def with the variable as its "body".

A: Ad "programmatically double the number of #":
The discussions
How to have hashes doubled and things expanded?
and
Double hashes inside macro definition?
might be of interest to you.
There you find approaches to the matter using l3regex or taking advantage of the fact that things like \write and \scantokens double hashes.
For the sake of having fun I did my own thing with the code below.

For recent TeX engines where \detokenize of the ε-TeX extensions is available I can offer a routine \ReplicateEveryHash which can serve as a workaround in some situations.
Syntax of the routine \ReplicateEveryHash is
\ReplicateEveryHash{⟨number⟩}{⟨balanced text⟩}
The routine \ReplicateEveryHash by means of \romannumeral-expansion recursively replicates ⟨number⟩ times every explicit character token of category 6(parameter) that is contained in the ⟨balanced text⟩.
The gist of the check for a hash is: \string# delivers a single hash-character-token of category 12(other) while with \detokenize hash-doubling takes place and therefore \detokenize{#} delivers two hash-character-tokens of category 12(other). (The edge case of an explicit space character of category 6 needs separate treatment.)
In case the ⟨balanced text⟩-argument of \ReplicateEveryHash contains matching pairs of explicit character tokens of category 1(begin group) and 2(end group), each of these pairs triggers another level of \romannumeral-expansion. Therefore excessive nesting of braces within the ⟨balanced text⟩-argument of \ReplicateEveryHash will take its toll on the semantic nest.
Besides this \ReplicateEveryHash does replace matching pairs of explicit character tokens of category 1(begin group) and 2(end group) of the ⟨balanced text⟩-argument by matching pairs of opening curly braces of category 1 and closing curly braces of category 2.
I suppose this won't be a problem in most situations as usually the curly braces are the only characters of category 1/2.
But this must be mentioned because this means that \ReplicateEveryHash is suitable only for situations where replacing explicit begin-grouping-character-tokens and explicit end-grouping-character-tokens by explicit curly-brace-tokens of the same kind doesn't matter.
Caveats/possible pitfalls:
If you place \ReplicateEveryHash{2}{...} into an \edef, due to \romannumeral-expansion hash-doubling will—in contrast with the \edef\macro{\unexpanded\expandafter{\expanded{#1}}}-approach—take place before expanding the tokens that form the ⟨balanced text⟩-argument of \ReplicateEveryHash.  Therefore \edef\macro{\ReplicateEveryHash{2}{\string#1}} (or \ReplicateEveryHash{2}{\edef\macro{\string#1}} if you prefer) will yield an error-message about an illegal parameter number because in the hash-doubling-step you will get two hashes trailed by the digit 1. The first hash will be stringified. The second hash, which is trailed by the digit 1, will not be stringified and therefore will be taken for a parameter #1 while the ⟨parameter text⟩ of \macro is empty.
\makeatletter
%%//////////////  Begin of code for \ReplicateEveryHash  //////////////////////
%%=============================================================================
%% PARAPHERNALIA:
%%    \UD@stopromannumeral,
%%    \UD@firstoftwo, \UD@secondoftwo,
%%    \UD@PassFirstToSecond, \UD@Exchange, \UD@removespace
%%    \UD@CheckWhetherNull, \UD@CheckWhetherBrace,
%%    \UD@CheckWhetherLeadingExplicitSpace, \UD@replicate, \UD@ExtractFirstArg
%%=============================================================================
\@ifdefinable\UD@stopromannumeral{\chardef\UD@stopromannumeral=`\^^00}%
\newcommand\UD@firstoftwo[2]{#1}%
\newcommand\UD@secondoftwo[2]{#2}%
\newcommand\UD@PassFirstToSecond[2]{#2{#1}}%
\newcommand\UD@Exchange[2]{#2#1}%
\@ifdefinable\UD@removespace{\UD@firstoftwo{\def\UD@removespace}{} {}}%
%%-----------------------------------------------------------------------------
%% Check whether argument is empty:
%%.............................................................................
%% \UD@CheckWhetherNull{<Argument which is to be checked>}%
%%                     {<Tokens to be delivered in case that argument
%%                       which is to be checked is empty>}%
%%                     {<Tokens to be delivered in case that argument
%%                       which is to be checked is not empty>}%
%%
%% The gist of this macro comes from Robert R. Schneck's \ifempty-macro:
%% <https://groups.google.com/forum/#!original/comp.text.tex/kuOEIQIrElc/lUg37FmhA74J>
\newcommand\UD@CheckWhetherNull[1]{%
  \romannumeral\expandafter\UD@secondoftwo\string{\expandafter
  \UD@secondoftwo\expandafter{\expandafter{\string#1}\expandafter
  \UD@secondoftwo\string}\expandafter\UD@firstoftwo\expandafter{\expandafter
  \UD@secondoftwo\string}\expandafter\UD@stopromannumeral\UD@secondoftwo}{%
  \expandafter\UD@stopromannumeral\UD@firstoftwo}%
}%
%%-----------------------------------------------------------------------------
%% Check whether argument's first token is an explicit character of
%% category 1:
%%.............................................................................
%% \UD@CheckWhetherBrace{<Argument which is to be checked>}%
%%                      {<Tokens to be delivered in case that argument
%%                        which is to be checked has a leading
%%                        explicit catcode-1-character-token>}%
%%                      {<Tokens to be delivered in case that argument
%%                        which is to be checked does not have a
%%                        leading explicit catcode-1-character-token>}%
\newcommand\UD@CheckWhetherBrace[1]{%
  \romannumeral\expandafter\UD@secondoftwo\expandafter{\expandafter{%
  \string#1.}\expandafter\UD@firstoftwo\expandafter{\expandafter
  \UD@secondoftwo\string}\expandafter\UD@stopromannumeral\UD@firstoftwo}{%
  \expandafter\UD@stopromannumeral\UD@secondoftwo}%
}%
%%-----------------------------------------------------------------------------
%% Check whether brace-balanced argument starts with an explicit space-token:
%%.............................................................................
%% \UD@CheckWhetherLeadingExplicitSpace{<Argument which is to be checked>}%
%%                                     {<Tokens to be delivered in case <argument
%%                                       which is to be checked> does have a
%%                                       leading explicit space-token>}%
%%                                     {<Tokens to be delivered in case <argument
%%                                       which is to be checked> does not have a
%%                                       a leading explicit space-token>}%
\newcommand\UD@CheckWhetherLeadingExplicitSpace[1]{%
  \romannumeral\UD@CheckWhetherNull{#1}%
  {\expandafter\UD@stopromannumeral\UD@secondoftwo}%
  {%
    % Let's nest things into \UD@firstoftwo{...}{} to make sure they are nested in braces
    % and thus do not disturb when the test is carried out within \halign/\valign:
    \expandafter\UD@firstoftwo\expandafter{%
      \expandafter\expandafter\expandafter\UD@stopromannumeral
      \romannumeral\expandafter\UD@secondoftwo
      \string{\UD@CheckWhetherLeadingExplicitSpaceB.#1 }{}%
    }{}%
  }%
}%
\@ifdefinable\UD@CheckWhetherLeadingExplicitSpaceB{%
  \long\def\UD@CheckWhetherLeadingExplicitSpaceB#1 {%
    \expandafter\UD@CheckWhetherNull\expandafter{\UD@firstoftwo{}#1}%
    {\UD@Exchange{\UD@firstoftwo}}{\UD@Exchange{\UD@secondoftwo}}%
    {\expandafter\expandafter\expandafter\UD@stopromannumeral
     \expandafter\expandafter\expandafter}%
     \expandafter\UD@secondoftwo\expandafter{\string}%
  }%
}%
%------------------------------------------------------------------------------
% \UD@replicate{<number>}{<tokens>}
%------------------------------------------------------------------------------
\newcommand\UD@replicateloop[3]{%
  \if m#3\expandafter\UD@firstoftwo\else\expandafter\UD@secondoftwo\fi
  {\UD@replicateloop{#1}{#2#1}}{\UD@stopromannumeral#2}%
}%
\newcommand\UD@replicate[2]{%
  \romannumeral
  \expandafter\UD@Exchange\expandafter{\romannumeral\number\number#1 000}%
                                      {\UD@replicateloop{#2}{}}\relax
}%
%%=============================================================================
%% Extract first inner undelimited argument:
%%
%%   \UD@ExtractFirstArg{ABCDE} yields  {A}
%%
%%   \UD@ExtractFirstArg{{AB}CDE} yields  {AB}
%%
%% Due to \romannumeral-expansion the result is delivered after two
%% expansion-steps/after "hitting" \UD@ExtractFirstArg with \expandafter
%% twice.
%%
%% \UD@ExtractFirstArg's argument must not be blank.
%% This case can be cranked out via \UD@CheckWhetherBlank before calling
%% \UD@ExtractFirstArg.
%%
%% Use frozen-\relax as delimiter for speeding things up.
%% I chose frozen-\relax because David Carlisle pointed out in
%% <https://tex.stackexchange.com/a/578877>
%% that frozen-\relax cannot be (re)defined in terms of \outer and cannot be
%% affected by \uppercase/\lowercase.
%%
%% \UD@ExtractFirstArg's argument may contain frozen-\relax:
%% The only effect is that internally more iterations are needed for
%% obtaining the result.
%%
%%.............................................................................
\@ifdefinable\UD@RemoveTillFrozenrelax{%
  \expandafter\expandafter\expandafter\UD@Exchange
  \expandafter\expandafter\expandafter{%
  \expandafter\expandafter\ifnum0=0\fi}%
  {\long\def\UD@RemoveTillFrozenrelax#1#2}{{#1}}%
}%
\expandafter\UD@PassFirstToSecond\expandafter{%
  \romannumeral\expandafter
  \UD@PassFirstToSecond\expandafter{\romannumeral
    \expandafter\expandafter\expandafter\UD@Exchange
    \expandafter\expandafter\expandafter{%
    \expandafter\expandafter\ifnum0=0\fi}{\UD@stopromannumeral#1}%
  }{%
    \UD@stopromannumeral\romannumeral\UD@ExtractFirstArgLoop
  }%
}{%
  \newcommand\UD@ExtractFirstArg[1]%
}%
\newcommand\UD@ExtractFirstArgLoop[1]{%
  \expandafter\UD@CheckWhetherNull\expandafter{\UD@firstoftwo{}#1}%
  {\UD@stopromannumeral#1}%
  {\expandafter\UD@ExtractFirstArgLoop\expandafter{\UD@RemoveTillFrozenrelax#1}}%
}%
%%=============================================================================
%% \ReplicateEveryHash{<number>}{<balanced text>}%
%%
%%   Each explicit category-6(parameter)-character-token of the
%%   <balanced text> is replicated <number> times.
%%
%%   You obtain the result after two expansion-steps, i.e.,
%%   in expansion-contexts you get the result after "hitting"
%%   \ReplicateEveryHash by two \expandafter.
%%
%%   As a side-effect, the routine does replace matching pairs of explicit
%%   character tokens of catcode 1 and 2 by matching pairs of curly braces
%%   of catcode 1 and 2.
%%   I suppose this won't be a problem in most situations as usually the
%%   curly braces are the only characters of category code 1 / 2...
%%
%%   This routine needs \detokenize from the eTeX extensions.
%%-----------------------------------------------------------------------------
\newcommand\ReplicateEveryHash[2]{%
   \romannumeral
   \expandafter\UD@PassFirstToSecond\expandafter{%
   \romannumeral\number\number#1 000}{%
     \UD@ReplicateEveryHashLoop{#2}{}%
   }%
}%
\newcommand\UD@ReplicateEveryHashLoop[3]{%
  \UD@CheckWhetherNull{#1}{\UD@stopromannumeral#2}{%
    \UD@CheckWhetherLeadingExplicitSpace{#1}{%
       \expandafter\UD@ReplicateEveryHashLoop
       \expandafter{\UD@removespace#1}{#2 }{#3}%
    }{%
      \UD@CheckWhetherBrace{#1}{%
        \expandafter\expandafter\expandafter\UD@PassFirstToSecond
        \expandafter\expandafter\expandafter{%
        \expandafter\UD@PassFirstToSecond\expandafter{%
            \romannumeral%
            \expandafter\expandafter\expandafter\UD@ReplicateEveryHashLoop
            \UD@ExtractFirstArg{#1}{}{#3}%
        }{#2}}%
        {\expandafter\UD@ReplicateEveryHashLoop
         \expandafter{\UD@firstoftwo{}#1}%
        }{#3}%
      }{%
        \expandafter\expandafter\expandafter\UD@CheckWhetherHash
        \UD@ExtractFirstArg{#1}{#1}{#2}{#3}%
      }%
    }%
  }%
}%
\newcommand\UD@CheckWhetherHash[4]{%
  \expandafter\UD@CheckWhetherLeadingExplicitSpace\expandafter{\string#1}{%
    \expandafter\expandafter\expandafter\UD@CheckWhetherNull
    \expandafter\expandafter\expandafter{%
    \expandafter\UD@removespace\string#1}{%
      \expandafter\expandafter\expandafter\UD@CheckWhetherNull
      \expandafter\expandafter\expandafter{%
      \expandafter\UD@removespace\detokenize{#1}}{%
        % something whose stringification yields a single space
        \UD@secondoftwo
      }{% explicit space of catcode 6
        \UD@firstoftwo
      }%
    }{% something whose stringification has a leading space
      \UD@secondoftwo
    }%
  }{%
    \expandafter\expandafter\expandafter\UD@CheckWhetherNull
    \expandafter\expandafter\expandafter{%
    \expandafter\UD@firstoftwo
    \expandafter{\expandafter}\string#1}{%
      \expandafter\expandafter\expandafter\UD@CheckWhetherNull
      \expandafter\expandafter\expandafter{%
      \expandafter\UD@firstoftwo
      \expandafter{\expandafter}\detokenize{#1}}{%
        % no hash
        \UD@secondoftwo
      }{% hash
        \UD@firstoftwo
      }%
    }{% no hash
      \UD@secondoftwo
    }%
  }%
  {% hash
    \expandafter\UD@PassFirstToSecond
    \expandafter{%
      \romannumeral\expandafter
      \UD@Exchange\expandafter{%
        \romannumeral\UD@replicateloop{#1}{}#4\relax
      }{\UD@stopromannumeral#3}%
    }{%
      \expandafter\UD@ReplicateEveryHashLoop
      \expandafter{\UD@firstoftwo{}#2}%
    }%
  }{% no hash
    \expandafter\UD@ReplicateEveryHashLoop
    \expandafter{\UD@firstoftwo{}#2}{#3#1}%
  }{#4}%
}%
%%=============================================================================
%%//////////////  End of code for \ReplicateEveryHash  ////////////////////////
\makeatother

\documentclass{article}
\usepackage[dvipsnames]{xcolor}

\makeatletter
\NewDocumentCommand\DeclareFoo{O{\emph{##1}}}{%
    % \DeclareFoo's #1 denotes the tokens that form
    % \Foo's default-definition-text of the macro
    % \@style.
    % At the time of carrying out \DeclareFoo the
    % definition-text of \@style is a second-level-
    % definition where hashes of macro-parameters need
    % to be doubled.
    % Therefore hashes in \DeclareFoo's #1, which denotes
    % a possible definition-text of \@style, need to be
    % doubled, otherwise the user has to do so when
    % specifying a non-default value for \DeclareFoo's
    % optional argument/a non-default definition-text for
    % the second-level-definition of \@style.
    \ReplicateEveryHash{2}{\DeclareDocumentCommand\Foo{O{#1} m}}{{%
        \def\@style####1{##1}%
        \@style{##2}%
    }}%
    % The following might be better for keeping the
    % definition of \@style local because \@style isn't
    % (re)defined any more when its replacement-text is
    % carried out:
    % \ReplicateEveryHash{2}{\DeclareDocumentCommand\Foo{O{#1} m}}{{%
    %     \begingroup
    %     \def\@style####1{\endgroup##1}%
    %     \@style{##2}%
    % }}%
}
\makeatother

\begin{document}

\DeclareFoo
Hello, \Foo{world}!

Hello, \Foo[\textbf{#1}]{world}!

\DeclareFoo[\color{blue}\textbf{#1}]%
This is \Foo{nice}!

\DeclareFoo[\color{red}\textbf{#1}]%
Is this \Foo{nice, too}?

Is this \Foo[\color[named]{ForestGreen}\textsc{#1}]{nice, too}?

Is this \Foo{nice, too}?

\end{document}


text:
Q: Strange Sybase / SQL Server linked server issue I have a sybase table which has a column note varchar(1000) null.
The following T-SQL will get the following error if there is a not-null value in note. (sybase is the linked server to the Sybase database)
select * from (sybase, 'select note from table')
select * from (sybase, 'select left(note, 257) note from table')
select * from (sybase, 'select left(note, 1000) note from table')

OLE DB provider 'ASEOLEDB' for linked server 'sybase' returned data
  that does not match expected data length for column '[ASEOLEDB].note'.
  The (maximum) expected data length is 257, while the returned data
  length is 258.

However, it works if the length parameter is less and equal to 256.
select * from (sybase, 'select left(note, 256) note from table')

Also the following SQL works.
exec ('select note from table') at [sybase]

Is it a bug of the Sybase driver?

A: try
select * from OPENQUERY(sybase, 'select left(cast(note as varchar(1000)), 257) note from table')


text:
Q: Is it possible to bind to a Java Service, from a Native c++ client, and transact, receive data from the service? I'm currently studying how binders work in general.
By looking at the following projects :
https://github.com/qianjigui/android_system_service_example
https://github.com/cloudchou/NativeBinderJavaClientDemo
I understand that binder transaction is possible in

*

*Native Service <-> Java Client

*Native Service <-> Native Client

*Java Service <-> Java Client

One last question that keeps bugging me is, is the following possible...?

*

*Java Service <-> Native Client

I can't find any articles or code that actually implement this, neither people discussing about the possibility of it. From what I understand is the transaction is based purely on the .aidl description, so the implementation language doesn't matter so the above should be possible. But I just want to be sure...

A: I think it can hardly use a native binder client, since binder API is not part of NDK. Here's a reference link:How to Create a android native service and use binder to communicate with it?
However, if you can get the ASOP all source codes, and use the android built tools, it will get possible.

A: With NDK binder API it became possible (available from Android 10), but service still cannot be started/bound from native code (without using private APIs).
https://developer.android.com/ndk/reference/group/ndk-binder

A: It is fully possible: Binder crosses process boundaries, so the programming language used to implement the service or its caller is irrelevant. You can see native client -> java service easily, by using "service call" (for fun, try "service call phone 2 s16 555-1234" to bring up the dial window, or "service call statusbar 1", "service call statusbar 2", etc.  The transaction does not require AIDL - AIDL merely creates the boilerplate code to facilitate it.
Note, however, that if you want to deal with Java objects, you'd need to do the "parceling" (serialization) yourself. That is, figure out what the Parcelable interface ordering is (in the  readFromParcel), and then lay the primitive types (uint32_t, float, String, etc) one by one.


text:
Q: Approximating arcsin from above I am very new to function approximations, and I am interested in approximating arcsin with a function $f$, s.t. $f(x) \geq \arcsin(x)$ for all $x$.
Taylor series would give me a function which is always at most $\arcsin(x)$, but I am wondering if there are maybe some trigonometric identities with which I can obtain a desired approximation.

A: For $0<x<\pi/2$ there is $\sin x<x<\tan x$, so for these $x$, an upper bound is
$$\arcsin(x)<\arcsin(\tan(x)),$$
while for $-\pi/2<x<0$ there is $\tan x<x<\sin x$, so for these $x$ an upper bound is
$$\arcsin(x)<x.$$
It looks like there is not a "simple" function which does the job on both sides of $0$ using the same formula. And also $\arcsin(\tan(x))$ is more complicated than the function you're trying to bound. Still, the taylor series for it may give a polynomial upper bound for $x>0$ [I haven't checked this].
EDIT: I just found some terms of the taylor series of $\arcsin(\tan(x))$. It starts out
$$x+(1/2)x^3+(3/8)x^5+(83/240)x^7+...$$
This will be greater than $\arcsin(x)$ if we use all the terms; if one wants the best upper bound from this, clearly one should not keep adding positive terms, but stop as soon as the series "beats" the series for $\arcsin(x)$. I haven't checked, but it looks like all we get from the taylor series for $\arcsin(\tan(x))$ is the simple statement
$$\arcsin(x)<x+(1/2)x^3,$$
which seems to hold for reasonably small positive $x$.
I guess what one would really want is a sequence of upper bounds that converged down to $\arcsin x$ for positive $x$. I don't know how to construct that.


text:
Q: Error MSB4185: "System.Globalization.CultureInfo" has not been enabled for execution When trying to build in MonoDevelop with Mono for Android I get this error. According to the debug it is not located in my code so im left clueless. Any idea?

Error MSB4185: The function "CurrentUICulture" on type
  "System.Globalization.CultureInfo" has not been enabled for execution.
  (MSB4185)

A: I own MSBuild (and this code). It's an error originating in the file microsoft.csharp.targets, as the error message probably says. In there is a property function:
$([System.Globalization.CultureInfo]::CurrentUICulture.Name)
What the error means is that it thinks that this function isn't in MSBuild's "safe list". These are selected functions that have no side effects. (If you want to use any function, you must have an environment variable MSBUILDENABLEALLPROPERTYFUNCTIONS=1).
I really don't know why this would appear unless somehow you're using the 4.5 microsoft.csharp.targets with the 4.0 microsoft.build.dll (which didn't have it in the safe list). I haven't received reports of this except in connection with Monodevelop.
Excuse my naivety, but I'm assuming Monodevelop is using the Microsoft .NET Framework with the Microsoft MSBuild and not a reimplementation of that.
Dan

A: The working solution for me is this:
Open a CMD and run this command on it: setx MSBUILDENABLEALLPROPERTYFUNCTIONS 1
Another solution I think is available is installing Mono Runtime and set it as your default CLR runtime from Tools -> Options -> .NET Runtimes.

A: After uninstalling .NET Framework 4.5 RC from my Windows 7 machine, this error disappeared.
Of course make sure you have valid .NET runtime after you uninstall 4.5.


text:
Q: bash variable expansion as parameter I have a command (zip, but nevermind) in which I have a parameter like
cmd /foo/bar/{*.php,*.css,images/}

I would like to put it in a variable to pass it to the command as :
VAR=/foo/bar/{*.php,*.css,images/}
cmd ${VAR}

But, whatever I try, it never expand as I want. I tried with or without quotes, but not better.
EDIT:
(No answer possible because closed)
I hadn't been able to find it, but the solution did exist:
VAR=(/foo/bar/{*.php,*.css,images/})
cmd ${VAR[@]}


text:
Q: Segmentation fault (core dumped) error not resolved #include<iostream>
#include<cstdlib>
using namespace std;

int main(){

int i,n;
char * buffer=NULL;
i=0;
cout<<"enter the character length you wish to store dynamically"<<endl;
cin>>i;

buffer= (char*) malloc(i+1);
if(buffer=NULL)
exit(1);
for(n=0;n<i;++n)
buffer[n]=rand()%26+'a';
buffer[i]='\0';

cout<<"the string is "<<buffer<<endl;
free(buffer);
return 0;}

I am getting segmentation fault:
Output:
enter the character length you wish to store dynamically
5
Segmentation fault (core dumped)
I am not able to figure out the mistake I did?
I tried to run in debugger mode,but there were no core file generated for it.?
Please suggest a solution to it.

A: buffer=NULL is an assignment. It will be evaluated as false and buffer[n]=rand()%26+'a'; will dereference the assigned NULL.
Do comparision buffer==NULL instead.


text:
Q: Multiple security realms I tried having multiple security realms in my application, but I get exception during deployment:

Message: Multiple login-config elements detected

web.xml fragment:
....
<security-constraint>
    <display-name>Admin Constraint</display-name>
    <web-resource-collection>
        <web-resource-name>Admin Pages</web-resource-name>
        <description/>
        <url-pattern>/admin/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
        <description/>
        <role-name>admin</role-name>
    </auth-constraint>
</security-constraint>
<login-config>
    <auth-method>BASIC</auth-method>
    <realm-name>ApplicationRealm</realm-name>
</login-config>
<login-config>
    <auth-method>FORM</auth-method>
    <realm-name>mb-domain</realm-name>
</login-config>
<security-role>
    <description/>
    <role-name>admin</role-name>
</security-role>
<security-role>
    <description/>
    <role-name>user</role-name>
</security-role>
...

What am I doing wrong?

A: Only one <login-config> can be used per web module deployment descriptor.
According to §14.2 of the Servlet Specification v. 3.1:

Rules for Processing the Deployment Descriptor
[...]

*

*The sub elements under web-app can be in an arbitrary order in this version of the specification. Because of the restriction of XML Schema, The multiplicity of the elements distributable, session-config, welcome-file-list, jsp-config, login-config, and locale-encoding-mapping-list was changed from "optional" to "0 or more". The containers must inform the developer with a descriptive error message when the deployment descriptor contains more than one element of session-config, jsp-config, and login-config.

Alternatives:

*

*Use programmatic authentication (based on either JASPIC or whatever facilities your Java EE / Servlet implementation offers).

*Use EAR packaging (if a single authentication strategy per module is acceptable).

*Drop container-managed authentication.


text:
Q: How can I simplify in Matlab? I want to simplify the following operation, but it yields me an error that says: too many input arguments. Can anybody tell me what am i doing wrong???
>>
syms a b c d e  f g h i j k l x y xy

A=[1 a b a^2 a*b b^2; 1 c d c*2 c*d d^2; 1 e f e^2 e*f f^2; 1 g h g^2 g*h h^2; 1 i j         i^2 i*j j^2; 1 k l k^2 k*l l^2]

B=[1; 0; 0; 0; 0; 0]

A =

[ 1, a, b, a^2, a*b, b^2]
[ 1, c, d, 2*c, c*d, d^2]
[ 1, e, f, e^2, e*f, f^2]
[ 1, g, h, g^2, g*h, h^2]
[ 1, i, j, i^2, i*j, j^2]
[ 1, k, l, k^2, k*l, l^2]

B =

 1
 0
 0
 0
 0
 0

>> simplify(inv(A)*B, 'steps', 100)enter code here

A: I've put the code you pasted in my copy of matlab (R2013a) and it finishes without any errors. The result is not simplified very much though.
If your computer is choking on the computation (it is very long), you could try separating the things a bit and see if it helps.
vec=inv(A)*B
for n=1:6
    results(n)=simplify(vec(n), 'steps', 100);
end
results

A: Your call belongs to this MATLAB function:
But it is in Symbolic Math Toolbox, which means it can only simplify math formulas instead of complex matrix computation.
Simplify Favoring Real Numbers

To force simplify favor real values over complex values, set the value of Criterion to preferReal:

syms x
f = (exp(x + exp(-x*i)/2 - exp(x*i)/2)*i)/2 - (exp(- x - exp(-x*i)/2 + exp(x*i)/2)*i)/2;
simplify(f, 'Criterion','preferReal', 'Steps', 100)
ans =
cos(sin(x))*sinh(x)*i + sin(sin(x))*cosh(x)
If x is a real value, then this form of expression explicitly shows the real and imaginary parts.

Although the result returned by simplify with the default setting for Criterion is shorter, here the complex value is a parameter of the sine function:

simplify(f, 'Steps', 100)
ans =
sin(x*i + sin(x))

Instead, I think you could try use this function:
Simplify(f, Steps = numberOfSteps)
But first of all, you need a 'f' which could be used like a recursion or iteration function.
e.g. Simplify(sin(x)^2 + cos(x)^2, All)
Hope this helps!


text:
Q: What is the simplest way to fix an existing csv unicode utf-8 without BOM file not displaying correctly in excel? I have the task of converting utf-8 csv file to excel file, but it is not read properly in excel. Because there was no byte order mark (BOM) at the beginning of the file

I see how:
https://stackoverflow.com/a/38025106/6102332
    with open('test.csv', 'w', newline='', encoding='utf-8-sig') as f:
        w = csv.writer(f)
        # Write Unicode strings.
        w.writerow([u'English', u'Chinese'])
        w.writerow([u'American', u'美国人'])
        w.writerow([u'Chinese', u'中国人'])

But it seems like that only works with brand new files.
But not work for my file already has data.
Are there any easy ways to share?
Is there any other way than this? : https://stackoverflow.com/a/6488070/6102332

*

*Save the exported file as a csv

*Open Excel

*Import the data using Data-->Import External Data --> Import Data

*Select the file type of "csv" and browse to your file

*In the import wizard change the File_Origin to "65001 UTF" (or choose correct language character identifier)

*Change the Delimiter to comma

*Select where to import to and Finish

A: Read the file in and write it back out with the encoding desired:
with open('input.csv','r',encoding='utf-8-sig') as fin:
    with open('output.csv','w',encoding='utf-8-sig') as fout:
        fout.write(fin.read())

utf-8-sig codec will remove BOM if present on read, and will add BOM on write, so the above can safely run on files with or without BOM originally.
You can convert in place by doing:
file = 'test.csv'

with open(file,'r',encoding='utf-8-sig') as f:
    data = f.read()

with open(file,'w',encoding='utf-8-sig') as f:
    f.write(data)

Note also that utf16 works as well.  Some older Excels don't handle UTF-8 correctly.

A: Thank You!
I have found a way to automatically handle the missing BOM utf-8 signature.
In addition to the lack of BOM signature, there is another problem is that duplicate BOM signature is mixed in the file data. Excel does not show clearly and transparently. and make a mistake other data when compared, calculated. eg :
data -> Excel
Chinese -> Chinese
12 -> 12
If you compare it, obviously ChineseBOM will not be equal to Chinese.
Code python to solve the problem:
import codecs
bom_utf8 = codecs.BOM_UTF8

def fix_duplicate_bom_utf8(file, bom=bom_utf8):
    with open(file, 'rb') as f:
        data_f = f.read()

    data_finish = bom + data_f.replace(bom, b'')

    with open(file, 'wb') as f:
        f.write(data_finish)
    return

# Use:
file_csv = r"D:\data\d20200114.csv" # American, 美国人

fix_duplicate_bom_utf8(file_csv)
 # file_csv  -> American, 美国人


text:
Q: if and elseif issue in codeigniter I am trying to calculate the incentive for the people with designation as Assistant Managers and Senior Executives. So, I need to give 1% of the total amount to the Senior Executives and 1.5% to the managers. So, while writing the if, elseif conditions for the same in codeigniter view. Only the if condition is working and elseif conditiion is not working. Since, I am new to codeigniter, please help me out with this.
$amount = 0;

if (isset($target_revenue[0]['target'])) {
    $amount = $get_rev / $target_revenue[0]['target'] * 100; {
        if ($amount > 100 && $designation = "Assistant Manager") {

            $get_rev1 = ($get_rev - $target_revenue[0]['target']) * 0.015;
        } else if ($amount > 100 && $designation = "Senior Executive") {

            $get_rev1 = ($get_rev - $target_revenue[0]['target']) * 0.01;
        }

    }
}

A: Inside both if conditions you need to add '==' instead of '='. And you can check your code syntax here if you need.
$amount = 0;

if (isset($target_revenue[0]['target'])) {
    $amount = $get_rev / $target_revenue[0]['target'] * 100; {
        if ($amount > 100 && $designation == "Assistant Manager") {

            $get_rev1 = ($get_rev - $target_revenue[0]['target']) * 0.015;
        } else if ($amount > 100 && $designation == "Senior Executive") {

            $get_rev1 = ($get_rev - $target_revenue[0]['target']) * 0.01;
        }

    }
}

A: **Try This: **
I don't know will it be helpful or not
$amount = 0;

if (isset($target_revenue[0]['target'])){
    $amount = $get_rev / $target_revenue[0]['target'] * 100;
if ($amount > 100 && $designation = "Assistant Manager") {
    $get_rev1 = ($get_rev - $target_revenue[0]['target']) * 0.015;
} else if ($amount > 100 && $designation = "Senior Executive") {
    $get_rev1 = ($get_rev - $target_revenue[0]['target']) * 0.01;
}

}


text:
Q: SSH tunnel with only destination password (instead of two passwords)? I have a destination server running Ubuntu 14.04 (let's call it destserver) and a tunnel server also running Ubuntu 14.04 (let's call it bridgeserver), which has a fixed IPV4 address. I have it currently set up so at boot, destserver uses autossh to connect to bridgeserver:
exec autossh -M 0 -N -R 2222:localhost:22 -o "ServerAliveInterval 60" -o "ServerAliveCountMax 3" -o "StrictHostKeyChecking=no" -o "BatchMode=yes" -i /path/to/bridgeserver_mybridgeuser_id_rsa mybridgeuser@BRIDGESERVER_IP_ADDR

I'm using key authentication here, so the above command can complete without passwords. Now, when I'm on my laptop on a public network somewhere, now I can do from it:
ssh -t -o ProxyCommand='ssh mybridgeuser@BRIDGESERVER_IP_ADDR nc localhost 2222' mydestuser@localhost

... and this works fine, except it asks me for two sets of passwords:
$ ssh -t -o ProxyCommand='ssh mybridgeuser@BRIDGESERVER_IP_ADDR nc localhost 2222' mydestuser@localhost
mybridgeuser@BRIDGESERVER_IP_ADDR's password:
mydestuser@localhost's password:
Welcome to Ubuntu 14.04.5 LTS (GNU/Linux 4.2.0-42-generic x86_64)
...

Now, I'd like to make this destination server available to other people, but I don't want to share any authentication details of the bridge server (which I rent personally), and thus I don't want to share the password of mybridgeuser. So I'd like to establish a connection like the above - except where I'm asked only about the password of the user (say mydestuser) at destserver.
Is there an ssh syntax that I could use on the client, so I can connect to destserver using only user credentials from destserver (without a password prompt from bridgeserver), without changes to the current setup with autossh? If changes to the setup are needed, what would the changes to the setup be - and how would the ssh command on the laptop look like?

A: Hm, I might be wrong about this, but I just wrote in this in my init file:
exec autossh -M 0 -N -R :2222:localhost:22 -o "ServerAliveInterval 60" -o "ServerAliveCountMax 3" -o "StrictHostKeyChecking=no" -o "BatchMode=yes" -i /path/to/bridgeserver_mybridgeuser_id_rsa mybridgeuser@BRIDGESERVER_IP_ADDR

... instead of:
exec autossh -M 0 -N -R 2222:localhost:22 -o "ServerAliveInterval 60" -o "ServerAliveCountMax 3" -o "StrictHostKeyChecking=no" -o "BatchMode=yes" -i /path/to/bridgeserver_mybridgeuser_id_rsa mybridgeuser@BRIDGESERVER_IP_ADDR

... notice, I just added a colon before what used to be the 2222:localhost:22; and now on the laptop I can issue just:
ssh mydestuser@BRIDGESERVER_IP_ADDR -p 2222

... and it seems to work now, as it is only asking me for one password:
$ ssh mydestuser@BRIDGESERVER_IP_ADDR -p 2222
mydestuser@BRIDGESERVER_IP_ADDR's password:
Welcome to Ubuntu 14.04.5 LTS (GNU/Linux 4.2.0-42-generic x86_64)
...

... whereas previously it didn't let me do that?!:
$ ssh mydestuser@BRIDGESERVER_IP_ADDR -p 2222
ssh: connect to host BRIDGESERVER_IP_ADDR port 2222: Connection refused

I'm not sure why this colon was needed, so I'd still like to read a proper answer about that...


text:
Q: C# XNA Lidgren client receives messages incorrectly I'm trying to make a simple server and client with Lidgren. The server is a C# console application and the client is made using XNA. The problem is when the client receives a message from the server, when it reads 2 floats it reads them as 0 (I'm assuming) even though they aren't sent like that.
Server: http://pastebin.com/s2cmBUf3
Client: http://pastebin.com/nrU7KFs8


text:
Q: Administering EC2 instance with Windows Powershell I'm having trouble administering a Windows 2k8 Server SP2 instance (hosted on EC2) with powershell from my Windows 7 client. When I try to run:
Invoke-Command {Get-Service} -ComputerName ec2-184-73-111-34.compute-1.amazonaws.com

I receive the following error:

Connecting to remote server failed
  with the following error message : The
  WinRM client cannot complete the
  operation within the time specified.
  Check if the machine name is valid and
  is reachable over the network and
  firewall exception for Windows Remote
  Management service is enabled. For
  more information, see the
  about_Remote_Troubleshooting Help
  topic.

On the server I have: (1) Connected with RDP (the server is reachable), and (2) run Enable-PSRemoting
On my client I have: (1) Added the EC2 instance to TrustedHosts
I've also tried running the above command on the server with the Windows firewall completely disabled, but that didn't solve the problem either. I've also verified there's a firewall exception for Windows Remote Management.
The tutorial I've been referencing is:
http://blogs.iis.net/thomad/archive/2010/08/12/managing-windows-amazon-ec2-machines-remotely-with-powershell.aspx

A: On EC2, you need to open port 5985, the default WinRM remoting port on your security group so that you can connect to the instance from your IP address.
On the instance in the cloud, do a:
winrm quickconfig -quiet

On your workstation:
set-item wsman:\localhost\Client\TrustedHosts -value "*" -force
Invoke-Command {Get-Service} -ComputerName <hostname> -Credential administrator

And that should get you going.

A: Both of those machines must be on the same domain.  I don't see how you have accomplished that.  "On my client I have: (1) Added the EC2 instance to TrustedHosts." does not suffice.  You would need to add the EC2 server to your ground based Domain, or have the EC2 server be the domain controller for that Windows7 client.
Another approach to "managing" that EC2 server from the ground would be to utilize PsExec.exe from Microsoft's "SysInternals" collection of utilities.  You would find that gem in their "PsTools" bundle of free tools.  So, on the Microsoft download site appropriate for you, search for PsTools and PsExec is in there.
PsExec let's you remotely control machines that are outside of your domain.

A: Just because RDP is authorized doesn't mean other services are. You have to allow access to ports on a target system port by port using ec2-authorize. What port does powershell use to talk to a target system? Did you authorize that port?


text:
Q: Tooling API workflow Email alert update I am trying to update workflow email alerts via Tooling API, My request is:
req.setBody('{"fullName": "Test","Metadata": {"description": "Updated via WorkBench"}}');
As "Only the Metadata and FullName fields may be specified on ActionEmail".
But without the other fields like Template ID etc the request is not getting created with error:

Mandatory fields are missing

And if we tend to add those fields, we get the same error stated above. Does anyone have any idea or sample code on this please?
Thanks

A: If you create workflowalert within salesforce UI and then pull it, you could see Json body example.
GET /tooling/sobjects/WorkflowAlert/{id}

In your example, first error is:

"message": "Required field is missing: template"

But we could see same field in metadata. I went step by step through errors and got next Json for update call:
{
    "Metadata": {
        "senderType": "CurrentUser",
        "description": "Updated via WorkBench",
        "template": "unfiled$public/MarketingProductInquiryResponse",
        "recipients": [{
            "field": null,
            "recipient": "xxx@xxx.com",
            "type": "user"
        }]
    }
}

Where template should be valid name, sendertype - valid picklist value etc.
If you send patch, you should get http 204 and updated record in SF.
PATCH /tooling/sobjects/WorkflowAlert/{Id}


text:
Q: Date Range Picker loses range when closed I am struggling with an issue.  I want to close the date range picker when a user starts scrolling down the page.  I am using this plugin to create the date range picker:
http://www.daterangepicker.com/
$(function() {
$('input[name="daterange"]').daterangepicker({
    timePicker: true,
    timePickerIncrement: 30,
    locale: {
        format: 'MM/DD/YYYY h:mm A'
    },
    ranges: {
       'Today': [moment(), moment()],
       'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
       'Last 7 Days': [moment().subtract(6, 'days'), moment()],
       'Last 30 Days': [moment().subtract(29, 'days'), moment()],
       'This Month': [moment().startOf('month'), moment().endOf('month')],
       'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
    }
});

$(window).scroll(function() {
    if ($('input[name="daterange"]').length) {
        $('input[name="daterange"]').daterangepicker("close");
  }
});

});
I've created a fiddle to show the issue:
https://jsfiddle.net/ccgorman/rLnycn80/
I have a bit of JS that closes the date range picker when the user scrolls, but as you can see, when you scroll back up and open it up again all the buttons, like Today, Yesterday...are gone, any idea how I close the picker without losing these buttons?

A: Change this line:
$('input[name="daterange"]').daterangepicker("close");
with:
$('input[name="daterange"]').data('daterangepicker').hide();


text:
Q: Bootstrap: Auto arrange components without offset When resizing the window so that some components don't fit on the same line anymore, they are pushed onto the next line, but with an offset. How do I get rid of that?

      <input type="checkbox"> Check me out

      <input type="checkbox"> Check me out

Just for clarification, I like the behavior the way it is, I just want to get rid of that offset.

A: If you take a look into the bootstrap.css, then you'll see the following lines:
.checkbox-inline + .checkbox-inline, .radio-inline + .radio-inline {
    margin-left: 10px;
    margin-top: 0;
}

The important Thing is the "+"-operator.
.checkbox-inline + .checkbox-inline

This means, that every ".checkbox-inline"-element that follows directly another ".checkbox-inline"-element, will have a margin of 10px to its left.
So a possible solution could be the Manipulation of the css-file. But another thing, you could do, is adding empty "span"-Elements between the checkboxes.

  <input type="checkbox">Check me out

  <input type="checkbox">Check me out

I hope, this was helpful.


text:
Q: Disable callbacks in PhantomJS (Javascript) I am using PhantomJS for a UI testing framework in C#. I am trying to click an element, which displays a confirm box, in one action and then return to the calling C# with the confirm box still open. Then, I am trying to call back into PhantomJS to click 'OK' on the dialog box in a second action.
The problem is that there is a callback attached to the confirm box which returns true/false (OK/Cancel), so the default behaviour just cancels the confirm box. I can attach my own custom callback, taking the message passed to the actual ( var result = confirm('message') ) call, like so:
page.onConfirm = function(msg) {
    console.log('Confirmation box showing for: ' + msg);
    return someBooleanValue;
}

But because of the truthy/falsey stuff in javascript, whatever I return here will either OK or cancel the confirm dialog - I can't seem to just leave it open.
It's worth mentioning that I am trying to still to plain javascript as opposed to introducing JQuery because it is a testing framework.
Any ideas how I do this?

A: For the benefit of anyone having the same issue, essentially the answer is that you can't do this. I just wound up having to define a default behaviour for these callbacks.


text:
Q: How to use same header for multiple page inside same html file I want to make an iPad HTML5/CSS3 based app and I found out about JQuery Mobile and tried to use it. Here what it looks like :

This is the summary page, when a user clicks on one of the grid element it should go to the proper detail page. (Click on grid "a" should go to an inner page with id "blockA" etc...).
I encoutered some problems and cannot find any clear clues on the net.

*

*I want my header + photo and summary + "informations" bar to be fixed. The only solution I found is to copy/paste the header div into my "blockA" page and into the 5 others which I found really annoying. Basically I want my top screen to be fixed and my bottom screen to change on link navigation. I thought of using jquery append methods and such but is there any "native" way of doing so?

*My header was really hard to bring like you can see it on the picture. I had to change the CSS a bit. Is there any easier way? Some class I missed in the JQuery structure CSS maybe? Can't find any exhaustive class list for JQM.

*How to set heights for my different components without modifying CSS.

Here is some of my HTML code :

Dossier de Mr. XXXXXXX

Mr. Whatever X

whatever.x@mail.com

09/03/1984

0450090909

1656486m

Ingénieur débutant

Status

Company

Employé depuis 01/09/2010

Informations

                    a

                    b

                    c

                    d

                    e

                    f

Dossier de Mr. XXXXXXX

Mr. Whatever X

whatever.x@mail.com

09/03/1984

0450090909

1656486m

Ingénieur débutant

Status

Company

Employé depuis 01/09/2010

Informations

        mon bloc A

Don't look at the ptaGetUser spans, it's for my later persistence framework that I should work on to add seamless persistence to HTML pages like this. For now though this is just here for nothing. I've also only added the first block for this exemple.
My CSS to make this the right dimension :
.ui-title,.ui-title
{
    height:24px;
}

.banner
{
    height:45px;
    padding: 0px 15px !important;
}

.ui-li-thumb, .ui-li-icon {
    max-width:165px;
    max-height:165px;
}

.pta-file-content
{
    height:148px;
}

.ui-li-has-thumb
{
    padding-left: 165px !important;
}
.ui-grid-a
{
    padding-top: 5px;
}
.ui-grid-b
{
    height:543px;
    width: 1022px;
}

.ui-grid-b .ui-block-a, .ui-grid-b .ui-block-b,.ui-grid-b .ui-block-c
{
    height:50%;
    width:32%;
    border: 1px solid black;
}

The whole screen slides when I click on the first grid element to show the page. As you can see I've copied the whole header into my second page div which is really bad for code readability. I also have CSS problems with my grid borders as it doesn't show bottom borders, how can I add borders to a grid without modifying CSS?

A: 1) jQuery Mobile doesn't currently offer persistent headers and footers, but an upcoming version, 1.1, will. Whether or not they stay on the page during transitions is something that has not yet been answered. Your best bet is to use some sort of server-side language for your pages, then set the header as an include. That way you don't have to copy and paste across multiple pages.
2) jQuery Mobile is great for building apps, but to get something truly custom, you've got to write it yourself; be that CSS or HTML or both.
3) Only way to achieve custom heights for your elements is to write custom CSS.

A: It sounds like you are trying to do a lot without modifying CSS. Why is that a requirement of your project?

*

*It sounds like you are looking for a persistent header.  Start here with the JQM Footers documentation. They cover persistence and it should be the same for headers. If the JQM docs do not solve this issue, check out this other Stackoverflow post.

*If you are looking for a custom configuration, check out the very bottom of this documentation on JQM headers.  If that doesn't quite do it you may also try the JQM layout grids. Otherwise, you will need CSS, be it inline or otherwise.

*While I am not sure I completely understand the problem here, I have heard that CSS/HTML should be used to control layout width, but not height.  Sorry, having trouble finding the articles to back that up so lets just consider that one design philosophy.  Just the same, this post tells you how to evenly balance height with CSS.
As for your last question about borders, you would have to use CSS to control them. Whether or not you do it inline or a stylesheet like one created with the JQM Themeroller, I am not aware of any other way of styling borders other than CSS.
Hope this helps!


text:
Q: SQL - Fill in values between range In SQL Server I have a table that looks like the following:

StatusID
StatusIN
StatusOUT

20
200
290

21
200
290

And the output I'm looking for is to get the values in between, and fill it out such as:

StatusID
Status

20
201

20
202

20
etc.

21
201

A: You can achieve this with a CTE:
DECLARE @t TABLE(
  StatusID int
  ,StatusIn int
  ,StatusOut int)

INSERT INTO @t VALUES (20, 200, 290), (21, 200, 290)

;WITH cte AS(
  SELECT StatusID, StatusIn, StatusOut
    FROM @t
  UNION ALL
  SELECT StatusID, StatusIn + 1 AS StatusIn, StatusOut
    FROM cte
    WHERE StatusIn + 1 <= StatusOut
)
SELECT StatusID, StatusIn
  FROM cte
  ORDER BY 1,2


text:
Q: Definition of the Entropy I have a question regarding definition of entropy by expected value of the random variable $\log \frac{1}{p(X)}$:
$H(X) = E \log \frac{1}{p(X)}$,
where $X$ is drawn accordingly to the probability mass function of $p(x)$.
The problem is I am still don't understand two thing:
1) How this formula was derived from the original formula for the entropy
$H(X) = - \sum_{x \in X} p(x) \log p(x)$.
2) Even without knowing how to derive the second formula, what it the meaning of $p(X)$? Can you show how to find an entropy for the fair dice with one toss by the second formula.
Appreciate your help!

A: 1) Suppose $X$ is a random variable that takes only a finite number of values, say: $x_1$ with probability $p_1$, $x_2$ with probability $p_2, \ldots, x_n$ with probability $p_n$.
What is the expectation of $X$? Well, easy, $E(X) = \sum_{i=1}^n x_i p_i.$ What about the random variable $X^2$? Well, $E(X^2) = \sum_{i=1}^n x_i^2 p_i$.
The same goes for the random variable $p(X)$. You can think of it as taking the value $p_i$ whenever $X$ takes the value $x_i$. Therefore its expectation is $E(p(X)) = \sum_{i=1}^n p_i^2$.
Finally, the random variable $\log\left(\frac{1}{p(X)}\right) = - \log(p(X))$ has expectation $$E\left[\log\left(\frac{1}{p(X)}\right)\right] = E[-\log(p(X))] = \sum_{i=1}^n (- \log(p_i))p_i = -\sum_{i=1}^n p_i \log(p_i) $$
2) For instance, for the fair dice, $p(1) = p(2) = \ldots = p(6) = 1/6$, hence $$H(X) = - 6 \cdot \frac{1}{6}\log\left(\frac{1}{6}\right) = \log(6)$$


text:
Q: Get total hours worked between 2 days mysql I have a MySQL table where employee login and logout timings are recorded. Here in the in-out column 1-represents login and 0-represents logout.
  [id]   [User_id]           [Date_time]                 [in_out]
    1       1          2011-01-20 18:01:03                  1
    2       1          2011-01-20 19:30:43                  0
    3       1          2011-01-20 20:46:23                  1
    4       1          2011-01-21 00:42:45                  0

Is it possible to retrieve total hours worked in a day (between 2 days) by a user using single query?
The same Question it's a copy of Get total hours worked in a day mysql and solution:
  SELECT `User_id`, time(sum(`Date_time`*(1-2*`in_out`)))
  FROM `whatever_table` GROUP BY `User_id`;

But the solution needs to be different when the employee start working in a day and go out on the next day.

A: You can achieve this using given stored procedure. Consider your table name EventLog.
DELIMITER $$
CREATE PROCEDURE `GET_TOTAL_LOGIN_TIME`(
    IN  startDate DATETIME,
    IN  endDate DATETIME,
    IN  userId INT(11)
)
BEGIN
    select
    (sum(
case when(e2.Date_time <= startDate) then 0 else
case when(e1.Date_time >= endDate) then 0 else
case when(e1.Date_time >= startDate && e2.Date_time <= endDate) then
            TIME_TO_SEC(TIMEDIFF(e2.Date_time, e1.Date_time))/60 else
case when(e1.Date_time <= startDate && e2.Date_time <= endDate) then
            TIME_TO_SEC(TIMEDIFF(e2.Date_time, startDate))/60 else
case when(e1.Date_time >= startDate && e2.Date_time >= endDate) then
            TIME_TO_SEC(TIMEDIFF(endDate,e1.Date_time))/60
end end end end end
)) as loginTimeInMin
    from
        ((EventLog e1
        left join EventLog e2 ON (((e1.User_id = e2.User_id) and (e2.in_out = 0) and (e1.Date_time < e2.Date_time))))
        left join EventLog e3 ON (((e1.User_id = e3.User_id) and (e1.Date_time < e3.Date_time) and (e3.Date_time < e2.Date_time))))
    where
        ((e1.in_out = 1) and isnull(e3.Date_time)) and e2.Date_time is not null
        AND e1.User_id = userId
        AND userRole.userRoleId = roleId
        AND userRole.userLoginId = userId
    group by e1.User_id;
END;

A: You can get the number of seconds worked like this:
 SELECT `User_id`, sum(unix_timestamp(`Date_time`)*(1-2*`in_out`))
 FROM `whatever_table`
 GROUP BY `User_id`;

Then you can convert the seconds to whatever you want.


text:
Q: cv2.error: OpenCV(4.3.0) ../opencv_contrib/modules/dnn_superres/src/dnn_superres.cpp:97: error: (-2:Unspecified error) Model not specified Im trying out this article;
https://towardsdatascience.com/deep-learning-based-super-resolution-with-opencv-4fd736678066
this is the code copied out of the article;
import cv2
from cv2 import dnn_superres
sr = dnn_superres.DnnSuperResImpl_create()
image = cv2.imread('./input.png')
path = "EDSR_x3.pb"
sr.readModel(path)
sr.setModel("edsr", 3)
result = sr.upsample(image)
cv2.imwrite("./upscaled.png", result)
i also tried opencv Super Resolution Tutorial;
https://docs.opencv.org/master/d5/d29/tutorial_dnn_superres_upscale_image_single.html
import cv2
from cv2 import dnn_superres
sr = dnn_superres.DnnSuperResImpl_create()
image = cv2.imread('./image.png')
path = "EDSR_x4.pb"
sr.readModel(path)
sr.setModel("edsr", 4)
result = sr.upsample(image)
cv2.imwrite("./upscaled.png", result)
My enviroment is anaconda3 opencv 4.3.0.
I either get the error from the title or i get "killed" when i run the opencv example.
*My file directory is all on the same level of the sample codes. I would just change my image file names.
I did try to compile opencv and opencv_contrib from cmake but, i didn't know how to have python refer to opencv and opencv_contrib from source.
ifollow this documentation to install opencv from source;
https://d*ocs.opencv.org/3.4/d2/de6/tutorial_py_setup_in_ubuntu.html
I opted to use anaconda wrapping of opencv 4.3.0 because i ran into too many dependency and wrongly installed package problems.
My friend from a meetup managed to apply the code from the article just as the article depicted while i tried to follow exactly what he did, using an anaconda enviorment. Would my problem stem from my virtual enviorment or opencv package version or the code itself? i did have another colleague run my code from my github branch and he had my exact same problems. How should i apprach the bugs im having and apply the super resolution examples i found?

A: The error 'Model not specified' comes from the fact that the Net is empty. You have to actually download the model and then provide the path to the 'sr.readModel()' function.
If you did that and it still does not work, you could try these two things:

*

*Try a smaller image (in .png format).

*Build OpenCV from source. Do not forget the contrib modules (this is where the dnn_superres module resides). You said you had a problem linking python. I would suggest to use this tutorial. After following that tutorial, do the following command (after you already did sudo make install), to link the python libraries:
sudo ldconfig


text:
Q: How to write a custom loss function in LGBM? I have a binary cross-entropy implementation in Keras. I would like to implement the same one in LGBM as a custom loss. Now I understand LGBM of course has 'binary' objective built-in but I would like to implement this one custom-made on my own as a starter for some future enhancements.
Here is the code,
def custom_binary_loss(y_true, y_pred):
    """
    Keras version of binary cross-entropy (works like charm!)
    """
    # https://github.com/tensorflow/tensorflow/blob/v2.3.1/tensorflow/python/keras/backend.py#L4826
    y_pred = K.clip(y_pred, K.epsilon(), 1 - K.epsilon())

    term_0 = (1 - y_true) * K.log(1 - y_pred + K.epsilon())  # Cancels out when target is 1
    term_1 = y_true * K.log(y_pred + K.epsilon()) # Cancels out when target is 0

    return -K.mean(term_0 + term_1, axis=1)

# --------------------
def custom_binary_loss_lgbm(y_pred, train_data):
    """
    LGBM version of binary cross-entropy
    """
    y_pred = 1.0 / (1.0 + np.exp(-y_pred))

    y_true = train_data.get_label()
    y_true = np.expand_dims(y_true, axis=1)
    y_pred = np.expand_dims(y_pred, axis=1)

    epsilon_ = 1e-7
    y_pred = np.clip(y_pred, epsilon_, 1 - epsilon_)

    term_0 = (1 - y_true) * np.log(1 - y_pred + epsilon_)   # Cancels out when target is 1
    term_1 = y_true * np.log(y_pred + epsilon_)  # Cancels out when target is 0

    grad = -np.mean(term_0 + term_1, axis=1)
    hess = np.ones(grad.shape)
    return grad, hess

But using the above my LGBM model only predicts zeros. Now my dataset is balanced and everything looks cool so what's the error here?
params = {
    'objective': 'binary',
    'num_iterations': 100,
    'seed': 21
}
ds_train = lgb.Dataset(df_train[predictors], y, free_raw_data=False)
reg_lgbm = lgb.train(params=params, train_set=ds_train, fobj=custom_binary_loss_lgbm)

I also tried with a different hessian hess = (y_pred * (1. - y_pred)).flatten(). Although I don't know what hessian really means it didn't work either!
list(map(lambda x: 1.0 / (1.0 + np.exp(-x)), reg_lgbm.predict(df_train[predictors])))

[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,  .............]

A: Try setting the metric parameter to the string "None" in params, like this:
params = {
    'objective': 'binary',
    'metric': 'None',
    'num_iterations': 100,
    'seed': 21
}

Otherwise, according to the documentation, the algorithm would choose a default evaluation method for objective set to 'binary'

A: in fact u should first set metric parameter to the string "None".
then u should define ur loss function and ur evaluation function.
if ur gradient and hess are right then u should also write evaluation function. only fobj parameter is not enough.


text:
Q: Rename NuGet feed I just renamed a NuGet feed published on TFS 2015 from "Libs" to "Libs_release". Now I want to rename it back to "Libs", but I cannot. The (unfortunately german) error message is:

Der Feedname "Libs" wird bald verfügbar sein.

What can I do? Do I have to wait a certain time?

A: It seems that it takes some time that the name can be reused. After ~2 hours I was able to rename the feed back to Libs.


text:
Q: How to use Compiler instance and ASTConsumer with clang 3.6 I have a little tool based on clang that create a compiler instance and that was able to parse C header files. This tool worked fine with clang 3.4 and 3.5.
I first created a compiler instance and use it with a new class created from an ASTConsumer:
ci = new clang::CompilerInstance()
ci.createDiagnostics();
ci.createFileManager();
ci.createSourceManager(ci.getFileManager());
std::shared_ptr<clang::TargetOptions> pto = std::make_shared<clang::TargetOptions>();
pto->Triple = llvm::sys::getDefaultTargetTriple();
clang::TargetInfo *pti = clang::TargetInfo::CreateTargetInfo(m_ci.getDiagnostics(), pto);
ci.setTarget(pti);
ci.createPreprocessor(clang::TU_Complete);
...
//add source file and the headers paths
...
MyASTConsumer * myASTConsumerClassInstance = new MyASTConsumer;
ci.setASTConsumer(myASTConsumerClassInstance);
...
//parse the header file

where myASTConsumerClassInstance is an instance of the class that I created like this (a simplified form):
class MyASTConsumer : public clang::ASTConsumer
{
    MyASTConsumer()
    ~MyASTConsumer() {};
    virtual bool HandleTopLevelDecl( clang::DeclGroupRef d);
    virtual void HandleTagDeclDefinition( clang::TagDecl * d);
    private:
    std::vector<clang::TagDecl *> m_my_tags;
}

In the HandleTagDeclDefinition method, all the tags declarations where registred in the vector m_my_tags. So after the parsing process, I was able to access to all the tag declarations from myASTConsumerInstance.
Now in the clang 3.6 api, the method clang::CompilerInstance::setASTConsumer requiert a std::unique_ptr<ASTConsumer>. How to adapt my code?

A: It is easy in fact replace this
MyASTConsumer * myASTConsumerClassInstance = new MyASTConsumer;
ci.setASTConsumer(myASTConsumerClassInstance);

with :
ci.setASTConsumer(llvm::make_unique<MyASTConsumer>());

or :
MyASTConsumer * myASTConsumerClassInstance = new MyASTConsumer;
ci.setASTConsumer(llvm::make_unique<clang::ASTConsumer>(*myASTConsumerClassInstance));


text:
Q: How to use NodeJS debugging in Visual Studio Code with asdf? (cannot find runtime 'node') Unfortunately Visual Studio Code doesn't find the runtime executable node.

But the integrated terminal knows about node:
$ which node
/home/user/.asdf/shims/node

How can I introduce node to Visual Studio Code without adding the runtime executable to the launch.json explicitly?
{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      [...]
      "runtimeExecutable": "~/.asdf/shims/node" // <- want to avoid this
    }
  ]
}

A: It seems VSCode first tries to resolve a Node binary before blindly executing it.
In my case I didn't have a global Node version set, which causes that check to fail.
I simply set a global version, VSCode's checks pass, and then it runs the local version happily, without any ASDF-specific launch config.

A: For me worked to set an asdf global version for node
asdf global nodejs 16.13.1


text:
Q: I can't join 3 tables with some condition I have 3 tables:

*

*Provinces

*Cities

*Residences

Here are the columns of these tables :
Provinces:
id , name , status

Cities:
id , province_id , name , status

Residences:
id , province_id , city_id , name , status

I want all provinces, with number of cities that province has, when cities have at least 1 residence.
For example: province #1 has 10 cities, and each city has 10 residences.
But only 5 cities have city.status = 1 and have residences, and only 3 cities have residences with status = 1.
So the data being returned should be :
Province 1 - 3 cities (count cities.id)

All 3 cities in province 1 have at least 1 residence with status = 1
How can I query this?
I can't use SQL 3
Sorry for my bad English
Thanks

A: SELECT
  p.name,
  COUNT(DISTINCT c.id) AS city_count
FROM
  residences   AS r
INNER JOIN
  cities       AS c
    ON c.id = r.city_id
INNER JOIN
  provinces    AS p
    ON p.id = r.province_id
WHERE
      r.status = 1
  AND c.status = 1
  AND p.status = 1
GROUP BY
  p.name

Or...
SELECT
  p.name,
  COUNT(*) AS city_count
FROM
  cities       AS c
INNER JOIN
  provinces    AS p
    ON p.id = c.province_id
WHERE
      c.status = 1
  AND p.status = 1
  AND EXISTS (
    SELECT *
      FROM residences
     WHERE status      = 1
       AND city_id     = c.id
       AND province_id = p.id
  )
GROUP BY
  p.name


text:
Q: PublishingStartDate empty even though the page is published I've been through the typical publish/approve process and have, seemingly, successfully published a page (I've checked it's approval status in the manage content and structure section of the site which says approved. Does this mean it's published?).
However, when I run the following query (which does bring back the page in question), the PublishingStartDate is always empty:
//query.ViewFields = @"<FieldRef Name=""PublishingStartDate"" /><FieldRef Name=""Author"" />";

A: That field only applies to pages that are/were published on a scheduled date and time and it should be empty for Pages that are published immediately.


text:
Q: lucene updation problem i am using this function to update the index ..
    private static void insert_index(String url)throws Exception
{
 System.out.println(url);
    IndexWriter writer = new IndexWriter(
            FSDirectory.open(new File(INDEX_DIR)),
            new StandardAnalyzer(Version.LUCENE_CURRENT),
            true,
            IndexWriter.MaxFieldLength.UNLIMITED);
    Document doc;
    String field;
    String text;

    doc = new Document();

    field = "url";
    text = url;
    doc.add(new Field(field, text, Field.Store.YES, Field.Index.ANALYZED));

    field = "tags";
    text = "url";
    doc.add(new Field(field, text, Field.Store.YES, Field.Index.ANALYZED));

    writer.addDocument(doc);
    writer.commit();
    writer.close();

}

it index more urls and if i search the field with url it shows only the last indexed url....

A: When creating a new index for the first time, the create parameter for the IndexWriter constructor has to be set to true. From then on it must be set to false, otherwise the previously saved index content is overridden. I'd change my code to detect index files before creating a new instance of IndexWriter.
This code can be used to workout if the index files exist
private bool IndexExists(string sIndexPath)
{
    return IndexReader.IndexExists(sIndexPath))
}

Then create the IndexWriter instance like this:
IndexWriter writer = new IndexWriter(
    FSDirectory.open(new File(INDEX_DIR)),
    new StandardAnalyzer(Version.LUCENE_CURRENT),
    IndexExists(INDEX_DIR) == false, // <-- This is what I mean
    IndexWriter.MaxFieldLength.UNLIMITED);


text:
Q: why does npm staging have multiple folders wit hthe same lib and version When doing an npm install with the -ddd flag, I noticed the following output:

npm sill extract rxjs@6.4.0 extracted to
D:\DSTGIT\digital-advice\ciam-web-app\node_modules.staging\rxjs-238afce1
(68114ms)
npm sill extract rxjs@6.4.0 extracted to
D:\DSTGIT\digital-advice\ciam-web-app\node_modules.staging\rxjs-512d1edc
(67660ms)
npm sill extract rxjs@6.4.0 extracted to
D:\DSTGIT\digital-advice\ciam-web-app\node_modules.staging\rxjs-8116df1c
(67770ms)
npm sill extract rxjs@6.4.0 extracted to
D:\DSTGIT\digital-advice\ciam-web-app\node_modules.staging\rxjs-0f96b965
(68007ms)
npm sill extract rxjs@6.4.0 extracted to
D:\DSTGIT\digital-advice\ciam-web-app\node_modules.staging\rxjs-6a5eaafd
(67783ms)
npm sill extract rxjs@6.4.0 extracted to
D:\DSTGIT\digital-advice\ciam-web-app\node_modules.staging\rxjs-e832871b
(67894ms)
npm sill extract rxjs@6.4.0 extracted to
D:\DSTGIT\digital-advice\ciam-web-app\node_modules.staging\rxjs-394691af
(68075ms)

I thought it would only do it once per version.
Any ideas?


text:
Q: Admin-on-REST: Nested Create-Route not working? my current setup looks like this:
httpClient.js:
import { fetchUtils } from 'admin-on-rest'

const HttpClient = (url, options = {}) => {
    if (!options.headers) {
        options.headers = new Headers({ Accept: 'application/json' })
    }

    // ...handle authorization and set some header

    return fetchUtils.fetchJson(url, options)
}

export default HttpClient

restClient.js
import { jsonServerRestClient } from 'admin-on-rest'
import HttpClient from './httpClient.js'

export default jsonServerRestClient('', HttpClient)

...so I'm pretty basic in that department.
What I now have is a couple of routes looking like this:
<Route exact path="/stream" render={(routeProps) => <StreamList hasCreate resource="stream" {...routeProps} />} />,
<Route exact path="/stream/create" render={(routeProps) => <StreamCreate resource="stream" {...routeProps} />} />,
<Route exact path="/stream/:id" render={(routeProps) => <StreamEdit hasDelete resource="stream" {...routeProps} />} />,
<Route exact path="/stream/:id/delete" render={(routeProps) => <Delete resource="stream" {...routeProps} />} />,
<Route exact path="/stream/query/:id" component={StreamQueryEdit} />,

...this is all pretty standard as well and works fine.
My problem now is that I have another route /config/what, where I want to have nested routes for one of the resources. The routing looks like this:
<Route exact path="/config/how/antonym" render={(routeProps) => <AntonymList hasCreate resource="antonym" {...routeProps} />} />
<Route exact path="/config/how/antonym/create" render={(routeProps) => <AntonymCreate resource="antonym" {...routeProps} />} />
<Route exact path="/config/how/antonym/:id" render={(routeProps) => <AntonymEdit resource="antonym" {...routeProps} />} />
<Route exact path="/config/how/antonym/:id/delete" render={(routeProps) => <Delete resource="antonym" {...routeProps} />} />

Inside the /config/how/ these nested routes are rendered like this:
if (this.props.children) {
    return this.props.children
}

The List-, Edit- and Delete-Route all work like expected here. The only problem is that once I navigate to the Create-Route I get a 500-error from the server.
Turns out that after some investigating, the framework does not recognize this route as a create Route but instead thinks of it as a GET request for the id of "create".
Here is what I tracked the issue down to:

This suggests that for some reason admin-on-rest thinks of this request as a GET request. This also causes the code to go through Edit.js (instead of "Create"?) And I'm really not sure why.
I tried to find the place where the type parameters are being set to see what might cause this behaviour ...but no luck so far.
It's especially weird that both the list and the edit route work fine in these cases. It's just the create-route...

A: Make sure for your AntonymCreate component it has a form like this:
export const AntonymCreate = (props) => (
    <Create {...props} title="Create">
    ...
    </Create>
);

This is probably why it doesn't work.


text:
Q: Including html parts in another html files I'm working on a "plain" HTML-CSS website. It contains several pages. I want some code to be included in all HTML pages. (All have a navbar at the top)
What is the best way to include that part of the code in all files in order to avoid repeating code?
I've tried creating a directory named "partials", there I added a file called header.html and then tried including it in a different file with PHP. like so:
<?php include "./partials/header.html" ?>

This is not working. Please advise me what to do.
Thanks!

A: From what you answer and ask on the reply's under your question I wonder if you are aware Php code only works when run on a server? You can create your own server environment locally using Xampp.


text:
Q: What does $d \mathbb{P}(\omega)$ mean in expectation of r.v. $f$? What does $d \mathbb{P}(\omega)$ mean in expectation of r.v. $f$?
$$\mathbb{E} f = \int_{\Omega} f(\omega) d \mathbb{P}(\omega)$$
Yes sure it's some "infinitesimal", but should this mean that $\mathbb{P}(\omega)$ is a variable of $f$? Since in elementary integrals:
$$\int_X f(x) dx$$ and $x$ is a variable of $f$.
$\omega \in \Omega$ by def. but why is it $d \mathbb{P}(\omega)$ then and now just $d \omega$?

A: Part of what might be confusing to you already shows up in discrete probability. Here is an example: we roll a fair die, and let $X$ be the resulting number.  We (that is, math teachers) say things like, the expected value of $X$ is $EX=\sum_{i=1}^6 i (1/6)$ and the expected value of $X^2$ is $EX^2=\sum_{i=1}^6 i^2 (1/6)$.  Suppose we also roll an unfair die, and call the result $Y$, for which $P(Y=i) = p_i$ where not all the $p_i$ values are $1/6$.  We say the expectations of $Y$ and $Y^2$ are $EY=\sum_{i=1}^6 i p_i$ and $EY^2 = \sum_{i=1}^6 i^2p_i$.  In all cases the expectation is a weighted sum of the value we are talking about, and the system of weights we assign to the fundamental outcomes.  In more advanced textbooks you will often see expressions like $EX=\int_\Omega X(\omega) P(d\omega)$, where $\omega$ plays the role of $i$ in my examples in this paragraph, where $P(\omega)$ plays the role of $p_i$ and so on.
In this way, we think of expectations as arising from two ingredients: a random quantity and the corresponding probability distribution.  In your case, the expression
$f(\omega)$ is the random quantity whose expectation we seek, and $d \mathbb P(\omega)$ is the corresponding probability distribution.
You might be also confused by the use of the letter $f$, which in textbooks is often used more-or-less exclusively as part of the probability law specification. Your example, however, is not an instance.


text:
Q: Bash re-run case statement until user inputs NO I have this piece of code which asks the user a simple yes/no.
The thing here, it should be to re-execute the code until the user explicitly says no.
With the following code, only one instance of yes is executed, then it exits.
while true; do
  read -p "Do you wish to continue with the analysis? " yn
  case $yn in
    [Yy]* )
            read -p 'Provide the folder to analyze: ' newFolderToAnalyze

            if [ -d "$newFolderToAnalyze" ]; then
              du -h $newFolderToAnalyze --max-depth=1
            fi

            break
            ;;
    [Nn]* )
            echo -e 'Bye-bye cause you said it!'
            ;;
    * )
            echo "Please answer yes or no."
            ;;
  esac
done

The key here, is that when the user inputs the yes the program should ask him again, until he says no.
Note the break statement, is there something to similar to end the current execution and jump to the while loop again?

A: You can stick the prompt and its evaluation into the condition:
while read -rp 'Continue? ' && [[ $REPLY != [Nn]* ]]; do
    echo "analyzing..."
done

A: You should rewrite your script as follow:
#!/bin/bash

while true; do
    read -p "Do you wish to continue with the analysis? " yn
    case $yn in
        [Yy]* )
            read -p 'Provide the folder to analyze: ' newFolderToAnalyze

            if [ -d "$newFolderToAnalyze" ]
            then

                du -h $newFolderToAnalyze --max-depth=1

            fi
        ;;

        [Nn]* )
            echo -e 'Bye-bye cause you said it!'
            break
        ;;

        * )
            echo "Please answer yes or no."
        ;;
    esac
done


text:
Q: Create SVG objects with javascript without disabling IOS compass access Literally every single working example I've found using javascript to create SVG elements (such as a circle) references "http://www.w3.org/2000/svg".
The problem is that you can't access the compass in IOS (mobile devices) unless the webpage and every site it references is https with a valid SSL certificate.
I can use setAttribute() to change the values of EXISTING elements in an svg with xmlns="https://www.w3.org/2000/svg", but createElementNS() only works with the http version.

<svg id="svg1" viewBox="0 0 300 100" xmlns="https://www.w3.org/2000/svg" stroke="red" fill="grey">
    <circle cx="50" cy="50" r="40" id="circle1"/>
    <circle cx="150" cy="50" r="4" />
</svg>
<script>
    //I can at least alter existing elements fine:
    var existing_circle=document.getElementById("circle1");
    existing_circle.setAttribute('r','5');//NS version works too
    //This stops working if https, even after trying all variations with/without "NS":
    var svg=document.getElementById("svg1");
    var circle = document.createElementNS("http://www.w3.org/2000/svg", 'circle');
    circle.setAttributeNS(null,'cx', "100");
    circle.setAttributeNS(null,'cy', "50");
    circle.setAttributeNS(null,'fill',"red");
    circle.setAttributeNS(null,'stroke','White');
    circle.setAttributeNS(null,'stroke-width','2');
    circle.setAttributeNS(null,'r','10');
    svg.appendChild(circle);
</script>


text:
Q: Sci-Fi TV Series identification from 90's, set on a starship, with a man who is half machine As a kid in 1993-1994, I watched some kind of Sci-Fi TV series about a guy who was turned into a machine. Or at least half of him was entirely a machine and the other was human, split vertically. I remember there was some kind of conflict between machines or a machine-like race and the protagonists of this series, which ended up with him turning into a half machine. Also, I remember the woman that loved that guy when saw him turned into a half robot/half man was shocked but touched his human side on a cheek and cried or something like that. It was a dramatic scene which was memorable. I don't remember anything else beside that and that the whole setting of series was on some kind of starship.
Also, not sure but I think series was produced by Disney, although I might be mistaken. And I think it was a miniseries, as the entire show was 6 episodes, each 45-60 minutes long.

A: Is it possible this is Earth Star Voyager? It was a television movie shown on the Wonderful World of Disney in 1988 as a two part pilot. It has a man who has been converted to a cyborg, Shell, with his face roughly split in half and mechanical augmentations down one side. The action is largely set on first the Vanguard Explorer, then the Earth*Star Voyager. And Dr. Arthur does have an emotional moment with Shell, although I don't see any face-touching and she did not know him from before then.

However, it was only aired in two parts originally (four parts in a Russian broadcast), is about as half as long as you're thinking at a total of 192 minutes, and the cyborg was created by the "Outlaw Technology Zone", a group of criminals, not a group of machine aliens.
Here is the German VHS release cover with a better look at Shell:

As noted the other times this has come up, the movie is available online:


text:
Q: Problem with defining the range of $f(x)=\ln(x+\sqrt{x^2+1})$
Find the $D_f$ of $f(x)=\ln(x+\sqrt{x^2+1})$

Personal work:
We have to solve the inequality: $x+\sqrt{x^2+1}>0$
I've thought of raising both sides powers' to $^2$ so the root can go away. So, we have: $$x^2+x^2+1>0 \iff 2x^2+1>0$$ And it's always positive. Problem? I need to find the $D_f$ of $f(x).$

A: No issues if $x\geq 0$. If $x<0$ then $\sqrt{x^2+1}+x$ is positive anyway, since $\sqrt{x^2+1}>|x|$, hence $f(x)=\log(x+\sqrt{x^2+1})$ is defined for any $x\in\mathbb{R}$. We may also notice that
$$ f(\sinh u) = \log(\sinh u+\cosh u) = \log(e^u) = u $$
hence $f(x)=\text{arcsinh}(x)$ is the inverse function of $\sinh$, which is bijective over $\mathbb{R}$.

A: HINT: $\sqrt{x^2+1}>\sqrt{x^2}=|x|$, so the domain (against the title, as suggest notation and your attempt) is...
(Your method assumes nonnegative $x$).

A: In your title you are asking for the range of $f(x)$, however it seems you are attempting to solve for the domain of $f(x)$, so I will provide such a solution. If it is not the case, please clarify.
The logarithm function is defined for $x>0$, so we want to solve the inequality $x+\sqrt{x^2+1}> 0$. This is equivalent to solving  \begin{align}\sqrt{x^2+1}> -x \tag{1} \end{align} and we have to consider two cases: when $x$ is positive and when $x$ is negative. So

*

*Case $x > 0: $ notice the right hand side of $(1)$ becomes negative, and the left hand side is positive, since $x^2+1$  is always positive. Hence it is true for all $x>0$.

*Case $x\leq0: $ Then we have that both the RHS and LHS are non-negative, so we have that
\begin{align}\sqrt{x^2+1}> -x \iff\left(\sqrt{x^2+1}\right)^2> (-x)^2 \iff x^2+1>x^2 \iff1>0,\end{align}
which is true for all $x$.
Hence the domain of $f(x)=\ln(x+\sqrt{x^2+1})$ is all the real numbers, $\mathbb{R}$.

A: WLOG $x=\cot2y$ where $0<2y\le\pi$
$$x+\sqrt{x^2+1}=\cot2y+\csc2y=\cot y$$ for $1+\cos2y\ne0\iff2y\ne\pi$
$0<\cot y<\infty$


text:
Q: can not ssh to another Docker Container docker-compose I have a docker image which i am using as my git server, i have all my data in it. then i have a database container where i need to clone data from my git docker server.
my docker-compose.yml file is:
version: '3'

services:
  git-server:
    image: git:latest
    build:
      context: git
    ports:
      - "22:22"

  my-db:
    image: my-db:latest
    build:
      context: db
    ports:
      - "5433:5432"
    links:
      - git-server

for git docker i am only creating git repos only.
FROM kinogmt/centos-ssh:latest

......

RUN mkdir /home/git/dashboard.git
WORKDIR /home/git/dashboard.git
RUN git --bare init && git --bare fetch git@bitbucket.org:****/******.git
.......
EXPOSE 22

and in my database dockerfile i am cloning that repo.
From centos:centos7

.......
RUN git clone git@git-server:dashboard.git
.......

when i run docker-compose build
it says

ssh: Could not resolve hostname git-server: Name or service not known
  fatal: Could not read from remote repository.
Please make sure you have the correct access rights and the repository
  exists.

A: At build time, containers are not attached to the bridge network (nor are they connected to volumes). If you need container to container networking, you need to move that workflow into your entrypoint or command you run when the container starts.

Commands executed with a RUN in the Dockerfile are performed at build time. When docker is building your image, it does so without networking to other containers, without volumes mounted, and without any dependencies on other containers. It simply takes the previous state from the prior line, creates a temporary container that runs that RUN command, and captures the resulting layers. So attempts to use container-to-container networking will fail because the other containers do not exist at build time. Builds should be reproducible and independent from external artifacts when possible, so this needs a redesign.
As a redesign, I'd personally remove the git clone from your image steps and include the code in the repo where your Dockerfile lives. Do any checkouts before starting the build. This has the advantage of keeping any secrets to log into a private repo out of your image. Then inside your build, you would just do a COPY of the files into your image instead of a git fetch.
The other option if there's a need for container-to-container communication for your process is to run a script in your CMD or ENTRYPOINT that runs any steps you need when the container is run vs when the image is built.


text:
Q: field like OBJECTID from ArcGIS in QGIS I want to ensure that the feature that I want to add from the field tablets is correctly synced so that, what I am trying to do is to add a unique sequential id into each feature, Is that correct?
or is there are a way to add OBJECTID like in ArcGIS?


text:
Q: Knowing to interpret the phpunit tests I´m trying to configure the fixtures and phpunit system is returned the next message '.E', but I don´t know how interpret it:

C:\kyopol\Apache 2.22.22\htdocs\demo\protected\tests>phpunit unit/EntityTest.php
PHPUnit 3.7.14 by Sebastian Bergmann.
Configuration read from C:\kyopol\Apache
  2.22.22\htdocs\demo\protected\tests\phpunit.xml
.E
Time: 2 seconds, Memory: 6.50Mb
There was 1 error:
1) EntityTest::testRead Undefined variable: newEntity
C:\kyopol\Apache
  2.22.22\htdocs\demo\protected\tests\unit\EntityTest.php:37
FAILURES! Tests: 2, Assertions: 3, Errors: 1.

Next, class test EntityTest.php data code:

class EntityTest extends CDbTestCase
{
public function testCreate()
{
    //CREATE a new Entity
    $newEntity=new Entity;
    $newEntity->setAttributes(
        array(
                'name' => 'Test Entity 1',
                'description' => 'Test entity number one',
                'type_id' => 1,
                'location_lat' => 77,
                'location_lon' => 77,
                'create_time' => '2013-02-16 20:36:00',
                'create_user_id' => 1,
                'update_time' => '0000-00-00 00:00:00',
                'update_user_id' => 0,
            )
    );
    $this->assertTrue($newEntity->save(false));

    //READ a Entity
    $retrievedEntity=Entity::model()->findByPk($newEntity->id);
    $this->assertTrue($retrievedEntity instanceof Entity);
    $this->assertEquals('Test Entity 1',$retrievedEntity->name);
}

public function testRead()
    {
        //READ a Entity
        $retrievedEntity=Entity::model()->findByPk($newEntity->id);
        $this->assertTrue($retrievedEntity instanceof Entity);
        $this->assertEquals('Test Entity 1',$retrievedEntity->name);
    }
}

What is it meaning the capital letter 'E' and the previous point '.' ?
In general: Could nobody said me how knows to interpret output messages in phpunit?
Cheers.

A: One of your tests is failing so that's why you see the E. The other one is passing, indicated by a ..
If there are any error messages in the tests they will be summarized at the end.
The error message of your failing test is "Undefined variable: newEntity".
Your first line in testRead() is:
$retrievedEntity=Entity::model()->findByPk($newEntity->id);

But you have never setup $newEntity in that test.


text: Q: Date pivot table creation I have a Bank transaction table with multiple dates, I want to create a pivot table out of it based on dates, but the number of visits is not predetermined, So I want to make the pivot table dynamic, as new transaction comes it should add new column saying visit 4,5,6,and so on and add corresponding amount in the row.


text:
Q: How to setup RAID 1+0 on Ubuntu Server I'm using the RAID 1+0 structure as described in this post: RAID 1+0 vs RAID 0+1
I'm at the installation screen for Ubuntu Server.  Both of my raid stripes are setup.  The screen I'm looking at now allows me to create partitions and stuff and I'm not sure how to setup the drive mirroring.  Can anyone help guide me in the right direction?
All of my hardware specs are in the other thread.
I've followed the guide here: https://help.ubuntu.com/community/Installation/SoftwareRAID
Though I'm not sure if I should be - it still fails to create the MD.

update
The configuration I have now where it won't let me create the mirrored RAID (assuming I'm doing it correctly)....
Serial ATA RAID isw_bcjjcifhdi_primary (stripe) - 1.0 TB Linux de
     #1 primary 988.0 GB B
     #5 logical  12.2 GB
Serial ATA RAID isw_dbgajfddgf_secondary (stripe) - 1.0 TB Linux
     #1 primary 988.0 GB B f ext4 /
     #5 logical  12.2 GB   F swap swap

update
the problem was that I didn't select RAID10 from the beginning.  I tried to setup dual stripes first.... oops!

When I go into format the partitions it won't create an Ext4 file system on the RAID.... it fails.  Any ideas on why?

A: You have a hardware RAID controller, so you don't want to set up any software RAID at all.
The RAID controller will have some sort of configuration interface (possibly through the BIOS) where you can define your arrays.
Before you even install the operating system, you will need to go into the RAID configuration and create a RAID10 array using all of your disks. Once you've done that, it will present the array as a single disk to any Operating System you install.
When you go to install your Operating System, just set it to use the whole "disk" (which is actually all of your disks together in the RAID array) and you'll be fine. The RAID controller does all the mirroring and striping for you, so you shouldn't have to configure anything RAID related in the Operating System itself.


text:
Q: 18.04 Boot freezes at "Started Hold until boot process finishes up" I have been encountering some trouble trying to boot 18.04. When I attempt to boot it becomes stuck "Started Hold until boot process finishes up", and ctrl+alt+f1/f2have no effect Following some instructions from the web I have tried booting into recovery mode to run networking and the execute some commands in the root shell. When I run network it freezes at "Flush Journal to Persistent Log". I have tried to fix that but I am quite new to Linux and have not been able to understand it. Any help is appreciated as I don't have the slightest idea of how to fix this. Thanks in advance for your time.

A: The same issue happened, when there was no free space on the disk.
To clean up you may go to root terminal and clean any not needed files.
To do that you need while starting the system to press Shift(old systems) or Escape(new systems) button, then select booting in "recovery mode". Then select something like "root terminal". Clean up at least few G bytes. Type "exit" and choose option to "resume normal boot".
In any case, https://wiki.ubuntu.com/RecoveryMode should help you.

A: I really don't know why it happens, but have worked around and came up with a solution with. The solution steps are

*

*Change into tty. (!!!Yes you can change into tty)

*Enter the credentials and change into root user using sudo -s.

*Remove the Nvidia Driver which normally would have been there installed on your system. (I believe apt-get remove --purge '^nvidia-.*' will work as it is shown here how-can-i-uninstall-a-nvidia-driver-completely).

*Remove gdm(Gnome-display-Manager) which is normally the display managers for gnome desktop environments using command apt remove gdm.

*Re-install GDM using the command apt install gdm.

*Reboot the system using the command reboot.

*The above has to work and you would see the login screen again. Incase the above method works, you will need to re-install the Nvidia-drivers. I am sure there is a way you will work around it as it is completey graphical.

(SRY peeps, I myself am not an Ubuntu user, but have been long for 3 years. Have shifted to some other distro and faced the same issue and fixed it using the above steps. I believe it will work the same way for Ubuntu as well. Give it as try, maybe it works for you)

A: I had the exact same problem after a kernel upgrade. It turned out that my root partition was stuffed so much, it had no free space. I used the advanced mode menu to free up some space and restarted. It just worked afterwards.

A: I just entered the Ubuntu menu pressing ESC when booting, then choose Recovery Mode. It worked for me.