text:
Q: Provide function dependency using Dagger 2 I would like to provide a function as dependency using Dagger 2:
@Module
class DatabaseModule {

    @Provides
    @Singleton
    fun provideDatabase(application: Application, betaFilter: (BetaFilterable) -> Boolean): Database {
        return Database(application, BuildConfig.VERSION_CODE, betaFilter)
    }

    @Provides
    @Suppress("ConstantConditionIf")
    fun provideBetaFiler(): (BetaFilterable) -> Boolean {
        return if (BuildConfig.FLAVOR_audience == "regular") {
            { it.betaOnly.not() }
        } else {
            { true }
        }
    }

}

Unfortunately, it does not seem to work:
[dagger.android.AndroidInjector.inject(T)] kotlin.jvm.functions.Function1<?
super com.app.data.BetaFilterable,java.lang.Boolean>
cannot be provided without an @Provides-annotated method.

What am I missing here?

A: It does not work because in order to allow functions with supertypes to be called in place of the lambda ((Any) -> Boolean can be used as well as (BetaFilterable) -> Boolean) a function as a parameter generates bytecode to allow this.
The following code:
object Thing

fun provide(): (Thing) -> Boolean {
    TODO()
}

fun requires(func: (Thing) -> Boolean) {
    TODO()
}

Results in the following signatures:

signature ()Lkotlin/jvm/functions/Function1<LThing;Ljava/lang/Boolean;>;
declaration: kotlin.jvm.functions.Function1<Thing, java.lang.Boolean> provide()
signature (Lkotlin/jvm/functions/Function1<-LThing;Ljava/lang/Boolean;>;)V
declaration: void requires(kotlin.jvm.functions.Function1<? super Thing, java.lang.Boolean>)

The subtle difference between -LThing (? super Thing) and LThing (Thing) makes the types incompatible for Dagger.
I don't believe it is possible to make this work, you will need to define a separate interface that does not have the same ? super/? extends properties as Function1 has.

A: Yes, this can be done in Kotlin.

You need to add @JvmSuppressWildcards at the injection site to ensure the
  signature matches.
  (source)

I wrote the following to verify it:
import dagger.Component
import dagger.Module
import dagger.Provides
import javax.inject.Singleton

class G constructor(val function: Function1<Int, Boolean>)

@Singleton
@Module
class ModuleB {
    @Provides
    fun intToBoolean(): (Int) -> Boolean {
        return { it == 2 }
    }
    @JvmSuppressWildcards
    @Provides fun g(intToBoolean: (Int) -> Boolean): G {
        return G(intToBoolean)
    }
}

@Singleton
@Component(modules = [ModuleB::class])
interface ComponentB {
    fun g(): G
}

val componentB = DaggerComponentB.create()
val g = componentB.g()
println(g.function(2)) // true
println(g.function(3)) // false

Background: Examining @Kiskae's response, it seems the problem is that a parameter of function type in Kotlin becomes contravariant on its own parameter types when the code is converted to Java bytecode.  If this doesn't make sense to you, don't worry.  It's not necessary to understand it to use the technique I show above.

A: As pointed out in Kiskae's answer, it is not possible to make this work using kotlin. You can make it work using java though:
@Module
public class DatabaseModuleJava {

    @Provides
    @Singleton
    public Database provideDatabase(Application application, Function1<BetaFilterable, Boolean> betaFilter) {
        return new Database(application, BuildConfig.VERSION_CODE, betaFilter);
    }

    @Provides
    @Singleton
    @SuppressWarnings("ConstantConditions")
    public Function1<BetaFilterable, Boolean> provideBetaFiler() {
        if (BuildConfig.FLAVOR_audience.equals("regular")) {
            return betaFilterable -> !betaFilterable.getBetaOnly();
        } else {
            return betaFilterable -> true;
        }
    }

}


text:
Q: Replacing certain delimiters in an existing document: P( ) to P[ ] What is the best strategy to replace the delimters of a Probability measure \mathbb{P} automatically in a very long existing file.
Assume the existing LaTeX file used notation like \mathbb{P}(A), \mathbb{P}(B) and \mathbb{P}(...), but it should use the notation \mathbb{P}\lbrack ...\rbrack.
I guess many LaTeX users are facing these kind of problems, but maybe ic can be better solved outside LaTeX - maybe by using regular expressions in the code editor? (I have very little experience with regex.)
It is important that not all round parenthesis are replaced. Only the opening parenthesis directly after \mathbb{P} and its corresponding closing parenthesis should be replaced by squared ones.
It would be nice if probabilities of intervalls would work to - eg. \mathbb{P}(\lbrack a, b)) to \mathbb{P}\lbrack\lbrack a, b)\rbrack, but if one percent of the replacements are wrong it would be still helpful.
PS: Of course it would be better to define a command for that in the first place like \newcommand{\PP}[1]{\mathbb{P}\left\lbrack{#1}\right\rbrack}, but I am talking about an existing document where \mathbb{P}(...) is hard coded in the text.
PPS:MWE:
\documentclass{article}
\usepackage{amssymb}

\begin{document}
    Basic examples: $\mathbb{P}(A)$,
    nested: $\mathbb{P}(A\cup(A\cap B))$, intervall-notation: $\mathbb{P}(X\in[a,b))$,
    left/right: $\mathbb{P}\left(X\in\left[a,(-b)^k\right)\right)$
    $\mathbb{P} ... (these\ parenthesis\ should\ not\ be\ affacted)$.%because they are not directly after P.

    Often $($ and $]$ are matched---e.g.:
    $\mathbb{P}(X\in[a,\infty))$,
    $\mathbb{P}\left( Y\in[b,c)\cup[d,e)\right)$ and often $[$ and $)$ are matched---e.g.:
    $\mathbb{P}\left( Y\in[b,c)\cup(d,e]\right)$

    Sometimes \texttt{left} and \texttt{right} are used and sometimes not. %\left and \right
    And nesting can be quite deep.
    \[\mathbb{P}\left( X\in \left( [a,b)\cup\left(c,3\left(a+(-1)^k(d+e)\right)\right] \right)\setminus (B\cap ( \lbrack k,k+1) \cup C )) \right)\]
    There could be comments involved too:
    \[\mathbb{P}( X\in \left( [a,b)\cup\left(c,3\left(a+(-1)(d+e)\right)\right] \right)\setminus (B\cap ( \lbrack k,k+1)%k+2)
    \cup C )) )\]
\end{document}

A: A simple search/replace would be to replace \mathbb{P}( with \PP{P}(. Then, assuming that all occurances of \mathbb{P} were of the form \mathbb{P}(...) the following should work:

If the content within the () also has round paren those will need an extra {} surrounding them.  That is, somehitng like \PP{P}({AB)) will need to be changed to \PP{P}({(AB)}).
\documentclass{article}
\usepackage{amssymb}

\newcommand*{\PP}{}% Ensure we are not overwriting an existing macro
\def\PP#1(#2){\mathbb{#1}[#2]}

\begin{document}
    %$\mathbb{P}(A)$% Replaced "\mathbb{P}" with "\PP{P}"
    $\PP{P}(A)$
\end{document}

A:
Only the opening parenthesis directly after \mathbb{P} and its corresponding closing parenthesis should be replaced by square brackets.

Here's a LuaLaTeX-based solution. It consists of (a) a Lua function called paren2brack which employs Lua's powerful string.gsub function and (b) a couple of LaTeX utility macros -- called \ParenBrackOn and \ParenBrackOff -- which switch the Lua function on and off. The parentheses-to-brackets substitution is performed "on the fly", i.e., the tex file itself is not edited or modified.
The solution can handle not just \mathbb{P}; in fact, the argument of \mathbb is allowed to be any uppercase letter.
Addendum: I've added a second string.gsub operation to the Lua function, so that it can process cases such as \mathbb{P}\left(A\right).

% !TEX TS-program = lualatex
\documentclass{article}
\usepackage{amssymb} % for '\mathbb' macro
\usepackage{luacode} % for 'luacode' env.

\begin{luacode}

function paren2brack ( s )
  s = s:gsub( "(\\mathbb{%u})(%b())" , function ( x , y )
                  return x .. "[" .. y:sub(2,-2) .. "]"
              end )
  s = s:gsub( "(\\mathbb{%u})\\left%((.-)\\right%)" , function ( x , y )
                  return x .. "\\left[" .. y .. "\\right]"
              end )
  return s
end

\end{luacode}

%% Define a couple of LaTeX utility macros:
\newcommand\ParenBrackOn{\directlua{luatexbase.add_to_callback (
   "process_input_buffer" , paren2brack , "paren2brack" )}}
\newcommand\ParenBrackOff{\directlua{luatexbase.remove_from_callback (
   "process_input_buffer" , "paren2brack" )}}

\begin{document}

$\mathbb{P}(A)$, $\mathbb{Q}(B\cup(C\cap D))$, $\mathbb{P}\left(E\right)$
--- Lua function not activated

\ParenBrackOn % assign the Lua function to LuaTeX's 'process_input_buffer' callback
$\mathbb{P}(A)$, $\mathbb{Q}(B\cup(C\cap D))$, $\mathbb{P}\left(E\right)$
--- Lua function is activated

\end{document}

A: Matching nested braces/brackets is not trivial; I propose the following which is a regular expression that plugs into perl via latexindent and its yaml interface. There's nothing to stop you from incorporating this into your own perl script.
The command that I used to generate the output is
latexindent -rr -l=jakob.yaml myfile.tex -o=output.tex

output.tex

\documentclass{article}
\usepackage{amssymb}

\begin{document}
    Basic examples: $\mathbb{P}\left\lbrack A\right\rbrack$,
    nested: $\mathbb{P}\left\lbrack A\cup(A\cap B)\right\rbrack$, intervall-notation: $\mathbb{P}\left\lbrack X\in[a,b)\right\rbrack$,
    left/right: $\mathbb{P}\left\lbrack X\in\left[a,(-b)^k\right)\right\rbrack$
    $\mathbb{P} ... (these\ parenthesis\ should\ not\ be\ affacted)$.%because they are not directly after P.

    Often $($ and $]$ are matched---e.g.:
    $\mathbb{P}\left\lbrack X\in[a,\infty)\right\rbrack$,
    $\mathbb{P}\left\lbrack  Y\in[b,c)\cup[d,e)\right\rbrack$ and often $[$ and $)$ are matched---e.g.:
    $\mathbb{P}\left\lbrack  Y\in[b,c)\cup(d,e]\right\rbrack$

    Sometimes \texttt{left} and \texttt{right} are used and sometimes not. %\left and \right
    And nesting can be quite deep.
    \[\mathbb{P}\left\lbrack  X\in \left( [a,b)\cup\left(c,3\left(a+(-1)^k(d+e)\right)\right] \right)\setminus (B\cap ( \lbrack k,k+1) \cup C )) \right\rbrack\]
    There could be comments involved too:
    \[\mathbb{P}\left\lbrack  X\in \left( [a,b)\cup\left(c,3\left(a+(-1)(d+e)\right)\right] \right)\setminus (B\cap ( \lbrack k,k+1)%k+2)
    \cup C )\right\rbrack )\]
\end{document}

and here's jakob.yaml; a summary of the approach is:

*

*for each $...$ and \[...\] process the body by finding and storing all but the outer-most occurrences of \left(...\right], (...], \left[...\right), [...), \left(...\right), (...)

*for the outer-most occurrences of \left(...\right) and (...) replace them with \left\lbrack...\right\rbrack
See what you think. Doubtless others could do this more efficiently.
jakob.yaml
replacements:
  -
    substitution: |-
      s/((?<!\\)\$|\\\[)    # opening between either $ or \[
            (.*?)           # body between $...$ or \[...\]
        ((?<!\\)\$|\\\])/   # closing $ or \]
        my $begin = $1;
        my $body = $2;
        my $end = $3;
        # operate on the body, only if it contains \mathbb
        if($body =~ m|\\mathbb|){
            my $storageToken = "jakob-paren-token";
            my $storageCount = 0;
            my @storageArray = ();
            # \left(...\right]
            # \left(...\right]
            # \left(...\right]
            my $leftRightRegEx =
                qr|(
                    \\left\(         # \left(
                    (?:
                      (?!
                       (?:\\left\()  # anything except \left(
                      ).
                    )*?
                    \\right\]        # up to \right]
                  )|xs;
            while( $body =~ m|$leftRightRegEx|xs ){
               $storageCount++;
               $body =~ s|$leftRightRegEx|
                    push(@storageArray,{id=>$storageToken.$storageCount,value=>$1});
                    $storageToken.$storageCount;|xse;
            }
            # (a,b]
            # (a,b]
            # (a,b]
            my $intervalRegEx =
                qr|(
                    \(               # (
                    (?:
                      (?!
                        (?<!\\)\(    # anything except (
                      ).
                    )*?
                    (?<!\\)
                    \]               # up to ]
                  )|xs;
            while( $body =~ m|$intervalRegEx|xs ){
               $storageCount++;
               $body =~ s|$intervalRegEx|
                    push(@storageArray,{id=>$storageToken.$storageCount,value=>$1});
                    $storageToken.$storageCount;|xse;
            }
            # \left[...\right)
            # \left[...\right)
            # \left[...\right)
            $leftRightRegEx =
                qr|(
                    \\left\[         # \left[
                    (?:
                      (?!
                       (?:\\left\[)  # anything except \left[
                      ).
                    )*?
                    \\right\)        # up to \right)
                  )|xs;
            while( $body =~ m|$leftRightRegEx|xs ){
               $storageCount++;
               $body =~ s|$leftRightRegEx|
                    push(@storageArray,{id=>$storageToken.$storageCount,value=>$1});
                    $storageToken.$storageCount;|xse;
            }
            # [a,b)
            # [a,b)
            # [a,b)
            $intervalRegEx =
                qr|(
                    \[               # [
                    (?:
                      (?!
                        (?<!\\)\[    # anything except [
                      ).
                    )*?
                    (?<!\\)
                    \)               # up to )
                  )|xs;
            while( $body =~ m|$intervalRegEx|xs ){
               $storageCount++;
               $body =~ s|$intervalRegEx|
                    push(@storageArray,{id=>$storageToken.$storageCount,value=>$1});
                    $storageToken.$storageCount;|xse;
            }
            # \left(...\right)
            # \left(...\right)
            # \left(...\right)
            my $untilNoNestedLeftRightRegEx = qr|\\left\(
                  (?:
                    (?!
                      (?<!\\right\))
                    ).
                  )*?
                  (?<!\\)
                  \\left\(|xs;
            $leftRightRegEx =
                qr|(
                    \\left\(         # \left(
                    (?:
                      (?!
                       (?:\\left\()  # anything except \left(
                      ).
                    )*?
                    \\right\)        # up to \right)
                  )|xs;
            while( $body =~ m|$untilNoNestedLeftRightRegEx|xs ){
               $storageCount++;
               $body =~ s|$leftRightRegEx|
                    push(@storageArray,{id=>$storageToken.$storageCount,value=>$1});
                    $storageToken.$storageCount;|xse;
            }
            # now store all matched (...)
            my $untilNoNestedParenRegEx = qr|\(
                  (?:
                    (?!
                      (?<!\\)\)
                    ).
                  )*?
                  (?<!\\)
                  \(|xs;
            my $parenRegEx = qr|(
                  \(
                  (?:
                    (?!
                      (?<!\\)\(
                    ).
                  )*?
                  (?<!\\)
                  \))|xs;
            while( $body =~ m|$untilNoNestedParenRegEx|){
               $storageCount++;
               $body =~ s|$parenRegEx|
                    push(@storageArray,{id=>$storageToken.$storageCount,value=>$1});
                    $storageToken.$storageCount;|xse;
            }
            # now make the substitution:
            #   \mathbb{(.*?)}\( (.*?) \)
            # into
            #   \mathbb{$1}\lbrack $2 \rbrack
            $body =~ s|(\\mathbb\{.*?\})\h*\((.*?)\)|$1\\left\\lbrack $2\\right\\rbrack|sg;
            $body =~ s|(\\mathbb\{.*?\})\h*\\left\((.*?)\\right\)|$1\\left\\lbrack $2\\right\\rbrack|sg;
            # finally, put the nested braces/intervals
            # back in to the body
            while(@storageArray){
                my $entry = pop(@storageArray);
                $body =~ s|${$entry}{id}|${$entry}{value}|s;
            }
        }
        $begin.$body.$end;/sgxe

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trying to use "\~" to generate tilde symbol in math mode $$ = \sum_{e \in A} w(e)
   = \sum_{e \in A} w(e)+ \sum_{e \in \{(r,v)| v \in V(G)\}} w(e)
   = w( \~{A} ) $$

I get the following error message:

Error: Please use \mathaccent for accents in math mode for the following code

I'm not sure what's wrong with it. I'm in math mode by using $$  $$, am I not?

A: Text accents and math accents have different syntax in LaTeX: to get Ã, you would use \~{A} in textmode, but \tilde A or \widetilde A (the latter for a wider version) in mathmode.
Here is a table showing how to get different kinds of accents in textmode and mathmode.
Thus, your corrected code is
= \sum_{e \in A} w(e) = \sum_{e \in A} w(e)+ \sum_{e \in {(r,v)| v \in V(G)}} w(e) = w( \tilde A )

A: The immediate problem is solved by replacing the text-mode instruction \~{A} with the math-mode directive \tilde{A}.
You may also want to make the equation both more compact and more readable by (a) introducing a line break in the material set below the third \sum symbol (via a \substack instruction) and (b) eliminating the whitespace that's otherwise inserted to the left and right of that summation symbol (via a \mathclap instruction).

Addendum: For the sake of completeness/reference, here's a list of common accents and how they should be produced in text and math mode, respectively. Note that the positions and, in the case of text-upright versus text-italic font shapes, even the shapes of the accents can differ between text and math modes. In math mode, in contrast, the shapes of the math-accent characters are the same regardless of whether \mathrm ("math roman") or \mathit ("math italics" -- the default) is in effect.

\documentclass{article}
\usepackage{mathtools} % for "\mathclap" macro; loads "amsmath" package
\begin{document}
\[
   = \sum_{e \in A} w(e)
   = \sum_{e \in A} w(e) +
     \sum_{\mathclap{\substack{e \in \{(r,v)\} \\ \text{s.t.}\, v \in V(G)}}} w(e)
   = w(\tilde{A})
\]
\end{document}

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{booktabs,array,lmodern}
\newcolumntype{C}{>{$}c<{$}} % automatic-math version of "c" column type
\begin{document}
\begin{tabular}{@{} l c c >{\itshape}c l C C @{}}
\toprule
Accent name & \multicolumn{3}{c}{Text mode}
            & \multicolumn{3}{c@{}}{Math mode} \\
\cmidrule(lr){2-4} \cmidrule(l){5-7}
            & how to & \multicolumn{2}{c}{result}
            & how to & \multicolumn{2}{c@{}}{result} \\
\midrule
acute             & \verb|\'| & \'A & \'A & \verb|\acute| & \acute{\mathrm{A}} & \acute{A} \\
grave             & \verb|\`| & \`A & \`A & \verb|\grave| & \grave{\mathrm{A}} & \grave{A} \\
circumflex        & \verb|\^| & \^A & \^A & \verb|\hat|   & \hat{\mathrm{A}}   & \hat{A}   \\
squiggle, tilde   & \verb|\~| & \~A & \~A & \verb|\tilde| & \tilde{\mathrm{A}} & \tilde{A} \\
macron, bar       & \verb|\=| & \=A & \=A & \verb|\bar|   & \bar{\mathrm{A}}   & \bar{A}   \\
dot accent        & \verb|\.| & \.A & \.A & \verb|\dot|   & \dot{\mathrm{A}}   & \dot{A}   \\
diereris, Umlaut  & \verb|\"| & \"A & \"A & \verb|\ddot|  & \ddot{\mathrm{A}}  & \ddot{A}  \\
breve             & \verb|\u| &\u{A}&\u{A}& \verb|\breve| & \breve{\mathrm{A}} & \breve{A} \\
caron, check, v-check&\verb|\v|&\v{A}&\v{A}&\verb|\check| & \check{\mathrm{A}} & \check{A} \\
ring              & \verb|\r| &\r{A}& \r{A}&\verb|\mathring|&\mathring{\mathrm{A}}& \mathring{A}\\
\bottomrule
\end{tabular}
\end{document}

A: I solved the issue by replacing \~{A} with \tilde{A}.

A: Just use the package lmodern.
\documentclass{article}
\usepackage{amsmath,amssymb}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{verbatim}

\usepackage{lmodern}

\begin{document}

$$ y = w( \~{A} ) $$

You can also disregard the use of \verb=\~{A}= and use à directly, like the example below:

$$ y = w( Ã ) $$

\end{document}


text:
Q: {{}} in ng-click & ng-repeat This is the code of my HTML

    <button
      ng-repeat="shopli in shopName"
      ng-click="openurl({{'\''+shopli.url+'\''}})"
      class="btn_shopList">
      {{shopli.name}}
    </button>

 ........

And the JS here
var app = angular.module('containArea', []);
app.controller('myCtrl', function($scope) {
    $scope.shopName=[
        {
          "name":'momo購物網',
          "url":'https://buyforfun.biz/2LvEY'
        },
        {
          "name":'金石堂書局',
          "url":'https://joymall.co/2MX4o'
        }
    ];
    $scope.openurl = function(url){
         window.open(url, '_blank');
    }
});

The {{shopli.name}} output correctly
But if I click the button , nothing happened
Could anyone help me to fix it

A: Use the value directly in ng-click function instead of using angular expression {{}}.
ng-click="openurl('\''+shopli.url+'\'')"

var app = angular.module('containArea', []);
app.controller('myCtrl', function($scope) {
  $scope.shopName = [{
      "name": 'momo購物網',
      "url": 'https://buyforfun.biz/2LvEY'
    },
    {
      "name": '金石堂書局',
      "url": 'https://joymall.co/2MX4o'
    }
  ];
  $scope.openurl = function(url) {
    console.log(url);
  }
});

    <button ng-repeat="shopli in shopName" ng-click="openurl(shopli.url)" class="btn_shopList">
      {{shopli.name}}
    </button>


text:
Q: Only first element init as 1 I have an array, ex:
int M[10] = { 1 };

I expected M[0] ~ M[9] will all be filled with 1, but when I printed them out, it doesn't, only M[0] is 1, others are 0.

A: This is a common misconception. Often you see people write things like this
int m[10] = { 0 };

To "initialise all elements to 0"; however, really that just initialises the first element to 0 and the rest are default initialised (to 0, which is why it works). Really they could've just written int m[10] = {};
You have the same problem: you initialise only the first element to 1 then the rest default to 0. You can either specify all the parameters, or use std::fill:
int m[10] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
int n[10];
std::fill(std::begin(n), std::end(n), 1);


text:
Q: Finding duplicates in a CSV file with whitespaces I want to find duplicates in a CSV file that contains whitespaces and newlines. sort -u and uniq (on a sorted file) bomb out due to spaces and/or in the data.
The data looks something like:
1,"foo","foo bar",false
2,"baz","bat",true
5,,"something with a space
and a newline.",false

That is, comma-separated, with newlines demarcating rows.
The data can have spaces in any of its columns, so using sort -u or uniq and specifying the key is not an option.
Final sort order is not important.


text:
Q: How To Overwrite A File If It Already Exists? I'm making a music player. It has 2 forms; one is the main area where you play music. The second form has a CheckedListBox where you select the mp3s you want.
When I click a button, it saves the selection in a .txt file so I can access them in the first form, where I'll put the strings into the paths for music player to find the files.
This is the code in my second form, where I save the selected songs into .txt files.
private void selectbtn_Click(object sender, EventArgs e)
{
    if (File.Exists(@"C:\Users\Me\Desktop\JAM_MACHINE\JAMS\record.txt"))
    {
       File.WriteAllText(@"C:\Users\Me\Desktop\JAM_MACHINE\JAMS\record.txt", String.Empty);
    }

    string[] checkedtitles = new string[checkedListBox1.CheckedItems.Count];

    for (int ii = 0; ii < checkedListBox1.CheckedItems.Count; ii++)
    {
        checkedtitles[ii] = checkedListBox1.CheckedItems[ii].ToString();
    }
    string selectedSongs = String.Join(Environment.NewLine, checkedtitles);

    songRecord.writeRecord(selectedSongs); //I initialised the class containing streamwriter/reader, and called it songRecord
    this.Close();
}

The problem is, whenever I close the program and open it again, I can't rewrite/clear the .txt file. It just adds on to the existing file. Is there something I'm not doing right?
Here is my streamreader/writer codes. I'm pretty sure I closed it after running too, but perhaps somebody can figure out what's wrong:
namespace songss
{
    class DataRecord
    {
    public void writeRecord(string line)
    {
        StreamWriter sw = null;
        try
        {
            sw = new StreamWriter(@"C:\Users\Me\Desktop\JAM_MACHINE\record.txt", true);
            sw.WriteLine(line);
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("Error: File not found.");
        }
        catch (IOException)
        {
            Console.WriteLine("Error: IO");
        }
        catch(Exception)
        {
            throw;
        }
        finally
        {
            if (sw != null)
                sw.Close();
        }
        }

 public void readRecord()
    {
        StreamReader sr = null;
        string myInputline;
        try
        {
            sr = new StreamReader(@"C:\Users\Me\Desktop\JAM_MACHINE\record.txt");
            while ((myInputline = sr.ReadLine()) != null) ; //readline reads whole line
            Console.WriteLine(myInputline);
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("Error: File not found");
        }
        catch(IOException)
        {
            Console.WriteLine("Error: IO");
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            if (sr != null)
                sr.Close();
        }
    }
    }
    }

A: WriteAllText
File.WriteAllText should do what you want.

Creates a new file, writes the specified string to the file, and then
  closes the file. If the target file already exists, it is overwritten.

StreamWriter
The StreamWriter class also has an option to overwrite/append:

Initializes a new instance of the StreamWriter class for the specified
  file by using the default encoding and buffer size. If the file
  exists, it can be either overwritten or appended to.

public StreamWriter(
    string path,
    bool append
)

Example:
using (StreamWriter writer = new StreamWriter("test.txt", false)){
    writer.Write(textToAdd);
}

Looking at your code, you're passing in true which means append.
sw = new StreamWriter(@"C:\Users\Me\Desktop\JAM_MACHINE\record.txt", true);
sw.WriteLine(line);

.NET Compact Framework
If you're stuck on a .NET version that doesn't support anything (e.g. compact framework), you can also implement WriteAllText yourself:
static void WriteAllText(string path, string txt) {
    var bytes = Encoding.UTF8.GetBytes(txt);
    using (var f = File.Open(path, FileMode.Create)) {
        f.Write(bytes, 0, bytes.Length);
    }
}

A: Use this
File.WriteAllText(@"C:\Users\Me\Desktop\JAM_MACHINE\JAMS\record.txt", line);

instead of
sw = new StreamWriter(@"C:\Users\Me\Desktop\JAM_MACHINE\record.txt", true);
sw.WriteLine(line);

A: Refer this link for Solution Provided by Microsoft:
(https://msdn.microsoft.com/en-us/library/system.io.file.appendtext(v=vs.110).aspx)
Here is code to append existing File:
StreamWriter writer = File.AppendText(Filepath);
writer.WriteLine(content);
writer.Close();


text:
Q: Expire all cookies on domain and subdirectories in 1 link I know there are lots of posts about this and bookmarklets that have been mentioned but none of them seem to actually work fo my particular case.
I'm doing a website for somebody whose users are not tech savvy and wouldnt want to clear their entire cookie collection out.
I've moved some forum software cookie path from domain.com/forums to domain.com/ however people are now having issues. I guess its due to cookie clashes.
I need a single javascript link that clears all the cookies from both domain.com and domain.com/forums. the link will be located inside /forums/ if that makes a difference? and all the names of the cookies are unknown.
Could somebody please give me a quick bookmarklet/snippet/link that would perform this task please?
thanks


text:
Q: Event listener for window.fetch Is there a way to globally monitor all window.fetch requests? I know it works with Promises, but I need to get notified whenever any of such requests is done (fail/success) and I have no access to the functions which invoke these or which are success/fail handlers.
So basically I'm looking for something like:
window.addEventListener('fetch', ev => {
  if (ev.type == 'FetchSuccess') {
    // process ev.response
  }
});

A: You can overwrite the fetch function the following way:
var oldFetch = fetch;  // must be on the global scope
fetch = function(url, options) {
    var promise = oldFetch(url, options);
    // Do something with the promise
    return promise;
}

This way you can get control over the returned promises while it maintains it's usage.


text:
Q: My LSTM network is very slow. What to optimize? I have following deeplearning4j network (and other similar)
MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder()
            .updater(new Adam.Builder().learningRate(2e-2).build())
            .l2(1e-5)
            .weightInit(WeightInit.XAVIER)
            .gradientNormalization(GradientNormalization.ClipElementWiseAbsoluteValue).gradientNormalizationThreshold(1.0)
            .list()
            .layer(0, new LSTM.Builder().nIn(vectorSize).nOut(256)
                .activation(Activation.TANH).build())
            .layer(1, new RnnOutputLayer.Builder().activation(Activation.SOFTMAX)
                .lossFunction(LossFunctions.LossFunction.MCXENT).nIn(256).nOut(2).build())
            .build();

Unfortunately training is very slow. My vector size is 400. I have huge amount of samples. What would you suggest to optimize for faster training? Should I decrease inner layer size? Thanks

A: Well from my own experience I would first definitely try Activation.SOFTSIGN as your activation function. It does not saturate as quickly, improving its robustness to vanishing gradients.


text:
Q: I don't understand ifstream In my textbook it says that ifstream is an istream for reading from a file. Later down the page, there is a comment next to an example:
ifstream ist(name.c_str()); // ist is an input stream for the file named name.

I'm a little confused what the difference is between ifstream and ist().

A: ist is the instance of ifstream you will be using. There is a type - ifstream - which can be the type of many variables.
You could have ist, ist2, ist3, xpto, all of them being an ifstream.
ifstream is the type.


text:
Q: Enable/Disable chrome extension from java desktop application I have developed a chrome extension which does particular job and tries to connect back to a java desktop application.
Now what I want is, the chrome extension should get enabled only when desktop(java) application is opened and similarly it should get disabled whenever I close the desktop application.
Can I manage this using java?
Or any other way/ CMD is it possible?

A: Basically, you would need some ways to exchange message between extensions and native apps, for this purpose, there are many optional ways, such as Native Messaging, WebSocket, or simple http server/client.
Depends on what you choose to use, the implementation details may differ. However their ideas are similar:

*

*Start the connection from extension and keep the connection for each side

*Save a flag in extension side to mark whether your extension should be enabled

*Once the connection is lost, revert the flag and disable the functionality of the extension


text:
Q: Magento 2 : get csv file download in frontend based on click of button How can i download csv file in magento 2 using below code is from controller,
public function execute(){
    $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
    $heading = array('Name','Sku','Qty','Price','Manufacturer');
    $outputFile = "products_". date('Ymd_His').".csv";
    $handle = fopen($outputFile, 'w');
    fputcsv($handle, $heading);

               $this->downloadCsv($outputFile);
                $resultRedirect->setPath('*/*');
                return $resultRedirect;
}
public function downloadCsv($file){
        if (file_exists($file)) {
            //set appropriate headers
            header('Content-Description: File Transfer');
            header('Content-Type: application/csv');
            header('Content-Disposition: attachment; filename='.basename($file));
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file));
            ob_clean();flush();
            readfile($file);
        }
    }

Csv file not downloaded using above code. Data are getting right for me.
Thanks.

A: I have checked your code. You just need to remove below code:
$resultRedirect->setPath('*/*');
return $resultRedirect;

You have no need to redirect any page while downloading any CSV file.
I Hope this will help you.


text:
Q: Optimizing simple search script in PowerShell I need to create a script to search through just below a million files of text, code, etc. to find matches and then output all hits on a particular string pattern to a CSV file.
So far I made this;
$location = 'C:\Work*'

$arr = "foo", "bar" #Where "foo" and "bar" are string patterns I want to search for (separately)

for($i=0;$i -lt $arr.length; $i++) {
Get-ChildItem $location -recurse | select-string -pattern $($arr[$i]) | select-object Path | Export-Csv "C:\Work\Results\$($arr[$i]).txt"
}

This returns to me a CSV file named "foo.txt" with a list of all files with the word "foo" in it, and a file named "bar.txt" with a list of all files containing the word "bar".
Is there any way anyone can think of to optimize this script to make it work faster? Or ideas on how to make an entirely different, but equivalent script that just works faster?
All input appreciated!

A: Let's suppose that 1) the files are not too big and you can load it into memory, 2) you really just want the Path of the file, that matches (not the line etc.).
I tried to read the file only once and then iterate through the regexes. There is some gain (it's a faster then the original solution), but the final result will depend on other factors like file sizes, count of files etc.
Also removing 'ignorecase' makes it faster a little bit.
$res = @{}
$arr | % { $res[$_] = @() }

Get-ChildItem $location -recurse |
  ? { !$_.PsIsContainer } |
  % { $file = $_
      $text = [Io.File]::ReadAllText($file.FullName)
      $arr |
        % { $regex = $_
            if ([Regex]::IsMatch($text, $regex, 'ignorecase')) {
              $res[$regex] = $file.FullName
            }
        }
  }
$res.GetEnumerator() | % {
  $_.Value | Export-Csv "d:\temp\so-res$($_.Key).txt"
}

A: If your files are not huge and can be read into memory then this version should work quite faster (and my quick and dirty local test seems to prove that):
$location = 'C:\ROM'
$arr = "Roman", "Kuzmin"

# remove output files
foreach($test in $arr) {
    Remove-Item ".\$test.txt" -ErrorAction 0 -Confirm
}

Get-ChildItem $location -Recurse | .{process{ if (!$_.PSIsContainer) {
    # read all text once
    $content = [System.IO.File]::ReadAllText($_.FullName)
    # test patterns and output paths once
    foreach($test in $arr) {
        if ($content -match $test) {
            $_.FullName >> ".\$test.txt"
        }
    }
}}}

Notes: 1) mind changed paths and patterns in the example; 2) output files are not CSV but plain text; there is not much reason in CSV if you are interested just in paths - plain text files one path per line will do.


text:
Q: How to set condition to remove from array? I'm trying to unset one record from array but I can't manage it, so I'm asking for someone to help me.
Logic I'm trying to achieve is:
User has an item with possible three categories, he posts a form and than I iterate over array and try to see if category3 matches, if not I go to category2, if not I go to category1. If I find one of the categories that matches array and category asked in form I proceed , but If I don't find any of the categories I unset that record in array.Below you will see an example what I've done now.
I can't get the proper result. Either I unset all the records or unset the record that should stay. I'm trying different conditions for last three days without success. Record I'm talking about is with a key 5.
This is my array:
    array (size=5)
    0 =>
    array (size=9)
      'cost_no' => string 'D01' (length=3)
      'cost_name' => string 'Carina' (length=6)
      'cost_type' => string 'Customs' (length=7)
      'cost_measure' => string 'Percent' (length=7)
      'cost_amount' => string '5.00' (length=4)
      'cost_id' => int 7
      'group1' => string '' (length=3)
      'group2' => string '' (length=3)
      'group3' => string '' (length=3)
  1 =>
    array (size=9)
      'cost_no' => string 'D02' (length=3)
      'cost_name' => string 'Banka' (length=5)
      'cost_type' => string 'Bank' (length=4)
      'cost_measure' => string 'Percent' (length=7)
      'cost_amount' => string '0.15' (length=4)
      'cost_id' => int 8
      'group1' => string '' (length=3)
      'group2' => string '' (length=3)
      'group3' => string '' (length=3)
  2 =>
    array (size=9)
      'cost_no' => string 'D03' (length=3)
      'cost_name' => string 'Ĺ pediter' (length=9)
      'cost_type' => string 'Transport' (length=9)
      'cost_measure' => string 'Percent' (length=7)
      'cost_amount' => string '0.50' (length=4)
      'cost_id' => int 9
      'group1' => string '' (length=3)
      'group2' => string '' (length=3)
      'group3' => string '' (length=3)
  3 =>
    array (size=9)
      'cost_no' => string 'D04' (length=3)
      'cost_name' => string 'Troškovi firme' (length=15)
      'cost_type' => string 'Tax' (length=3)
      'cost_measure' => string 'Percent' (length=7)
      'cost_amount' => string '21.00' (length=5)
      'cost_id' => int 10
      'group1' => string '' (length=3)
      'group2' => string '' (length=3)
      'group3' => string '' (length=3)
  5 =>
    array (size=9)
      'cost_no' => string 'C1' (length=2)
      'cost_name' => string 'Cost only for this group' (length=24)
      'cost_type' => string 'Warehouse' (length=9)
      'cost_measure' => string 'Percent' (length=7)
      'cost_amount' => string '12.00' (length=5)
      'cost_id' => int 12
      'group1' => string 'ACC_P' (length=5)
      'group2' => string '1401' (length=4)
      'group3' => string '' (length=3)

This is foreach and condition I tried to use to unset if non of the categories match ( it has to check from category3 to category 1).
foreach ($cost_array as $key1 => $value1) {

            if (isset($form_group3) AND isset($value1['group3']) AND $value1['group3'] != $form_group3) {

                if (isset($form_group2) AND isset($value1['group2']) AND $value1['group2'] != $form_group2) {

                    if (isset($form_group1) AND isset($value1['group1']) AND $value1['group1'] != $form_group1) {

                    } else {
                        unset($cost_array[$key1]);
                    }
                } else {
                    unset($cost_array[$key1]);
                }
            } else {
                unset($cost_array[$key1]);
            }
}

Groups user posts from form:
$form_group1 = mysqli_real_escape_string($conn_mysqli, $_POST['group1']);
$form_group2 = mysqli_real_escape_string($conn_mysqli, $_POST['group2']);
$form_group3 = mysqli_real_escape_string($conn_mysqli, $_POST['group3']);


text:
Q: If the language has only one predicate, can we simplify the quantifiers? Assume that our language has only one predicate symbol. Then $(\forall x_1 \forall x_2 )(\phi)$ is equivalent to  $(\forall x)(\phi')$ where $\phi'$ is a formula obtained by replacing all occurrences of $x_1$ and $x_2$ to $x$.
I wonder if this proposition is correct. .

A: Even with arity $1$ this breaks down.
Consider the sentence $$(*)\quad\forall x_1\forall x_2(P(x_1)\vee\neg P(x_2)).$$ This is equivalent to $$(**)\quad(\forall x(P(x)))\vee (\forall x(\neg P(x))).$$
(Why? Clearly the latter implies the former, so suppose that the latter failed. Then we have $a,b$ with $\neg P(a)$ and $P(b)$. Now in $(*)$ set $x_1=a$ and $x_2=b$.)
On the other hand, the one-variable version $$(\dagger)\quad\forall x(P(x)\vee\neg P(x))$$ is a tautology. So they're not in general equivalent.

Replacing my original second example which used both equality and a predicate symbol:
In fact, we don't need non-logical symbols at all - consider the sentence $$\forall x_1\forall x_2(x_1=x_2),$$ which is not a tautology but transforms into one under the operation you describe.
Of course $=$ basically is a binary relation, it's just that it's a "logical" as opposed to "non-logical" one; for that reason, the first example above is really the best one. However, it's still worth noting how equality alone brings enough complexity into the picture.

A: Work in the language of graphs, which has a single binary predicate symbol $R(x,y)$ whose interpretation is "$x$ is connected to $y$".
Consider the following formula $\varphi$:$$\forall x_1\forall x_2(x_1\neq x_2\rightarrow R(x_1,x_2))$$
Then $\varphi'$ holds in every structure, while $\varphi$ doesn't


text:
Q: Change position of navigationItem.leftBarButtonItem I have a custom back button created as UIBarButtonItem and inserted to navigationItem.leftBarButtonItem. I need to move it a little bit to the left. I was able to move with an image of UIBarButtonItem, but hit area of the button remained on original place.

A: Try to create a custom UIButton with the frame you want and after that create the UIBarButtonItem(customView: UIButton) like this for example
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 45, height: 40))
let yourBarButton = UIBarButtonItem(customView: button)


text:
Q: how to get the text content of an element with no ID in javascript I want to get a particular text content of the heading element which does not have any ID associated with it. What javascript code should I use to get the content 'I only want this one'.
var elements = document.querySelectorAll('.one span');
console.log(elements[0].text);

This code is not giving the desired output

I don't want this
I only want this one

I expect the output to be 'I only want this one', but I am getting undefined...

A: You're looking to select the text node, which is not an element, so you can't select it immediately with querySelectorAll (or querySelector) - so, first select the parent (the .one), then navigate to its last child:

const parent = document.querySelector('.one');
const textNode = parent.lastChild;
console.log(textNode.textContent);

  I don't want this
I only want this one

Note that if you just want the first element which matches a particular selector string, it's more appropriate to use querySelector (which returns that element), rather than querySelectorAll (which returns a collection, from which you must proceed to select the first element in it).


text:
Q: Flutter Provider, where to place a function call to load data from firestore database I'm currently working on an app and I want to get some data of a user's friends. Ideally, after sign in, this information is loaded up onto the screen for viewing.
I initially made my function call to do this within the "build" method of my HomeScreen, but this caused an infinite loop as the function call ended with "notifyListeners()".
That being said, where should I place my call to avoid a loop, while still having the UI update once the data has been fetched from the database?

A: You should have a look at the FutureBuilder widget, which provides great functionality to load async data and show the result once available. While the data is loading, or if your code runs into an error, you can show a different widget. Essentially it works like this:
FutureBuilder<String>(
  future: _yourFuture,
  builder: (context, snapshot) {
    switch (snapshot.connectionState) {
      case ConnectionState.active:
      case ConnectionState.waiting:
        // Return loading indicator
        return Container();
      case ConnectionState.done:
        if (snapshot.hasError) {
          // Return error
          return Container();
        } else if (snapshot.hasData) {
          // Data loaded => use snapshot.data to access it
          return Container();
        }
  }
})

I would not recommend to load data during initState(), since this method cannot be async and thus, you cannot await your result.
I hope that helps.


text:
Q: Oscillation of the function at each point
I would like to find the oscillation of the function $f:\Bbb R^2\to\Bbb R,$ $$f(x,y)=\begin{cases}\sin\left(\frac1x\right)+\sin\left(\frac1y\right),&x,y\ne 0\\0, x,=0\text{ or } y=0.\end{cases}$$

This is our definition:

Let $A\subset\Bbb R^2$ and $f:A\to\Bbb R$ any function. Oscillation $O(f,c)$ of the function $f$ at the point $c\in A$ is defined as $$O(f,c)=\inf_{U\ni c\\ U\text{ open }}\sup_{x_1,x_2\in U\cap A}|f(x_1)-f(x_2)|.$$

And a lemma:

Function $f:A\to\Bbb R$ is continuous at $c\in A$ if and only if $O(f,c)=0.$

My attempt:
According to the lemma, since the given function is continuous on $S:=\{(x,y)\in\Bbb R^2\mid xy\ne 0\},O(f,c)=0,\forall c\in S_1.$
Now, suppose $x_0\ne 0$ and $y_0=0.$
For any $\varepsilon>0,$ there is $n\in\Bbb N$ s. t. $\left(x_1,\frac{2\pi}{4n+1}\right),\left(x_2,\frac{2\pi}{4n+3}\right)\in B((x_0,0);\varepsilon)$ for $x_1,x_2$ close enough to $x_0$ since $x\mapsto\sin\left(\frac1x\right)$ is uniformly continuous on segments not containing $0$.
Then $$f\left(x_1,\frac{2\pi}{4n+1}\right)-f\left(x_2,\frac{2n}{4n+3}\right)\to 2,$$
and I think this is the oscillation at such point, but I'm not sure if this is right.
If $x=y=0,$ then we can consider expressions $$f\left(\frac{2\pi}{4n+1}, \frac{2\pi}{4n+1}\right)-f\left(\frac{2\pi}{4n+3}, \frac{2\pi}{4n+3}\right),$$
but $|f(x_1,y_1)-f(x_2,y_2)|\le 4,\forall (x_1,y_1),(x_2,y_2)\in\Bbb R^2,$ so I think this works.
Can somebody help me with the case of the axes?

A: On your attempt
Excellent attempt. Finishing off the continuity points was important , then dealing with $(0,0)$ separately was very good insight because you recognized the freedom that was available.
However, I am not fully sure that your expressions for the exact numbers are on point. For example, with $\frac{2\pi}{4n+1}$, the reciprocal is $\frac{4n+1}{2 \pi}$, and I'm not sure you intended the $\pi$ to go to the bottom , and probably preferred it to remain on top. Then your intentions were right, and you were likely very close to the candidate. However, you were unsure as to how you produced the optimal subsequence at each point, and this is where I'm going to share a lovely lemma.

We first start with the following result that immediately connects oscillations to the sequential definition of continuity. It's a long proof but very illustrative because it will help solve a lot of problems regarding oscillation.

Lemma : Suppose that $f : \mathbb R^2 \to \mathbb R$ and $(x,y)$ be a point such that there is some open set $(x,y) \in V$ with $f(x)$ bounded in $V$. Let $$S_{(x,y)} = \{L : \exists (x_n,y_n) \in \mathbb R^2, (x_n,y_n) \to (x,y), f(x_n,y_n) \to L\}$$ Then, $$Osc(f,(x,y)) = \sup S_{(x,y)} - \inf S_{(x,y)}$$ and both are finite quantities.

That is, if we take the set of all limits of $f((x_n,y_n))$ for every subsequence $(x_n,y_n)$ that converges to $(x,y)$ with $f((x_n,y_n))$ convergent, then the range of this set equals the oscillation of $f$, provided that $f$ is bounded on some neighbourhood $V$ of $(x,)$.
The basic idea is the following: every open set $U'$ containing $(x_n,y_n)$, also contains some ball around $(x_n,y_n)$. That ball, is an open set which contains $(x_n,y_n)$ but the supremum of $|f(x_1)-f(x_2)|$ is obviously smaller over that ball , than over $U'$. Therefore, it's enough to consider a supremum over open sets which are balls around the point : and there, one profits from having structure on the reducing balls.
Proof : We begin by showing that if $f$ is bounded on $V$ then both quantities are finite. Let $|f(t)|<M$ on $V$ : then $\sup_{t,s \in V}|f(t)-f(s)| < 2M$ therefore $Osc(f,(x,y)) < 2M$. On the other hand, let $(x_n,y_n) \to (x,y)$ with $f(x_n,y_n)$ convergent to a point $L$. By definition, there exists $N$ such that $n>N$ implies $(x_n,y_n) \in V$ , which implies that $|f(x_n,y_n)| < M$. Consequently, $|L|<M$ and $\inf S_{(x,y)}- \sup S_{(x,y)} < 2M$. Finiteness of both quantities are proved.
Note that $f$ being continuous at $(x,y)$ is equivalent to both $Osc(f,(x,y))=0$ and $S_{(x,y)} = \{f(x,y)\}$ by the sequential definition of continuity. In this case the equality is obvious. Therefore, we will now assume that both are positive finite quantities and prove that both are greater than or equal to the other.

We will first assume that $\sup S_{(x,y)} = X$ and $\inf S_{(x,y)} = Y$. Let $X-Y>\epsilon>0$ be arbitrary. There exist $X',Y' \in S_{(x,y)}$ with $X-X'<\frac \epsilon 4, Y'-Y< \frac\epsilon 4$. In particular, by the triangle inequality, $|X'-Y'| > X-Y - \frac \epsilon 2$.
Now, let $X_{1n}, X_{2n}$ be two sequences that help in satisfying the $S_{(x,y)}$ membership for $X',Y'$ : that is, $X_{1n} \to (x,y)$, $X_{2n}\to (x,y)$, with $f(X_{1n}) \to X', f(X_{2n}) \to Y'$. Let's now note that $f(X_{1n}) - f(X_{2n}) \to X'-Y'$, so that by the $\epsilon-N$ criterion, there exists $N$ such that $n>N$ implies $|f(X_{1n})- f(X_{2n})| > X'-Y'-\frac \epsilon 2 > X-Y-\epsilon$.
Let $U$ be any open set around $(x,y)$, and let $R$ be such that the ball around $(x,y)$ of radius $R$ is contained in $U$. There exists $M$ such that for $m>M$, $X_{1m} , X_{2m}$ will also lie in that ball. Now, for $m>\max \{M,N\}$, we have $X_{1m},X_{2m} \in U$ and $|f(X_{1m})-f(X_{2m})| > X-Y-\epsilon$. In particular, for every $U$, $$\sup_{x_1,x_2 \in U} |f(x_1)-f(x_2)| \geq |f(X_{1m})-f(X_{2m})| > X-Y-\epsilon$$
for all $U$ open sets containing $x$. Taking the infimum over all $U$ , $$
\inf_{(x,y) \in U, U \text{ open}} \sup_{x_1,x_2 \in U} |f(x_1)-f(x_2)| \geq X-Y-\epsilon
$$
for all $\epsilon>0$. Taking $\epsilon \to 0$ gives $$
\inf_{(x,y) \in U, U \text{ open}} \sup_{x_1,x_2 \in U} |f(x_1)-f(x_2)| \geq X-Y
$$
That is, we've shown that the LHS is bigger than or equal to the RHS.

Now, let's go the other way. Let's prove something intermediate : if $r_n$ is a sequence of positive reals decreasing to $0$, and $B_{r_n} = \{t : \|t - (x,y)\| < r_n\}$ then $Osc(f,(x,y)) = \lim_{n \to \infty} \sup_{t,s \in B_{r_n}} |f(t)-f(s)|$. The limit exists as the limit of a decreasing sequence bounded below by $0$, and consists of finite quantities for $n>N$ where $B_{r_N} \subset V$.
To prove this note that $\sup_{t,s \in B_{r_n}} |f(t)-f(s)| \geq Osc(f,(x,y))$ by definition, so taking $n \to \infty$ gives RHS $\geq$ LHS above. For the other way, if $U$ is any open set, there is some $N$ such that $n>N$ implies $B_{r_n} \subset U$. Therefore, $$\sup_{t,s \in U} |f(t)-f(s)| \geq \sup_{t,s \in B_{r_n}} |f(t)-f(s)|$$ for all $n>N$, and taking the limit, $\sup_{t,s \in U} |f(t)-f(s)| \geq \lim_{n \to \infty}\sup_{t,s \in B_{r_n}} |f(t)-f(s)|$. Taking the infimum over $U$ on the LHS finishes the proof that LHS $\geq$ RHS, as desired.
Armed with this, we now proceed to show our result. Let $Osc(f,(x,y))>\epsilon>0$. Let $r_n$ be a sequence of positive reals decreasing to $0$. For every $n$, pick $x_{1n},x_{2n} \in B_{r_n}$ such that $$\sup_{t,s \in B_{r_n}} |f(t)-f(s)| < |f(x_{1n})- f(x_{2n})| + \epsilon$$
Now, $x_{1n},x_{2n} \to (x,y)$ because they belong in balls around $(x,y)$ of progressively smaller radius. Note that $f(x_{1n}), f(x_{2n})$ need not be convergent : but here, we play the subsequence trick. Indeed, pick $N$ with $B_{r_N} \subset U$.
Note that $f(x_{1n})$ is bounded for $n>N$. Therefore, it has a convergent subsequence , say $f(x_{1n_k}) \to L_1$, by the Bolzano-Weierstrass theorem. Now, note that $f(x_{2n_k})$ is bounded for $k>K$, so it has a convergent subsequence, say $f(x_{2n_{k_l}}) \to L_2$, and of course $f(x_{1n_{k_l}}) \to L_1$. For this subsequence $n_{k_l}$ we have :
$$
\sup_{t,s \in B_{r_{n_{k_l}}}} |f(t)-f(s)| < |f(x_{1n_{k_l}})- f(x_{2n_{k_l}})| + \epsilon$$
Let $l \to \infty$ and use the intermediate result along with the limits and continuity of $|\cdot|$ to see that $$
Osc(f,(x,y)) \leq |L_1-L_2| + \epsilon \leq \sup S_{(x,y)} - \inf S_{(x,y)} + \epsilon
$$
Letting $\epsilon \to 0$ completes the proof of the other side. $\blacksquare$

With the lemma, let's solve this question. The first point to note is that it can be applied since $f(x,y) \leq 2$ everywhere. Of course, $f$ is continuous on $xy \neq 0$ so here the oscillation is zero.
We know that $Osc(f,(0,0)) \leq 4$ since any function values cannot exceed $2$. However, consider the sequences $$
x_n = y_n = \frac 1{2n\pi + \frac \pi 2} \\
x'_n = y'_n = \frac{1}{2n\pi + 3\frac \pi 2}
$$
then $(x_n,y_n) \to (0,0), (x_n',y_n') \to (0,0)$ and yet $f(x_n,y_n) = 2, f(x'_n,y'_n) =-2$ so it's obvious that the respective limits are $2$ and $-2$, whose difference is $4$. It follows that $Osc(f,(0,0)) = 4$.
Now, suppose that $x=0,y \neq 0$. Let's take any sequence $(x_n,y_n)$ converging to $(0,y)$. The point is, this implies $y_n \to y$, and therefore by continuity at non-zero $y$, $\sin \frac 1{y_n} \to \sin \frac 1y$. Therefore, in particular, if $(x_n,y_n)$ and $(x'_n,y'_n)$ both converge to $(0,y)$ and both $\lim_{n \to \infty} f(x_n,y_n), \lim_{n \to \infty} f(x'_n,y'_n)$ exist, we must have that the limit of their difference exists. However, $$
f(x_n,y_n) - f(x'_n,y'_n) = \sin\frac 1{x_n} - \sin \frac 1{x'_n} + \left(\sin \frac 1{y_n} - \sin \frac 1{y'_n}\right)
$$
and as you take the limit, it follows that $\sin \frac 1{y_n} - \sin \frac 1{y'_n} \to 0$, therefore the difference between the limits is at most $2$. Therefore, it follows that $Osc(f,(0,y)) \leq 2$.
However, you can once again consider two subsequences :
$$
x_n = \frac 1{2\pi n + \frac \pi 2}, y_n = y
$$
and $$
x'_n = \frac 1{2 \pi n + \frac {3 \pi}2} , y_n = y
$$
then both $(x_n,y_n)$ and $(x'_n,y_n)$ converge to $(0,y)$. However, note that $f(x_n,y_n) = 1+\sin \frac 1y$ and $f(x'_n,y_n) = -1 + \sin \frac 1y$ for all $n$. It follows that the subsequential limits are also $1+\sin\frac 1y$ and $-1 + \sin \frac 1y$ : their difference is $2$. It follows from the lemma that $Osc(f,(0,y)) \geq 2$. Therefore, the oscillation equals $2$.
At points $(x,0)$ with $x \neq 0$, the same argument applies symmetrically to show that the oscillation equals $2$. In total, you get the function $$
Osc(f,(x,y)) = \begin{cases}
0 & xy=0\\
4 & x=y=0 \\
2 & \text{ otherwise}
\end{cases}
$$


text:
Q: How to upload photo in laravel using AngularJs and store into databse? Here is my Index.php File that describe Form of new record Insert with file upload. here is also my controller file, model file and Angular model file and also javascript file. please help me to insert record with image in to database (mongo db). when i hide code of image upload then record added successfully in to database table but when i add file upload tag then it's not working. It showws "ReferenceError: response is not defined" Error

Employees Database

<input type="text"  value="Search" ng-model="searchquery"  class="form-control"  placeholder="Search" style="margin-top: 20px;margin-bottom: 10px;">

                    ID

                    Name
                    Email
                    Contact No
                    Position
                    <button id="btn-add" class="btn btn-primary btn-xs" ng-click="toggle('add', 0)">Add New Employee</button>

                    {{((currentPage-1) *itemsPerPage)+($index + 1)}}

                    {{ employee.name }}
                    {{ employee.email }}
                    {{ employee.contact_number }}
                    {{ employee.position }}

View
                <select ng-model="viewby" ng-change="setItemsPerPage(viewby)"><option>3</option><option>5</option><option>10</option></select> records at a time.

                <uib-pagination total-items="totalItems" ng-model="currentPage" ng-change="pageChanged()" class="pagination-sm" items-per-page="itemsPerPage"></uib-pagination>

                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

{{form_title}}

                        <form name="frmEmployees" class="form-horizontal" novalidate="" enctype="multipart/form-data">

                                Name

                                    <input type="text" class="form-control has-error" id="name" name="name" placeholder="Fullname" value="{{name}}"
                                    ng-model="employee.name" ng-required="true">
                                    Name field is required

                                Email

                                    <input type="email" class="form-control" id="email" name="email" placeholder="Email Address" value="{{email}}"
                                    ng-model="employee.email" ng-required="true">
                                    Valid Email field is required

                                Contact Number

                                    <input type="text" class="form-control" id="contact_number" name="contact_number" placeholder="Contact Number" value="{{contact_number}}"
                                    ng-model="employee.contact_number" ng-required="true">
                                Contact number field is required

                                Position

                                    <input type="text" class="form-control" id="position" name="position" placeholder="Position" value="{{position}}"
                                    ng-model="employee.position" ng-required="true">
                                Position field is required

                                Photo

                                    <input ng-model="employee.image" type="file" class="form-control" accept="image/*" onchange="angular.element(this).scope().uploadedFile(this)" >

                        </form>

                        <button type="button" class="btn btn-primary" id="btn-save" ng-click="save(modalstate, id)" ng-disabled="frmEmployees.$invalid">Save changes</button>

AngularJS code:
app.controller('employeesController', function($scope, $filter, $http, API_URL) {
    //retrieve employees listing from API
    $http.get(API_URL + "employees").then(successCallback, errorCallback);
    function successCallback(response){
        //success code
        $scope.employees = response.data;
        $scope.viewby = '10';
        $scope.totalItems = response.data.length;
        //alert($scope.totalItems);
        $scope.currentPage = '1';
        $scope.itemsPerPage = $scope.viewby;
        $scope.maxSize = '10'; //Number of pager buttons to show
        $scope.setPage = function (pageNo) {
          $scope.currentPage = pageNo;
        };
        $scope.pageChanged = function() {
          console.log('Page changed to: ' + $scope.currentPage);
        };
        $scope.setItemsPerPage = function(num) {
          $scope.itemsPerPage = num;
          $scope.currentPage = 1; //reset to first page
        }

        $scope.noOfPages = Math.ceil($scope.employees.length/$scope.maxSize);
        //alert($scope.noOfPages);
        $scope.filter = function() {
            $timeout(function() {
                $scope.noOfPages = Math.ceil($scope.filtered.length/$scope.maxSize);
            }, 10);
        };
    }
    function errorCallback(error){
        //error code
    }

    //show modal form
    $scope.toggle = function(modalstate, id) {
        $scope.modalstate = modalstate;

        switch (modalstate) {
            case 'add':
                $scope.form_title = "Add New Employee";
                break;
            case 'edit':
                $scope.form_title = "Employee Detail";
                $scope.id = id;
                $http.get(API_URL + 'employees/' + id).then(successCallback, errorCallback);
                        function successCallback(response){
                            //success code
                            console.log(response);
                            $scope.employee = response.data;
                        }
                        function errorCallback(error){
                            //error code
                        }
                break;
            default:
                break;
        }
        console.log(id);
        $('#myModal').modal('show');
    }
    //save new record / update existing record
    $scope.save = function(modalstate, id) {
        $scope.frmEmployees.image = $scope.files[0];
        var url = API_URL + "employees";
        //append employee id to the URL if the form is in edit mode
        if (modalstate === 'edit'){
            url += "/" + id;
            //alert(url);
        }
        $http({
            method: 'POST',
            url: url,
            transformRequest: function (data) {
                  var formData = new FormData();
                  formData.append("image", $scope.employee.image);
                  //alert(formData);
                  return formData;
              },
            data: $.param($scope.employee),
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        })
        .then(success, error);
            function success(response){
                console.log(response);
                location.reload();
            }
            function error(error){
                console.log(response);
                alert('This is embarassing. An error has occured. Please check the log for details');
            }
    }

    $scope.uploadedFile = function(element) {
            $scope.currentFile = element.files[0];
            var reader = new FileReader();

            reader.onload = function(event) {
              $scope.image_source = event.target.result

              $scope.$apply(function($scope) {
                $scope.files = element.files;
              });
            }
                    reader.readAsDataURL(element.files[0]);
          }

    //delete record
    $scope.confirmDelete = function(id) {
        var isConfirmDelete = confirm('Are you sure you want this record?');
        if (isConfirmDelete) {
            $http({
                method: 'DELETE',
                url: API_URL + 'employees/' + id
            })
                    .then(success, error);
            function success(response){
                console.log(response);
                location.reload();

            }
            function error(error){
                console.log(response);
                alert('This is embarassing. An error has occured. Please check the log for details');
            }
        } else {
            return false;
        }
    }
});
/*app.filter('startFrom', function() {
    return function(input, start) {
      start = +start; //parse to int
      return input.slice(start);
    };
});*/

var app = angular.module('employeeRecords', ['ui.bootstrap']).constant('API_URL', 'http://localhost/blog/public/');

PHP code:
<?php

namespace App\Http\Controllers;

use App\Employee;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class Employees extends Controller {

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index($id = null) {
        if ($id == null) {
            return Employee::orderBy('id', 'asc')->get();
        } else {
            return $this->show($id);
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  Request  $request
     * @return Response
     */

    public function store(Request $request) {
        $employee = new Employee;

        $employee->name = $request->input('name');
        $employee->email = $request->input('email');
        $employee->contact_number = $request->input('contact_number');
        $employee->position = $request->input('position');

        $employee->photo =$request->file('photo');
        $filename=$employee->getClientOriginaName();
        storage::put('uploads/'.$filename,file_get_contents($request->file('photo')->getRealPath()));
        $employee->image=$filename;

        $employee->photo = 'uploads/'. $request->input('photo');

        $employee->save();

        return 'Employee record successfully created with id ' . $employee->id;
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id) {
        return Employee::find($id);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function update(Request $request, $id) {
        $employee = Employee::find($id);

        $employee->name = $request->input('name');
        $employee->email = $request->input('email');
        $employee->contact_number = $request->input('contact_number');
        $employee->position = $request->input('position');
        $employee->save();

        return "Sucess updating user #" . $employee->id;
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */

     public function destroy(Request $request)
      {
        $employee = Employee::find($request->id);
        $employee->delete();

            return "Employee record successfully deleted #" . $request->id;
        }

}

<?php

namespace App;

//use Illuminate\Database\Eloquent\Model;
//use Jenssegers\Mongodb\Eloquent\Model;
use Jenssegers\Mongodb\Model as Eloquent;

class Employee extends Eloquent
{
   public $collection = 'employees';
   public $fillable = ['id', 'name', 'email','contact_number','position','photo'];
}

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

Route::get('/', function () {
    return view('index');
});

Route::get('/employees/{id?}', 'Employees@index');
Route::post('/employees', 'Employees@store');
Route::post('/employees/{id}', 'Employees@update');
Route::delete('/employees/{id}', 'Employees@destroy');

A: You may want to check this laravel's Documentation in order to know how to store an uploaded image into a directory and then use query builder or eloquent to insert the filename into database.

A: The 'ReferenceError:' part suggests you are facing a JavaScript error. The second part, about 'response' not being defined, indicates that the response property is not defined. In fact, this is the JavaScript version of the notorious NullReferenceException in .NET ;).
Since the only places in JS code actually accessing 'response' properties are in the two success callbacks, I would start there. On the other hand, in your error callbacks, you are also trying to console.log 'response', which is not a valid variable there (you only specify 'error').
Please try fixing the error callbacks, if that does not work, try commenting those JS code segments where you are trying to use the 'response' variable one by one. Given the rather small piece of code, I think debugging should not be that hard ;).


text:
Q: Allow user to change its picture. Django In my app I allow users to have a profile picture. And I would like them to be able to change it. Surprisingly, I didn't find anything on how to accomplish that.
Here is what I tried:
models.py
        class UserProfile(FacebookProfileModel):
           user = models.OneToOneField(User)
           profilepic = models.ImageField(upload_to="profilepics/", default="blabla.jpg")

my html:
       <form method='post' action='{%url myproject.views.changes %}>
       <div class="controls">
       <input type="file" name="image">
       </div>
       <input type="submit">
       </form>

my view:
      def changes(request):
          if 'image' in request.POST:
             image = request.POST.get('image')
             userprofile.profilepic.url = image
             userprofile.save()

When I do that, I get the following error message:
       'AttributeError at /my/site/
        can't set attribute'

Any idea on how I could accomplish that? Thank you

A: Make sure you request a UserProfile object first, then
Looks like you should use
image = request.FILES['image']
userprofile.profilepic = image

instead of
image = request.POST.get('image')
userprofile.profilepic.url = image

See This example, the views.py section, as Jake said

A: You need to include enctype="multipart/form-data" in your form. Here is an example of how to update an ImageField:
first the update_form.html:
<form method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit" class="save btn btn-default">Update</button>
</form>

Then the form:
from django.contrib.auth import get_user_model

class EditProfile(UserChangeForm):
    class Meta:
        model = get_user_model()
        fields = ('email', 'name', 'avatar')

And finally the view:
def user_edit(request):
    if request.method == 'POST':
        form = EditProfile(request.POST, instance=request.user)
        if form.is_valid():
            form.save()
            if request.FILES.get('avatar', None) != None:
                try:
                    os.remove(request.user.avatar.url)
                except Exception as e:
                    print('Exception in removing old profile image: ', e)
                request.user.avatar = request.FILES['avatar']
                request.user.save()
            return redirect('user:profile', id=request.user.id)
    else:
        form = EditProfile(instance=request.user)
        return render(request, 'user/user-edit.html', {'form': form})


text:
Q: A fibrewise homeomorphism of fibre bundles is a pullback square I know that given a continuous map $f: X \to Y$ and a bundle $F \to Y$ then the map $f^*F \to F$ is a fibrewise homeomorphism.
I vaguely remember reading a converse to this: if we have a fibre bundle map $\phi: E \to F$ covering $f: X \to Y$ on the base and $\phi$ is a fibrewise homeomorphism, then this is a pullback square, i.e. $E \cong f^*F$.
If this is indeed true, does anyone happen to know of a reference for this? Husemoller is my go-to reference for fibre bundle theory, but I couldn't find anything in there. If this is false, is there a straightforward counterexample?

A: I have played around and figured out a proof, but I would still appreciate a textbook reference for this, if anyone knows of one.
As usual, we check that $E \to X$ satisfies the universal property of the pullback.
Given another fibre bundle $V \to X$, with a bundle morphism $\psi: V \to F$ covering $f: X \to Y$ on the base, a bundle morphism $\theta: V \to E$ covering $1_X: X \to X$ on the base which makes the diagram commute (if it exists) must satisfy
$$\phi_x \circ \theta_x = \psi_x: V_x \to F_{f(x)}$$ on the fibre over any point $x \in X$. But since $\phi_x: E_x \to F_{f(x)}$ is a homeomorphism then we must have
$$\theta_x = \phi_x^{-1} \circ \psi_x.$$
Hence, such a morphism $\theta$, if it exists, is necessarily unique. To show existence, it suffices to check that the fibrewise formula for $\theta$ defines a continuous map. I haven't checked continuity yet, but I'm confident it will work.


text:
Q: High Memory Usage Using Python Multiprocessing I have seen a couple of posts on memory usage using Python Multiprocessing module. However the questions don't seem to answer the problem I have here. I am posting my analysis with the hope that some one can help me.
Issue
I am using multiprocessing to perform tasks in parallel and I noticed that the memory consumption by the worker processes grow indefinitely. I have a small standalone example that should replicate what I notice.
import multiprocessing as mp
import time

def calculate(num):
    l = [num*num for num in range(num)]
    s = sum(l)
    del l       # delete lists as an  option
    return s

if __name__ == "__main__":
    pool = mp.Pool(processes=2)
    time.sleep(5)
    print "launching calculation"
    num_tasks = 1000
    tasks =  [pool.apply_async(calculate,(i,)) for i in range(num_tasks)]
    for f in tasks:
        print f.get(5)
    print "calculation finished"
    time.sleep(10)
    print "closing  pool"
    pool.close()
    print "closed pool"
    print "joining pool"
    pool.join()
    print "joined pool"
    time.sleep(5)

System
I am running Windows and I use the task manager to monitor the memory usage. I am running Python 2.7.6.
Observation
I have summarized the memory consumption by the 2 worker processes below.
+---------------+----------------------+----------------------+
|  num_tasks    |  memory with del     | memory without del   |
|               | proc_1   | proc_2    | proc_1   | proc_2    |
+---------------+----------------------+----------------------+
| 1000          | 4884     | 4694      | 4892     | 4952      |
| 5000          | 5588     | 5596      | 6140     | 6268      |
| 10000         | 6528     | 6580      | 6640     | 6644      |
+---------------+----------------------+----------------------+

In the table above, I tried to change the number of tasks and observe the memory consumed at the end of all calculation and before join-ing the pool. The 'del' and 'without del' options are whether I un-comment or comment the del l line inside the calculate(num) function respectively. Before calculation, the memory consumption is around 4400.

*

*It looks like manually clearing out the lists results in lower memory usage for the worker processes. I thought the garbage collector would have taken care of this. Is there a way to force garbage collection?

*It is puzzling that with increase in number of tasks, the memory usage keeps growing in both cases. Is there a way to limit the memory usage?

I have a process that is based on this example, and is meant to run long term. I observe that this worker processes are hogging up lots of memory(~4GB) after an overnight run. Doing a join to release memory is not an option and I am trying to figure out a way without join-ing.
This seems a little mysterious. Has anyone encountered something similar? How can I fix this issue?

A: One potential problem here is that results could be coming back in any order, but because you're reading them in order, it has to store all the results coming back from the processes in memory. The higher num_tasks is, the more results it potentially has to store in memory waiting for your for f in tasks loop to process the result.
In the worst case, the results are calculated in exactly reverse order. In that case, all the results must be held by the multiprocessing module in memory for you before your for f in tasks loop will start processing anything.
It does seem like the amount of memory they're using is higher than I'd expect in this case though (more than it should be just for storing the 1000-10000 numbers returned by the calculate() function), but maybe there's just a high constant overhead per worker result that's stored up.
Have you tried specifying the callback parameter to apply_async, so you can process results immediately as they're completed, or using imap_unordered, so it can give you back results as soon as they're ready?

A: I did a lot of research, and couldn't find a solution to fix the problem per se. But there is a decent work around that prevents the memory blowout for a small cost, worth especially on server side long running code.
The solution essentially was to restart individual worker processes after a fixed number of tasks. The Pool class in python takes maxtasksperchild as an argument. You can specify maxtasksperchild=1000 thus limiting 1000 tasks to be run on each child process. After reaching the maxtasksperchild number, the pool refreshes its child processes. Using a prudent number for maximum tasks, one can balance the max memory that is consumed, with the start up cost associated with restarting back-end process. The Pool construction is done as :
pool = mp.Pool(processes=2,maxtasksperchild=1000)

I am putting my full solution here so it can be of use to others!
import multiprocessing as mp
import time

def calculate(num):
    l = [num*num for num in range(num)]
    s = sum(l)
    del l       # delete lists as an  option
    return s

if __name__ == "__main__":

    # fix is in the following line #
    pool = mp.Pool(processes=2,maxtasksperchild=1000)

    time.sleep(5)
    print "launching calculation"
    num_tasks = 1000
    tasks =  [pool.apply_async(calculate,(i,)) for i in range(num_tasks)]
    for f in tasks:
        print f.get(5)
    print "calculation finished"
    time.sleep(10)
    print "closing  pool"
    pool.close()
    print "closed pool"
    print "joining pool"
    pool.join()
    print "joined pool"
    time.sleep(5)

A: I had to use a combination of maxtasksperchild and chunksize for things to finally get under control. It's hard to say for a general situation as data can differ greatly.
For my situation, I had:

*

*Files ranging from 1-11GB with 20,000 to 150,000 features to individually process and insert into a MongoDB collection. Issues mainly occured with the large files.

*With just providing half the number of processes available on the instance:

*

*memory would just be completely used, likely related to some sort of memory loss from too many tasks per child process, and everything would eventually hang

*Or processes would be mostly sleeping, because the chunksize would be too large and some processes just ended up getting all the heavy data. And so sleeping processes would just be using up memory for no reason and things would eventually hang too.

What worked for me was something like this (the parameters will have to be fiddled with depending on your data):
with Pool(processes=num_processes, maxtasksperchild=10) as pool:
    results = pool.starmap(
        process_feature,
        [(idx, feature) for idx, feature in enumerate(features)],
        chunksize=100,
    )


text:
Q: Local time zone to UTC conversion: DST change happens at wrong time I'm converting a 2013 timeserie in local time (Europe/Paris) with DST to UTC.
I'm using the following code
oasi <- read.csv("oasi.csv", sep=";", skip=28, header=FALSE)
oasi$datetime <- as.POSIXct(oasi[,1], tz="Europe/Paris", format="%d.%m.%Y %H:%M:%S")
oasi$utc <- oasi$datetime
attr(oasi$utc, "tzone") <- "UTC"

When I print the DST change at 27/10/2013 at 02:00 I see the following strange behaviour
                 datetime                 utc
43063 2013-10-27 02:05:00 2013-10-27 00:05:00
43064 2013-10-27 02:15:00 2013-10-27 00:15:00
43065 2013-10-27 02:25:00 2013-10-27 00:25:00
43066 2013-10-27 02:35:00 2013-10-27 00:35:00
43067 2013-10-27 02:45:00 2013-10-27 01:45:00
43068 2013-10-27 02:55:00 2013-10-27 01:55:00
43069 2013-10-27 02:05:00 2013-10-27 00:05:00
43070 2013-10-27 02:15:00 2013-10-27 00:15:00
43071 2013-10-27 02:25:00 2013-10-27 00:25:00
43072 2013-10-27 02:35:00 2013-10-27 00:35:00
43073 2013-10-27 02:45:00 2013-10-27 01:45:00
43074 2013-10-27 02:55:00 2013-10-27 01:55:00
43075 2013-10-27 03:05:00 2013-10-27 02:05:00
43076 2013-10-27 03:15:00 2013-10-27 02:15:00
43077 2013-10-27 03:25:00 2013-10-27 02:25:00
43078 2013-10-27 03:35:00 2013-10-27 02:35:00
43079 2013-10-27 03:45:00 2013-10-27 02:45:00
43080 2013-10-27 03:55:00 2013-10-27 02:55:00

It seems the DST is applied between 02:35 and 02:45 and not at 03:00.
This is very strange and I don't understand why it is happening.
dput output of local datetime for 02:35 and 02:45:
structure(c(1382834100, 1382838300), class = c("POSIXct", "POSIXt"), tzone = "Europe/Paris")

Could be an OS bug? I'm using Win7 64 Bit.

A: I can reproduce like this:
as.POSIXct(c("27.10.2013 02:35:00", "27.10.2013 02:45:00"), tz="Europe/Paris", format="%d.%m.%Y %H:%M:%S")
#[1] "2013-10-27 02:35:00 CEST" "2013-10-27 02:45:00 CET"

You should be aware that your input is ambiguous. The clock was switched one hour back, so this hour exists twice. I don't know how the time zone is chosen in this case. It seems to be somewhat arbitrary.
You need to add the timezone information to your input:
as.POSIXct(c("27.10.2013 02:35:00 +0100", "27.10.2013 02:45:00 +0100"), tz="Europe/Paris", format="%d.%m.%Y %H:%M:%S %z")
#[1] "2013-10-27 02:35:00 CET" "2013-10-27 02:45:00 CET"
as.POSIXct(c("27.10.2013 02:35:00 +0200", "27.10.2013 02:45:00 +0200"), tz="Europe/Paris", format="%d.%m.%Y %H:%M:%S %z")
#[1] "2013-10-27 02:35:00 CEST" "2013-10-27 02:45:00 CEST"

A: As suggested by @roland I tried to finds the DST changes, add the timezone info and eliminates the ambiguity from the initial CET dataset. This code seems to work fine for a one-year dataset.
oasi <- read.csv("oasi.csv", sep=";", skip=28, header=FALSE, stringsAsFactors=FALSE)
dst.index <- which(abs(difftime(as.POSIXct(oasi[,1], tz="UTC", format="%d.%m.%Y %H:%M:%S"),
                      as.POSIXct(c(oasi[1,1], head(oasi[,1],-1)), tz="UTC", format="%d.%m.%Y %H:%M:%S"),
                      units = "mins")) > 10)

oasi[1:dst.index[1],1] <- paste(oasi[1:dst.index[1],1], "+0100")
oasi[dst.index[1]:dst.index[2],1] <- paste(oasi[dst.index[1]:dst.index[2],1], "+0200")
oasi[-1:-dst.index[2],1] <- paste(oasi[-1:-dst.index[2],1], "+0100")

oasi$datetime <- as.POSIXct(oasi[,1], tz="Europe/Paris", usetz=true, format="%d.%m.%Y %H:%M:%S %z")


text:
Q: Why is the quotient map $G\rightarrow G/T$ a fibration? I have just learnt about fibrations and I saw somewhere the following. Given a compact lie group $G$, one can consider a maximal torus $T$ of $G$ then the quotient map $G\rightarrow G/T$ is a fibration. Does anyone know why this is true?
Thanks in advance

A: This is a corollary of a result of Ehresman: If $p:M\rightarrow N$ is a submersion between compact connected manifolds, it is a locally trivial fibration.
https://en.wikipedia.org/wiki/Ehresmann%27s_lemma


text:
Q: SharePoint 2013 Online adding a user to a group using a workflow I am trying to add a user to a security group via a SharePoint 2013 workflow I am currently trying to do this using the Call HTTP web service action and I have 3 dictionary's built. All of this is done inside of an App Step.
Unfortunately I am getting an error back from the Response Content which I am having to email to myself, the error code reads:

{"error":{"code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"An entry without a type name was found, but no expected type was specified. To allow entries without type information, the expected type must also be specified when the model is specified."}}}**

This is currently how my workflow looks:

My call to the web service looks like the followingand I am currently using POST as the Request Type
https://site.sharepoint.com/sites/sitecollection/_api/web/sitegroups/getbyname('group name')/users

Inside of all of the dictionary's I have the following:

The LoginName string is set to be the user who created the current item in that list. This will be the login name of that current user.
I have had this issue for over 3 days and if anyone can help I would really appreciate it.

A: I would like suggest to use 3rd party solution Workflow Actions Pack to solve this task.
It contains Add User to SharePoint Group workflow action.
Moreover it allows you dramatically extend functionality of SharePoint Designer, because it contains more than sixty additional workflow actions.
Please have a look at full list of workflow action in documentation section.
I have to mention that I one of developers of this product and I'm very proud for our product and our customer service.

A:

*

*First Build: Accept and Content-Type

*Second Build: type

*Third Build: __metadata and LoginName


text:
Q: Mongoose / Ejs - I can not see the comment I made if I GET to the post again, only after I made it thats when it is visible So basically I can not see the comment I made, only after I created the comment and when I'm rendering the same page again, that's when I can see the comment and its author, but I cannot see it if I, for example, go to the posts or myposts page, and then I GET to the same post where I created the comment, that's when the comment is not visible anymore. Please help me I do not know why the comment is not visible anymore if I try to GET to the same post again, after having left that page.
If you have any ideas for me, how I should create and make my comment model, please help me :)
model.js
const mongoose = require("mongoose"),
    Schema = mongoose.Schema,
    bcrypt = require("bcryptjs");

const commentSchema = new Schema({
    context: String,
    author: String,
    postId: {
        type: Schema.Types.ObjectId
    }
})

const postSchema = new Schema({
    title: String,
    description: String,
    context: String,
    author: {
        type: Schema.Types.ObjectId,
    },
    comments: [commentSchema]
});

const userSchema = new Schema({
    name: {
        type: String,
        required: true
    },

    email: {
        type: String,
        required: true,
    },

    password: {
        type: String,
        required: true
    },

    posts: [postSchema]
});

userSchema.pre("save", async function save(next) {
    const user = this;
    if (!user.isModified("password")) return next();
    const hashedPassword = await bcrypt.hash(user.password, 10);
    user.password = hashedPassword;
    next();
});

const Post = mongoose.model("Post", postSchema);
const User = mongoose.model("User", userSchema);
const Comment = mongoose.model("Comment", commentSchema)

module.exports = {
    User,
    Post,
    Comment
}

admin controller
exports.postCreateComment = async (req, res) => {
    const {
        context
    } = req.body;
    try {
        const post = await Post.findById(req.params.postId);

        const comment = new Comment({
            context: context,
            author: req.user.name,
            postId: post._id
        });

        const savedComment = await comment.save();
        const postsComment = await post.comments.push(comment);

        res.render("admin/post", {
            path: "/posts",
            pageTitle: post.title,
            post: post,
        });
    } catch (error) {
        console.log(error);
    }

}

admin route
router.post("/posts/:postId", adminController.postCreateComment);

<%= post.title %>

<%= post.description%>

<%= post.context%>

        <% if(String(post.author) === String(user._id)) { %>
        <a href="/posts/edit-post/<%= post._id %>">Edit Post
        <a href="/posts/deleted-post/<%= post._id %>">Delete Post
        <% } %>

        <form action="/posts/<%=post._id%>" method="POST">
            Comment Here
            <textarea name="context" placeholder="Enter Comment..." cols="30" rows="10"></textarea>
            <input type="hidden" name="_csrf" value="<%= csrfToken %>">
            <button type="submit">Submit</button>
        </form>

    <% if (post.comments.length > 0) { %>
    <% for (let comment of post.comments) { %>

<%=comment.author%>

<%=comment.context%>

    <% } %>
    <% } %>

A: Rather than finding a post, creating a comment, and then mutating a post, it'd make a lot more sense to create a comment & then find the post. If the comment was successfully created, it'd show up, and if it wasn't, it'd make it more clear where the error was (I suspect that there's a problem with the comment.save() logic)
        const comment = new Comment({
            context: context,
            author: req.user.name,
            postId: req.params.postId
        });
        const savedComment = await comment.save();
        const post = await Post.findById(req.params.postId);
        // note that this no longer needs `post.comments.push` so it's no longer mutating the returned post
        res.render("admin/post", {
            path: "/posts",
            pageTitle: post.title,
            post: post,
        });


text:
Q: Can I safely use object initializers inside using statements? I'm wondering if the use of object initializers inside using statements somehow prevents the correct disposal of the resource declared inside them, e.g.
using (Disposable resource = new Disposable() { Property = property })
{
   // ...
}

I've read that object initializers are nothing but synctatic sugar, which the compiler translates to something similar to the following code:
MyClass tmp = new MyClass();
tmp.Property1 = 1;
tmp.Property2 = 2;
actualObjectYouWantToInitialize = tmp;

Even if I may appear as a confused ignorant, I'd like to ask for clarifications. Does the fact that the initialized object is (as far as I understand) a pointer to another object (which is also a pointer, as far as I know), interfere with the disposal of the resource done by a using statement?

A: The main (only?) danger is that if setting Property fails (i.e. throws an exception), then resource won't be Disposed.
using (Disposable resource = new Disposable() { Property = property })
{
   // ...
}

Normally exceptions within a using block are fine - since the using is syntactic sugar for a try .. finally.
The issue here is that when Property = property is executing you effectively aren't yet 'inside' the using block. This is essentially no different to what happens if the constructor threw an exception.
The thing that the finally block will be trying to Dispose is resource - but resource was never set - resource (as shown in your actualObjectYouWantToInitialize example) is set after the properties have all been set  .
https://dotnetfiddle.net/vHeu2F shows how this might occur in practice. Notice that Dispose was logged once, even though there are two using blocks.
using System;

namespace Bob
{
    public class Disposable : IDisposable
    {
        private int _property;

        public int Property { get => _property; set => throw new Exception(); }

        public void Dispose()
        {
            Console.WriteLine("Disposed");
        }
    }

    public class Program
    {
        public static void Main()
        {
            Console.WriteLine("1");
            using (var resource = new Disposable())
            {
                Console.WriteLine("2");
            }
            Console.WriteLine("3");

            using (var resource = new Disposable() { Property = 1 })
            {
                Console.WriteLine("4");

            }
            Console.WriteLine("5");
        }
    }
}

CA2000 may be helpful in detecting this issue.

A: @mjwills answer is correct. Here are the details:
public void M()
{
    using (var x = new Test{Property = ""})
    {

    }
}

will generate following IL code:
.method public hidebysig
    instance void M () cil managed
{
    // Method begins at RVA 0x206c
    // Code size 35 (0x23)
    .maxstack 3
    .locals init (
        [0] class Test
    )

    IL_0000: nop
    IL_0001: newobj instance void Test::.ctor()
    IL_0006: dup
    IL_0007: ldstr ""
    IL_000c: callvirt instance void Test::set_Property(string)
    IL_0011: nop
    IL_0012: stloc.0
    .try
    {
        IL_0013: nop
        IL_0014: nop
        IL_0015: leave.s IL_0022
    } // end .try
    finally
    {
        // sequence point: hidden
        IL_0017: ldloc.0
        IL_0018: brfalse.s IL_0021

        IL_001a: ldloc.0
        IL_001b: callvirt instance void [mscorlib]System.IDisposable::Dispose()
        IL_0020: nop

        // sequence point: hidden
        IL_0021: endfinally
    } // end handler

    IL_0022: ret
} // end of method Test::M

You can see that the property setter is called before entering the try which will result in the finally not being called in case of exception in the setter.


text:
Q: "Whiz" and "wiz" in Wizard of Oz In this famous song from The Wizard of Oz I do not completely understand the words whiz and wiz. I think it's probably a play on words.
What is the meaning of each use of wiz or whiz?

We're off to see the Wizard
The Wonderful Wizard of Oz
We hear he is a whiz of a wiz
If ever a wiz there was
If ever, oh ever, a wiz there was
The Wizard of Oz is one because
Because, because, because, because, because
Because of the wonderful things he does
We're off to see the wizard
The Wonderful Wizard of Oz!

A: Wiz is short for wizard. Whiz means something remarkable.

A: Wiz is a short form for Wizard.
In the context above Whiz means:

Whiz
"clever person," 1914, probably a special use of whiz "something
  remarkable" (1908), an extended sense of whizz; or perhaps a shortened
  form of wizard. Noun phrase whiz kid is from 1930s, a take-off on a
  radio show's quiz kid. - Online Etymology

Synonyms for Whiz

ace, genius, virtuoso, prodigy, expert, clever

The Author is using the homonymes whiz and wiz to create a word play. He is saying that the Wizard in the Wizard of Oz is the smartest, cleverest Wizard that exists because of all the wonderful things he does.
The original meaning of Whiz:

Whiz started out as onomatopoeia describing:

*

*To make a whirring or hissing sound, as of an object speeding through air.

*To move swiftly with or as if with such a sound; rush: whizzed past on a ten-speed

thank you Jay Elston for the last part
I hope I could help ; )

A: 'Whiz' and 'wiz' are variant spellings of the standard 'whizz'. 'Whiz' is more typical throughout North America and 'wiz' tends to be favoured when used alongside the related word 'wizard', which has a secondary definition identical to 'whizz'/'whiz'/'wiz': an extremely clever person. Thus 'a whizz of a whizz' is someone who is not only extremely clever but who is perceived to be extremely clever even amongst extremely clever people.


text:
Q: Question on using a dictionary to define answer I am trying to create a python script where depending on the keywords present in the question asked a specific answer is sent.
i.e If a question is asked that contains any word from dictionary A and specific answer is returned and then if the question contains any word from dictionary B a different answer is returned.
I am currently using an if else stack and stating the keywords manually but would like to place them in a dictionary.

A: It sounds like you are looking for something like this, where you loop through each dictionary checking if a keyword is in either one, and if it is, returning the corresponding answer
keywords_A = {'one': 1, 'two': 2, 'three': 3}
keywords_B = {'four': 4, 'five': 5, 'six': 6}

def get_answer(question):
    for keyword in keywords_A:
        if keyword in question:
            return keywords_A[keyword]
    for keyword in keywords_B:
         if keyword in question:
            return keywords_B[keyword]

get_answer('What is one written as?')
>>> 1
get_answer('What is five written as?')
>>> 5


text:
Q: How to get system path to installed packages in Google Colab? I am trying to make my code installable from Github.
In a folder in my github, I have some scripts which have relative imports. I tried running the scripts but I get errors.
According to this SO question Run script within python package

EDIT - If your script.py uses relative imports (and you don't want to
  change that), then there is no way to do it except getting that root
  path into the environment. You can do this in your script if you want,
  instead of setting it in the cmd shell or batch file. But it needs to
  get done somewhere. Here's how you can set the environment path in
  your script:

import sys
sys.path.append(r'..\..\path\to\my\package')
import package.other.anotherscript

So now I'm trying to figure out what is the path to my installed Github, but I can't seem to find it.  It seems to have installed correctly, but it's just not there.
This is my Github
https://github.com/Santosh-Gupta/MedicalQA
These are my scripts, which have relative imports
https://github.com/Santosh-Gupta/MedicalQA/tree/master/Scripts
This is what I use to install my Github.
!pip install https://github.com/Santosh-Gupta/MedicalQA/archive/master.zip

I tried finding the package using
print(sys.path)
os.listdir('lib')
os.listdir('lib/python3.6')
os.listdir('lib/python3.6/site-packages')

Any other info for getting scripts and code with relative imports to work in python packages would be greatly appreciated.

A: Use pip show <packagename> to get path where package is stored


text:
Q: How do i detect the control that sent the WM_KEYDOWN? WM_KEYDOWN message sends the message to the main window, I'd like to get control that originated the message. I've tried with GetFocus() handling WM_KEYDOWN like below but it didn't do anything, even when a press a key with focus on the buttona. How is that done? what am I missing?
Here's how I'm handling WM_KEYDOWN:
 case WM_KEYDOWN:
    HWND hFocus = GetFocus();
    if(hFocus == buttonA)
    {
        buttona_onKeyDown();
    }
    else if(hFocus == buttonB)
    {
        buttonb_onKeyDown();
    }
    else
    {
        //MessageBox(NULL, L"Not found!", L"", MB_OK);
    }
 break;

full code:
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "Comctl32.lib")
#pragma comment(lib, "Gdi32.lib")

#define WIN32_LEAN_AND_MEAN
#define UNICODE
#define _UNICODE

#include <windows.h>

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
void buttona_onKeyDown();
void buttonb_onKeyDown();

HWND buttonA, buttonB;

int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
                    PWSTR lpCmdLine, int nCmdShow) {

    MSG  msg;
    WNDCLASSW wc = {0};
    wc.lpszClassName = L"Buttons";
    wc.hInstance     = hInstance;
    wc.hbrBackground = GetSysColorBrush(COLOR_3DFACE);
    wc.lpfnWndProc   = WndProc;
    wc.hCursor       = LoadCursor(0, IDC_ARROW);

    RegisterClassW(&wc);
    HWND hWnd =
    CreateWindowW(wc.lpszClassName, L"Buttons",
                  WS_OVERLAPPEDWINDOW | WS_VISIBLE,
                  150, 150, 300, 200, 0, 0, hInstance, 0);

    while (GetMessage(&msg, NULL, 0, 0))
    {
        if (!IsDialogMessage(hWnd, &msg))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }

    return (int) msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg,
    WPARAM wParam, LPARAM lParam) {

    switch(msg)
    {

        case WM_CREATE:
            buttonA =
            CreateWindowW(L"Button", L"A",
                WS_VISIBLE | WS_CHILD | WS_TABSTOP,
                20, 50, 80, 25, hwnd, (HMENU) 10, NULL, NULL);

            buttonB =
            CreateWindowW(L"Button", L"B",
                WS_VISIBLE | WS_CHILD | WS_TABSTOP,
                120, 50, 80, 25, hwnd, (HMENU) 11, NULL, NULL);
            break;

        case WM_DESTROY:
            PostQuitMessage(0);
            break;

         case WM_KEYDOWN:
            HWND hFocus = GetFocus();
            if(hFocus == buttonA)
            {
                buttona_onKeyDown();
            }
            else if(hFocus == buttonB)
            {
                buttonb_onKeyDown();
            }
            else
            {
                //MessageBox(NULL, L"Not found!", L"", MB_OK);
            }
         break;
    }

    return DefWindowProcW(hwnd, msg, wParam, lParam);
}

void buttona_onKeyDown()
{
    MessageBox(NULL, L"A OnKeyDown", L"", MB_OK);
}

void buttonb_onKeyDown()
{
    MessageBox(NULL, L"B OnKeyDown", L"", MB_OK);
}