text:
Q: Function Recursion in shell I'd like to know why this recursive function in shell works properly:
exp ( )
    {
        local result
        #local op1="$1"
        #echo $2
        if [[ $2 -eq 0 ]]; then
            echo 1
            return
        fi
        tmp=$(( $2 - 1 ))
        local result1=$(exp $1 $tmp )
        result=$(( $result1 * $1 ))
        echo $result
    }
    exp 3 4

But when touching $2 in any way, for example like this:
exp ( )
    {
        local result
        echo $2
        if [[ $2 -eq 0 ]]; then
            echo 1
            return
        fi
        tmp=$(( $2 - 1 ))
        local result1=$(exp $1 $tmp )
        result=$(( $result1 * $1 ))
        echo $result
    }
    exp 3 4

It fails with:
4
foo.sh: line 15: 0
1 * 3 : syntax error in expression (error token is "1 * 3 ")
foo.sh: line 15: 2
3 * 3 : syntax error in expression (error token is "3 * 3 ")
9

A: Invoke exp 3 0, save it as result1 and ask yourself if $(( $result1 * $1 )) makes sense now.
The function expects itself to print one number. You make it print (echo) two numbers. At some point result1 contains two numbers and then result=$(( $result1 * $1 )) is syntactically wrong.

A: The problem isn't that you touch $2, it's that you echo stuff. Your function is, as you say, recursive. This means that it will process its own output. As soon as you have it printing out anything other than a single return number (which is what you expect), it will break.
Specifically, your function will do this:
    tmp=$(( $2 - 1 ))
    local result1=$(exp $1 $tmp )
    result=$(( $result1 * $1 ))
    echo $result

This works fine when the output of exp $1 $tmp, which is saved as result1 is just a single number. However, when you echo something else, the output of exp is no longer a single number so the simple math operations you do will break.


text:
Q: Getting specific event version via Event Message We are trying to show all the event details about an event message, we are tracking multiple messages, some are eventMessage.
When trying to access the event relationship on the eventMessage we always get the same event for all messages in the conversation.
Therefore, the original event message shows the latest event properties (start and end time, location, etc.)
I've tried to use the Microsoft Graph Explorer to see if there is any way to get a specific event item by using the changeKey of the item itself.
Sadly, with no success.
For example, when trying to access all messages within a conversation by filtering with the conversation id and expanding the event relationship
GET https://graph.microsoft.com/v1.0/me/messages/?$filter=conversationId eq '<ConversationId>='&$expand=Microsoft.Graph.EventMessage/Event

We always get the same event for all messages.
{
    "value": [
        {
            "@odata.type": "#microsoft.graph.eventMessage",
            "@odata.etag": "W/\"<CHANGEKEY1>\"",
            "id": "<MSGID1>",
            "createdDateTime": "2019-05-26T15:48:46Z",
            "lastModifiedDateTime": "2019-06-09T23:34:48Z",
            "changeKey": "<CHANGEKEY1>",
            "receivedDateTime": "2019-05-26T15:48:46Z",
            "sentDateTime": "2019-05-26T15:48:44Z",
            "event": {
                "@odata.etag": "W/\"<EVENTCHANGEKEY>\"",
                "id": "<EVENTID>",
                "createdDateTime": "2019-05-26T15:48:46.2276944Z",
                "lastModifiedDateTime": "2019-06-16T11:42:26.1599832Z",
                "changeKey": "<EVENTCHANGEKEY>",
                "categories": [],
                "originalStartTimeZone": "Israel Standard Time",
                "originalEndTimeZone": "Israel Standard Time",
                "iCalUId": "<ICALUID>",
                "reminderMinutesBeforeStart": 15,
                "isReminderOn": false,
                "hasAttachments": false,
                "importance": "normal",
                "sensitivity": "normal",
                "isAllDay": false,
                "isCancelled": false,
                "isOrganizer": false,
                "responseRequested": true,
                "seriesMasterId": null,
                "showAs": "tentative",
                "type": "singleInstance",
                "onlineMeetingUrl": null,
                "recurrence": null,
                "responseStatus": {
                    "response": "notResponded",
                    "time": "0001-01-01T00:00:00Z"
                },
                "start": {
                    "dateTime": "2019-06-11T09:00:00.0000000",
                    "timeZone": "UTC"
                },
                "end": {
                    "dateTime": "2019-06-11T09:30:00.0000000",
                    "timeZone": "UTC"
                },
                "location": {
                    "displayName": "טלפוני / במשרד",
                    "locationType": "default",
                    "uniqueId": "ff8323c6-c525-415a-be80-88de9c1bd53d",
                    "uniqueIdType": "locationStore"
                },
                "locations": [
                    {
                        "displayName": "טלפוני / במשרד",
                        "locationType": "default",
                        "uniqueId": "ff8323c6-c525-415a-be80-88de9c1bd53d",
                        "uniqueIdType": "locationStore"
                    }
                ]
            }
        },
        {
            "@odata.type": "#microsoft.graph.eventMessage",
            "@odata.etag": "W/\"<CHANGEKEY2>\"",
            "id": "<MSGID2>",
            "createdDateTime": "2019-06-09T23:34:46Z",
            "lastModifiedDateTime": "2019-06-17T10:00:07Z",
            "changeKey": "<CHANGEKEY2>",
            "receivedDateTime": "2019-06-09T23:34:47Z",
            "sentDateTime": "2019-06-09T23:34:45Z",
            "event": {
                "@odata.etag": "W/\"<EVENTCHANGEKEY>\"",
                "id": "<EVENTID>",
                "createdDateTime": "2019-05-26T15:48:46.2276944Z",
                "lastModifiedDateTime": "2019-06-16T11:42:26.1599832Z",
                "changeKey": "<EVENTCHANGEKEY>",
                "categories": [],
                "originalStartTimeZone": "Israel Standard Time",
                "originalEndTimeZone": "Israel Standard Time",
                "iCalUId": "<ICALUID>",
                "reminderMinutesBeforeStart": 15,
                "isReminderOn": false,
                "hasAttachments": false,
                "importance": "normal",
                "sensitivity": "normal",
                "isAllDay": false,
                "isCancelled": false,
                "isOrganizer": false,
                "responseRequested": true,
                "seriesMasterId": null,
                "showAs": "tentative",
                "type": "singleInstance",
                "onlineMeetingUrl": null,
                "recurrence": null,
                "responseStatus": {
                    "response": "notResponded",
                    "time": "0001-01-01T00:00:00Z"
                },
                "start": {
                    "dateTime": "2019-06-11T09:00:00.0000000",
                    "timeZone": "UTC"
                },
                "end": {
                    "dateTime": "2019-06-11T09:30:00.0000000",
                    "timeZone": "UTC"
                },
                "location": {
                    "displayName": "טלפוני / במשרד",
                    "locationType": "default",
                    "uniqueId": "ff8323c6-c525-415a-be80-88de9c1bd53d",
                    "uniqueIdType": "locationStore"
                },
                "locations": [
                    {
                        "displayName": "טלפוני / במשרד",
                        "locationType": "default",
                        "uniqueId": "ff8323c6-c525-415a-be80-88de9c1bd53d",
                        "uniqueIdType": "locationStore"
                    }
                ]
                }
            }
            "@odata.etag": "W/\"CQAAABQAAAC5VJWM6fuTTIIUqGiAHWMQAAEwug==\"",
            "id": "AAMkADliYjE5MWViLWNlMGQtNDliYy05YThkLWM4YWZiNzY2ODdlNwBGAAAAAAA5_Z03NIx3SqoeFwQnhSEiBwDt8lpmQG0nRYbMU6WI2FVeAAAAAAEPAADt8lpmQG0nRYbMU6WI2FVeAAFkUv4FAAA=",
            "createdDateTime": "2019-06-17T10:31:28Z",
            "lastModifiedDateTime": "2019-06-17T10:28:24Z",
            "changeKey": "CQAAABQAAAC5VJWM6fuTTIIUqGiAHWMQAAEwug==",
            "categories": [],
            "receivedDateTime": "2019-06-17T10:31:26Z",
            "sentDateTime": "2019-06-17T10:31:30Z",
            "hasAttachments": true,
            "internetMessageId": "<DB7PR03MB39784FB9DE2927C185428518CFEB0@DB7PR03MB3978.eurprd03.prod.outlook.com>",
            "subject": "FW: Recruitment briefing before 8200 conference  ",
            "bodyPreview": "",
            "importance": "normal",
            "parentFolderId": "AAMkADliYjE5MWViLWNlMGQtNDliYy05YThkLWM4YWZiNzY2ODdlNwAuAAAAAAA5_Z03NIx3SqoeFwQnhSEiAQDt8lpmQG0nRYbMU6WI2FVeAAAAAAEPAAA=",
            "conversationId": "<ConversationId>=",
            "isDeliveryReceiptRequested": false,
            "isReadReceiptRequested": false,
            "isRead": false,
            "isDraft": true,
            "webLink": "https://outlook.office365.com/owa/?ItemID=AAMkADliYjE5MWViLWNlMGQtNDliYy05YThkLWM4YWZiNzY2ODdlNwBGAAAAAAA5%2BZ03NIx3SqoeFwQnhSEiBwDt8lpmQG0nRYbMU6WI2FVeAAAAAAEPAADt8lpmQG0nRYbMU6WI2FVeAAFkUv4FAAA%3D&exvsurl=1&viewmodel=ReadMessageItem",
            "inferenceClassification": "focused",
            "toRecipients": [],
            "ccRecipients": [],
            "bccRecipients": [],
            "replyTo": [],
            "flag": {
                "flagStatus": "notFlagged"
            }
        }
    ]
}

We expected to get each eventMessage with its own "version" of the event itself.
In the provided case, the start and end time should have been changed.
When accessing the webUrl property, we get the expected result.
As shown in the web url:
Original Message

Updated Message

redpajama_set_name: RedPajamaStackExchange


text:
Q: Heroku: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory even after changing NODE OPTIONS I am deploying a Shopify App to Heroku and the build fails with:
Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory.
I already tried setting NODE options like this:
heroku config:set NODE_OPTIONS="--max_old_space_size=2560" -a [app_name]

This did not work either, even after taking memory as high as 8192. I am running a 2x dyno with 1GB memory. Here is an excerpt from my package.json:
  "scripts": {
    "shopify": "shopify",
    "build": "shopify app build",
    "dev": "shopify app dev",
    "info": "shopify app info",
    "generate": "shopify app generate",
    "start": "NODE_ENV=production node ./web/index.js",
    "deploy": "shopify app deploy"
  },

I suspected increasing the max_old_space or changing to a paid dyno would help, but no luck.


text:
Q: Stochastic Integrals: Approximating $f(t,\omega)$ by $ke^{-kt} \int_0^t e^{ks} f(s,\omega)ds$ Let $f_N(s,\omega)$ be some bounded jointly measurable function in the product space $L^1([0,T],\mathscr{L},\mu_L) \times (\Omega,\mathscr{F},P)$.
For such an $f_N$ we define a function $g_k$ for $k>0$ by
$$g_k(t,\omega) = ke^{-kt} \int_0^t e^{ks} f_N(s,\omega)ds.$$
In this case, for any $\epsilon>0$, how do we find an $g_k$ for which
$\int_0^T E | f_N(t,\cdot) - g_k(t,\cdot)|^2 dt < \epsilon$?
This is part of a proof from Numerical Solution of Stochastic Differential Equations. I would greatly appreciate any help.

Now a function $f \in \mathcal{L}_{T}^{2}$ is generally not mean-square continuous, but we can approximate it arbitrarily closely in the norm (2.5) by one that is. To begin, we approximate $f$ by a bounded function $f_{N} \in \mathcal{L}_{T}^{2}$ defined by
  $$
f_{N}(t, \omega)=\max \{-N, \min \{f(t, \omega), N\}\}
$$
  for some $N>0 .$ Obviously $\left|f_{N}(t, \omega)\right| \leq N,$ with $f_{N}(t, \omega)=f(t, \omega)$ for those $(t, \omega)$ for which $|f(t, \omega)| \leq N .$ Moreover
  $$
\int_{0}^{T} E\left(\left|f_{N}(t, \cdot)-f(t, \cdot)\right|^{2}\right) d t \leq 4 \int_{0}^{T} E\left(|f(t, \cdot)|^{2}\right) d t<\infty
$$
  so by the Dominated Convergence Theorem 2.2 .3 applied to the functions $E\left(\left|f_{N}(t, \cdot)-f(t, \cdot)\right|^{2}\right)$ in $L^{1}\left([0, T], \mathcal{L}, \mu_{L}\right)$ it follows that
  $$
\int_{0}^{T} E\left(\left|f_{N}(t, \cdot)-f(t, \cdot)\right|^{2}\right) d t \rightarrow 0 \quad \text { as } \quad N \rightarrow \infty
$$
  Then for such an $f_{N}$ we define a function $g_{k}$ for $k>0$ by
  $$
g_{k}(t, \omega)=k e^{-k t} \int_{0}^{t} e^{k s} f_{N}(s, \omega) d s
$$
  From the properties of $f_{N}$ and the fact that the above integrand does not involve values of $f_{N}$ for times exceeding $t,$ it follows that $g_{k}$ is jointly $\mathcal{L} \times \mathcal{A}$ measurable and that $g_{k}(t, \cdot)$ is $\mathcal{A}_{t}$ -measurable for each $t \in[0, T] .$ Also from the bound on $\left|f_{N}\right|$ we have
  $$
\left|g_{k}(t, \omega)\right| \leq N\left(1-e^{-k t}\right)
$$
  so $E\left(g_{k}(t, \cdot)^{2}\right)$ is finite and integrable over $0 \leq t \leq T ;$ hence $g_{k} \in \mathcal{L}_{T}^{2} .$ Finally, the sample paths of $g_{k}$ satisfy
  $$
\left|g_{k}(t, \omega)-g_{k}(s, \omega)\right| \leq 2 k N|t-s|
$$
  and are thus continuous. In fact this bound also implies that $E\left(g_{k}(t, \cdot)^{2}\right)$ is continuous, that is $g_{k}$ is mean-square continuous. Consequently we can approximate it by a step function $f^{(n)} \in \mathcal{S}_{T}^{2}$ as in the first part of the proof. For any given $\epsilon>0$ we can choose $f_{N}, g_{k}$ and $f^{(n)}$ successively so that
  $$
\begin{array}{c}
\left\|f-f_{N}\right\|_{2, T}<\frac{1}{3} \epsilon, \quad\left\|f_{N}-g_{k}\right\|_{2, T}<\frac{1}{3} \epsilon \\
\left\|g_{k}-f^{(n)}\right\|_{2, T}<\frac{1}{3} \epsilon
\end{array}
$$
  Then by the triangle inequality $(1.4 .37)$ we have
  $$
\left\|f-f^{(n)}\right\|_{2, T}<\epsilon
$$
  which is what we were required to prove. $\square$

(Transcribed from this screenshot)

A: You can write $g_k$ as the convolution $g_k = f_N * \psi_k$, where $\psi_k(t) = k e^{-kt}\mathbf{1}_{t>0}$ is delta-like. Since $f_N(\cdot,\omega)\in L^2(0,T)$ for almost all $\omega$, then
$$
||g_k(\cdot,\omega) - f_N(\cdot,\omega)||_{L^2[0,T]} \to 0,k\to\infty,
$$
for such $\omega$. Thanks to boundedness, $||g_k - f_N||^2_{2,T}\to 0$, $k\to\infty$ (I guess that $||f||^2_{2,T}$ is just the expectation of $||f||^2_{L^2[0,T]}$).


text:
Q: Git commit and push error Changes not staged for commit: I have problem with commit and push the client, I get this error:
On branch VersionOne
Your branch is up to date with 'origin/VersionOne'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
  (commit or discard the untracked or modified content in submodules)
        modified:   client (modified content)

no changes added to commit (use "git add" and/or "git commit -a")

Before I was pushing my files from the client its self, but I create backend file and could not commit it from the clinet, so I create new branch in top level directory and add both of them, the client not pushed.

A: I solve this problem, by moving to the client folder which is the inner repository or submodel and delete all the git files by  going to :

*

*cmd in widnows

*cd to my project

*run del /F /S /Q /A .git

*Init git again in the root folder and puch everything

NOTE: MAKE SURE TO BACKUP EVERYTHING FOR ANY CASE


text:
Q: rails: start the server with multiple port in single line Is there any possible to run rails server with multiple port in a single command?.
I know the following command is help to start the server with the port number 3001
rails s -p 3001

But, I'm expecting the command like following... Need to start the server with multiple port in single line
rails s -p 3001..3006
or
rails s -p 3001 3002 3003

Is it possible?

A: You can run 2 or more instances of the rails server one for each port.  Your other option could be to have your firewall or router forward traffic from each of these ports to a single port on the machine.


text:
Q: NoClassDefFoundError for singleton kotlin android? I create an arr of my library module and use it in another application.
On one of the singleton class from my aar I get NoClassDefFoundError for its usage
This is my singleton class
object SharedPrefTask {

fun doSomeWork() {
    /////
}
}

This is the class where I use the singleton
class ConfigController(val mContext: Context) {
private var prefTask: SharedPrefTask = SharedPrefTask

fun fetchConfig() {
    val configs = prefTask.doSomeWork()
}
}

Is there something which is wrong here?
I get the exception
Fatal Exception: java.lang.NoClassDefFoundError: <clinit> failed for class m0.g; see exception in other thread
   at b.a.<init>(ConfigController.kt:2)

A: The issue was due obsfucation from the obsfucation of proguard
Adding the rule helped resolve this
-keeppackagenames com.exaple.**


text:
Q: scala count strings in a list contained in a read file I am new to SO but have spent days going through related to questions. The closest related question I found is How to compare each word of a line in a file with a list element in scala? but that goes back to 2014 so thought there may be different solutions now.
Also in the above quoted post the best answer uses a mutable data struct which I am trying to avoid. The last answer by Dima looked more functional however did not work :(
I am trying to create a similar program in SCALA except the output should also contain an overall count for the keyword and all keywords should be outputed, even if no matches were found, thus the count would be zero.
The keywords to check against are hard coded into a list however I also want to add the option of a 2nd user supplied argument that contains the keywords. So far I have come to the following but got suck:
object FileAnalyser extends App {

val hardcodedkeywords = List("foo", "bar", "hello")

if (args.length > 1) {
  val keywords = args(1).toList
  try {
    val rdd = Source.fromFile(args(0)).getLines.toList.zipWithIndex.flatMap {
      case(line, index) => line.split("\\W+").map { (_, index+1) }
    } //.filter(keywords.contains(_)).groupBy { _._1 }.mapValues(_._2)
  } catch {
    case ioe: IOException => println(ioe)
    case fnf: FileNotFoundException => println(fnf)
    case _: Throwable => println("Uknown error occured")
  }
} else
  try {
    val rdd = Source.fromFile(args(0)).getLines.toList.zipWithIndex.flatMap {
      case(line, index) => line.split("\\W+").map { (_, index+1) }
    } //filter(hardcodedkeywords.contains(_))
      //.groupBy { _._1 }.mapValues(_._2)
  } catch {
    case ioe: IOException => println(ioe)
    case fnf: FileNotFoundException => println(fnf)
    case _: Throwable => println("Uknown error occured")
  }
}

So far I have managed to use args(0) containing the file to read, to be read, and mapped to a list containing a string per line as well index+1 (as line numbers start from 1 but index starts from 0)
The program must be as functional as possible so less mutables and state changes and more higher order functions and list recursions.
Thanks
Example output would be:
//alphabetical      //No duplicates
//order             //Increasing in no.
keyword              lines                count
bar                  [1,2..]                6
foo                  [3,5]                  2
hello                []                     0

A: Here's a basic outline to how it might be done.
val keywords = List(/*key words here*/)

val resMap = io.Source
  .fromFile(/*file to read*/)
  .getLines()
  .zipWithIndex
  .foldLeft(Map.empty[String,Seq[Int]].withDefaultValue(Seq.empty[Int])){
    case (m, (line, idx)) =>
      val subMap = line.split("\\W+").toSeq  //separate the words
        .filter(keywords.contains)           //keep only key words
        .groupBy(identity)                   //make a Map w/ keyword as key
        .mapValues(_.map(_ => idx+1))        //and List of line numbers as value
        .withDefaultValue(Seq.empty[Int])
      keywords.map(kw => (kw, m(kw) ++ subMap(kw))).toMap
  }

//formatted results (needs work)
println("keyword\t\tlines\t\tcount")
keywords.sorted.foreach{kw =>
  println(kw + "\t\t" +
          resMap(kw).distinct.mkString("[",",","]") + "\t\t" +
          resMap(kw).length
         )
}

some explanation

*

*io.Source is the library (actually an object) that offers some basic input/output methods, including fromFile(), which opens a file for reading.

*getLines() reads from the file one line at a time.

*zipWithIndex attaches an index value to each line read.

*foldLeft() reads all the lines of the file, one at a time, and (in this case) builds a Map of all the key words and their line locations.

*resMap and subMap are just the names I chose to give to the variables I'm building. resMap (result Map) is what's created after the whole file has been processed. subMap is an intermediate Map built from just one line of text from the file.

If you want the option of passing in a collection of key words, I'd do it like this:
val keywords = if (args.length > 1) args.tail.toList else hardcodedkeywords


text:
Q: Changing color of DIV by scrolling another DIV's with specific classes (margin/padding problem) I'm currently working on a project where the logo color should change depending on the background color.
My only problem is the following: The Logo is switching to the class "inverted" if it scrolls over the black bg02 DIV. Up to here everything is working fine. But if I set a margin and/or padding to the bg02 DIV, than the Logo switches not right anymore (too early in and out). If there is no margin/padding, than it works like a charm.
I've tried it with offsetHeight instead of normal height, but it doesn't work. Can u help me?

$(document).on("scroll", function() {
    // Use logo position:
    var scrollPos = $(document).scrollTop() + $("#logo").position().top + ($("#logo").height() / 2)
    // Or use position from window top:
    // var scrollPos = $(document).scrollTop();
    $('.bg02').each(function() {
        var refElement = $(this);
        if (refElement.position().top <= scrollPos && refElement.position().top + refElement.innerHeight() > scrollPos) {
            $('#logo').addClass("inverted");
            // found one, so exit .each
            return false;
        } else {
            $('#logo').removeClass("inverted");
        }
    });
});
#logo {
    position: fixed;
    top: 20px;
    left: 5%;
    z-index: 100;
    font-size: 26px;
    font-weight: 700;
    color: #000;
}

#logo.inverted {
    color: #fff;
}

.bg01, .bg02 {
    position: relative;
    width: 100%;
    height: 600px;
    margin: 60px auto;
    padding: 40px 0 40px 0;
}

.bg01 {
    background: #fff;
}

.bg02 {
    background: #000;
}

Logo

A: It looks like you didn't take into account the margin in your calculations. Padding won't give you any problems. This will probably work,even though I don't know how effective it is to do these checks for every ".bg02" element.

$(document).on("scroll", function() {
    // Use logo position:
    var scrollPos = $(document).scrollTop() + $("#logo").position().top + ($("#logo").height() / 2)
    // Or use position from window top:
    // var scrollPos = $(document).scrollTop();
    $('.bg02').each(function() {
        var refElement = $(this);
        var margin = parseInt(refElement.css("margin-top"));
        if (refElement.position().top <= scrollPos - margin  && refElement.position().top + refElement.innerHeight() + margin > scrollPos) {
            $('#logo').addClass("inverted");
            // found one, so exit .each
            return false;
        } else {
            $('#logo').removeClass("inverted");
        }
    });
});
#logo {
    position: fixed;
    top: 20px;
    left: 5%;
    z-index: 100;
    font-size: 26px;
    font-weight: 700;
    color: #000;
}

#logo.inverted {
    color: #fff;
}

.bg01, .bg02 {
    position: relative;
    width: 100%;
    height: 600px;
    margin: 60px auto;
    padding: 40px 0 40px 0;
}

.bg01 {
    background: #fff;
}

.bg02 {
    background: #000;
}

Logo


text:
Q: How can I stop an iPod from upgrading the iOS once it has already started the download? I accidentally clicked to upgrade from iOS 7 to iOS 8.1.1. The problem is, I am a developer and want my device to remain at iOS 7 so I'm testing with the same OS and browser version that my corporate users are using in the field. However, there is no "Cancel" button (seriously, Apple? ...seriously? )
I tried shutting the device off and turning it back on, but it resumes the download after it's restarted. Same with turning WiFi on and off. I need to stop it permanently.
I read this macworld.com article that discusses how to revert back once you've upgraded, but at the top it specifies that it no longer works: "Update: The technique outlined here for reverting to iOS 7 no longer works as Apple has stopped signing versions of iOS prior to iOS 8."
I did read one "hacky" way to prevent the download from completing by leaving the video recorder on so space fills up and it can't finish. Is there a better way to do it?
(Hopefully this question is in the right place w/right tags - I haven't posted in this SE before)

A: Turn off wifi.  Reset All settings.  Phone reboots and download is canceled.


text:
Q: grouping foreign objects (javascript merge) I'm writing a small userscript to recieve an object from a xhr request and send parts of it to another website. The recieved json looks like this
{"result": [
{"id":"1234","title":"Gartenzwerg","description":"Strom unter Kunst","lat":153.558356,"lng":50.205637,"city":"Citü","state":"XY","day":"1970-01-01","order":0,"imageUrl":"https://cool.page","nextUpgrade":false,"upgraded":false,"status":"WITHDRAWN"},
{"id":"56789","title":"Weizenähre","description":"Strom unter Kunst","lat":153.590972,"lng":50.235216,"city":"Citü","state":"XY","day":"1971-01-01","order":1,"imageUrl":"https://cooler.page","nextUpgrade":true,"upgraded":true,"status":"NOMINATED"},
{...}],
"message":null,
"code":"OK",
"errorsWithIcon":null,
"fieldErrors":null,
"errorDetails":null,
"version":"4.0.10",
"captcha":false}

I use Add a "hook" to all AJAX requests on a page to get the informations and then send each result-part by it's own to my page with a fetch-function
    var data = JSON.parse(this.responseText).result;
    for (let i=0; i<Object.keys(data).length; i++) {
        sendDataToPage(data[Object.keys(data)[i]]);
        await sleep(500);
    }

Now it's very ineffective to send each by it's own, so i'd like to groupe f.e. 10 elements before I send them.  With Object.assign I only get the last element. Do I have to use another function to merge or how do I use it the right way?


text:
Q: What does it mean to define events in probability space? Assume for any set $S\subseteq [n]$, there is a parameter $q_S\ge 0$. And these parameters satisfy $\sum_{S\subseteq [n]}q_S=1$.
A claim states that we can define a collection of events $A_1,\dots,A_n$ such that
$$\mathbb{P}\left(\left(\bigcap_{i\in S}A_i\right)\cap \left(\bigcap_{j\in [n]\setminus S} A_j^c\right)\right)=q_S$$
for every $S\subseteq [n]$.

My question is,
(a) what is the definition of "define a collection of events"? How do we know it is well-defined?
(b) Why there exists such a collection of events of this form satisfying $\mathbb{P}\left(\left(\bigcap_{i\in S}A_i\right)\cap \left(\bigcap_{j\in [n]\setminus S} A_j^c\right)\right)=q_S$? Is there any quantitative relation $q_S$ should satisfy?

A: A simple (and minimal) way to construct such a probability space is to choose $\Omega=\{0,1\}^n$, $\mathcal F=2^\Omega$, and $P(\{\omega_S\})=q_S$ for every $S\subseteq[n]$, where each $\omega_S$ is defined as $\omega_S=(\omega^S_k)_{1\leqslant k\leqslant n}$ with $\omega^S_k=\mathbf 1_{k\in S}$.
Thus, $\Omega=\{\omega_S\mid S\subseteq[n]\}$ and the only relevant condition on some family of real numbers $(q_S)$ for this space $(\Omega,\mathcal F,P)$ to define a bona fide probability space, is that every $q_S$ should be nonnegative and that $\sum\limits_{S\subseteq[n]}q_S=1$.
Then, the events $A_k$ are simply $A_k=\{\omega_S\mid S\ni k\}$ and, for every $S\subseteq[n]$, $$\left(\bigcap_{k\in S}A_k\right)\cap \left(\bigcap_{k\in [n]\setminus S} A_k^c\right)=\{\omega_S\}$$


text:
Q: How to give hyperlink in bibtex files? The bib entry is:
@article{ball1992,
title   = "Why does high inflation raise inflation uncertainty?",
journal = "Journal of Monetary Economics",
volume  = "29",
number  = "3",
pages   = "371-388",
year    = "1992",
issn    = "0304-3932",
doi     = "doi.org/10.1016/0304-3932(92)90032-W",
url     = "sciencedirect.com/science/article/pii/030439329290032W",
author  = "Laurence Ball",
}

This is how I currently hard-code the hyperlink to the title field:
title = {\href{sciencedirect.com/science/article/pii/030439329290032W}{Why
          does high inflation raise inflation uncertainty?}},

I was thinking if there is any easy way to automate this? For example, all the bibtex entries contain url information. Can we use this someway so that we don't have to do it manually?


text:
Q: Object based image editor for Windows I'm not a designer but I sometimes have to create/edit images for our applications.
In the past I've used "Microsoft Image Composer" - I like its user interface because it's object based and easy to use. Unfortunately it was discontinued and the old version I am using has some problems with png files.
I've tried to find a good replacement but everyone seems to be using layers instead of objects.
Do you know any image editors that are object based?
EDIT:
Still haven't found what I am looking for ... the best alternative so far is Paint.NET even though it uses layers.

A: Have you tried Illustrator? As a vector graphics app it might not be exactly "object based", but you work with independent shapes instead of pixel layers.
Inkscape http://www.inkscape.org/ is a free alternative. I haven't tried it, but it seems like a winner.

A: Sticking to what's likely to already be on your machine, both PowerPoint and Visio are object oriented (but crude) image editors.

A: I guess no such software exists. That's a pity because I found that UI much better than the layer model.


text:
Q: DateTime Now in a specified timezone How can something like this be implemented in C#:
string timeZone = "Fiji Time";
TimeZoneInfo timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(timeZone);
DateTime dateTimeNowInFiji = new DateTime(timeZoneInfo).Now;

A: var t = TimeZoneInfo.ConvertTimeFromUtc(DateTime.Now.ToUniversalTime(), TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));

NB. To make this work I needed to change "Fiji Time" to "Fiji Standard Time" for the TimeZone id.

A: C#:
TimeZoneInfo timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Fiji Standard Time");
DateTime dateTimeNowInTargetTimeZone = TimeZoneInfo.ConvertTime(DateTime.Now, timeZoneInfo);


text:
Q: document click bug? (firefox - windows) Here is the problem. Firefox (Windows) does not trigger document click event, when select is open.
It just closes the select, and only next click will be counted as a click.
To reproduce:

*

*Click select (the drop-down menu will appear)

*Click outside the drop-down menu, on document outside (select will be closed)

However, the 2nd click won't trigger the document click event.
As you can see in this Youtube video, there are 3 clicks but 2 events.
Demo on jsFiddle
HTML
<select>
    <option value="1">Value1</option>
    <option value="2">Value2</option>
    <option value="3">Value3</option>
</select>

JS
var n = 0;
$(document).ready(function(){
    $('select').click(function(e){
      e.stopPropagation();
      n++;
      $('#debug').text('select clicked ' + n);
    });

    $(document).click(function(){
        n++;
        $('#debug').text('document clicked '+ n);
    });
})


text:
Q: Sodity - Smart Contract I'm writing a Lottery contract that's supposed to accept players, pick a winner and send the NFTs collected to the winner's address, then start over again.
After running npm run test, the first 5 tests are passing but the "sends NFT to the winner & resets the players array" test fails, with an error message.
Lottery Contract sends NFTs to the winner & resets the players array: Error: Transaction has been reverted by the EVM.
Anyone want to assist solving this Error.

A: I know that HashEx has a security subscription, it seems to me that in your case it is just right, besides, serious techies are behind the hashex, just look how the time comes.


text:
Q: Do I need multiple Power Plants? I'm just getting into this game and I've built a basic coal to power plant train delivery system. I'm curious, since power plants can accept an unlimited amount of coal, is there any reason to deliver coal to multiple plants instead of delivering all the coal to one?

A: While there are mods available that add mechanics regulating the demand side (that means, adding limits to the amount of coal for example, that a power plant can process in a certain timespan), in vanilla OpenTTD any processing plant can process unlimited amounts of goods.
However, delivering the goods to the most distant plant will yield the maximum amount of profits, so you might need to supply more than a single one. There is an in-game chart that shows the profit per good by (days in transit vs. distance travelled), and you can see that especially coal profits a lot from large distances.
Normally, you would start building around a single plant, and connect multiple mines to that, in order to reuse existing infrastructure. Then later re-route trains to go to different power plants that have a larger distance.
As Private Pansy correctly mentions, in the late game you need to optimize your track layout in order to get it more efficient. That means removing any "wait until fully loaded" orders and usually packing your tracks with the maximum amount of trains affordable. This is less important for coal, but highly important for other goods (say, fruits in the desert setting).

A: There's one additional reason to use two power plants, and that is making more money with each train, to increase their effective ROI ratio. With the default trainset, refits are typically expensive or not possible, so you would have trains hauling empty loads back in a simple setup. With two plants, you can haul coal 'both ways'.
Suppose you identify two pairs of power plant and coal mine, close together, with both pairs far apart. You could build two small train lines, but since you're paid 'by the square', it can be far more lucrative to have your train line go:
Coal mine #1 ----> Plant #1 -> Coal mine #2 ----> Plant #2 ->

where longer arrows represent greater distances. You can get (almost) twice the income over a simple one-way empty, one-way full connection. Almost, since you will probably need a small distance between the Plant and the next Mine, and since full trains are heavier and accellerate slower.
By the way, this is a great way to jumpstart your company in openTTD, and typically regarded as the optimal opening move on most maps/settings. Here's a link to a more in-depth tutorial.


text:
Q: Set Pointer to Hand when hovering over UI element in Silverlight I have an Image, which is attached to some JavaScript on MouseEnter.
This all works fine. When user "Mouses Over", JS is called and storyboard runs as expected.
I also want to change the mouse cursor to a "Hand Pointer" when the user hovers over, probably I guess, this occurs in the same JS function.
Also, how do I change it back?
Many thanks

A: Answering my own question again:
Turns out there is a Hand attribute I missed.
<Image Canvas.Left="719.732" x:Name="img17_18" Width="180" Height="208.09" Source="Padmamand1.jpg" Stretch="Fill" Canvas.Top="36.91" Opacity="0.595" Cursor="Hand"/>

Sweet.


text:
Q: Pipe output of one iteration of a python for loop to another script Each instance of the for loop, spits out the contents of one binary file which should be captured by another script to do further processing. For example:
script1.py
filename = glob.glob('*.txt')
for i in range(len(filename)):
    with open(filename[i], 'rb') as g:
        sys.stdout.write(g.read())

script2.py
from subprocess import call
script = "cat > test.fil"
call(script,shell=True)

Command:
python script1.py | python script2.py

If I execute this command, it waits for all iterations to be completed before piping the output to script2.py. I would like this to be done batchwise. For example, once data from one binary file is pushed to stdout, launch script2.py.
script2.py cannot be called from script1.py. Both the scripts need to be run in different docker containers. It would be better to avoid a docker installation inside a docker container.

A: if sys.stdout is connect to a pipe, by default it buffers. You must call sys.stdout.flush() to flush the output:
sys.stdout.write(g.read())
sys.stdout.flush()

Your second script could also read stdin directly, instead of evoking the shell, to evoke cat, to read it. The way you wrote, you're executing 3 processes (python, your shell, cat).
import shutil
import sys
with open('test.fil', 'w') as f:
    shutil.copyfileobj(sys.stdin, f)

In a unrelated note, you don't need to use the for loop in a numeric range, when you are going to use the number only to index a list. The for loop can iterate directly in the list elements:
filenames = glob.glob('*.txt')
for filename in filenames:
    with open(filename, 'rb') as g:
        ...


text:
Q: PHP form in table not doing action It's got to be something easy I'm missing, maybe a " or ' is in the wrong place.  I have below code, and everything comes out great, the table is built and the "Delete" button is created, however when I click on the button it doesn't do anything, the button highlights but it just stays on the same page and doesn't go to my delete page, anyone see a problem with what I have below?
echo "
";
echo "
";
echo "".'Show'."	";
echo "".'TVDBID'."	";
echo "".'AirsDayOfWeek'."	";
echo "".'AirsTime'."	";
echo "".'Status'."	";
echo "".'Edit'."	";
echo "
";

while ($row = mysql_fetch_array($myShows)) {
    echo "
";
    echo "".$row['uShow']."	";
    echo "".$row['TVDBID']."	";
    echo "".$row['AirsDayOfWeek']."	";
    echo "".strftime("%l:%M %p", strtotime($row['AirsTime']))."	";
    echo "".$row['sStatus']."	";
    echo "<formb name=".$row['TVDBID']." action='DeleteShow.php?id=".$row['TVDBID']."'>"."<input type='submit' value='Delete'/></formb>	";
    echo "
";
}

echo "
";
echo "
";

EDIT
Adding the different forms from my CSS file, maybe I've missunderstood their use.
form {
  width: 100%;
  background-color: rgba(255,255,255,.2);
  text-align: center;
  padding: 1.25em;
  border-radius: 5px;
}

formb {
  width: 100%;
  background-color: rgba(255,255,255,.2);
  text-align: center;
  padding: .25em;
  border-radius: 5px;
}

A: replacing
echo "<formb name=".$row['TVDBID']." action='DeleteShow.php?id=".$row['TVDBID']."'>"."<input type='submit' value='Delete'/></formb>	";

with
echo "<form name=".$row['TVDBID']." action='DeleteShow.php?id=".$row['TVDBID']." class='formb'>"."<input type='submit' value='Delete'/></form>	";

Should work...
Update :
.formb {
  width: 100%;
  background-color: rgba(255,255,255,.2);
  text-align: center;
  padding: .25em;
  border-radius: 5px;
}

point is, call your CSS as class or ID over you HTML FORM element..


text:
Q: Export signed application package I'm using eclipse and developing android application. I have an project which is existed on google play store. I change my code and i want to update my app on google play. I click on Android Tools --> Export signed application package. Then i entered my password, everything is good with my code. Finally, i clicked on finish and the step is over. What should i do for next step for updating my app on play store? (I'm saying again, It was an existed project on google play, have keystore file inside of it.) Thanks in advance.

A: In order to update your app on Google Play you have to sign your .apk with your release certificate. The process is described here: http://developer.android.com/tools/publishing/app-signing.html#releasemode . You should not do what you've described above; "Android Tools --> Export signed application package" because doing so you are signing your apk with the debug certificate. You need to export your apk as unsigned from the Eclipse and then sign it with your release certificate.
edit:
If you are using Linux then it's something like:
jarsigner -verbose -sigalg MD5withRSA -digestalg SHA1 -keystore ~/android-sdks/my-release-key.keystore apk_unsigned.apk release_key

and then:
zipalign -v 4 apk_signed.apk apk_final.apk

A: All i must do is, right click on project--> Android Tools--> Export Signed App Package and then, on Developer Page Android sign up, finally choose your existing app, click on APK and add new APK to Production. After 1 hour, my new apk added on Google Play, and i updated this app.


text:
Q: How to install Edge/Chrome extension offline? Not in DevMode The question is not about Developer Mode "load unpacked". If the extension is loaded as unpacked then it shows additional popup on the normal browsers. Canary and Dev do not show this popup (used the extension for a while) but I have to use the build in Edge and regular Chrome.
I want to install extension from local source or from my webpage(over HTTPS).
I have the extension and can modify it (manifest, content script, etc.).
I have complete control over the local machine. I can add registries, local policies and templates (not AD joined but MS account), change folders, hosts file, etc.
I have already submited the extension to Google Web Store for review. It might  be delayed for a week or more, might fail review or both.
I asked related question How can I skip manual tests for a private Chrome extension?
So is there a working guide for installing extension in offline/corporate mode?
The extension might be visible on the extension page but it should not show warnings and/or additional icons.
Somehow I do not manage to understandand and successfully follow Alternate extension distribution methods or Deploying Connect Extensions in Closed Environments guides.
Any help would be apriciated.
p.s. Worst case scenario is to pack a lot of files in extension package and update it in large chunks. Current extension connects to web server and uses pictures and sounds from the server. On the fly speach generation is almost ready. Can not use the common browser/OS voices.

A: From this doc: Windows and Mac installs must come from Chrome Web Store. It seems that we must upload the extensions to stores if we want to use them on Windows and Mac. So I think the first step is to upload your extension to Chrome Web Store or Microsoft Store. Then you can download the .crx file from the store to install it locally.


text:
Q: Add line to FFMPEG waveform without a background I am trying to write an ffmpeg command to generate a waveform from audio. I've managed to generate the waveform but I fail when trying to add a line such that the silent areas are not blank.
Currently the command is:
 -filter_complex "[0:a]aformat=channel_layouts=mono,compand=attacks=0:points=-80/-900|-45/-15|-27/-9|0/-7|20/-7:gain=15,showwavespic=s=180x26:colors=#7c84cc[fg];color=s=180x26:color=#303030[bg];[bg][fg]overlay=format=auto,drawbox=x=(iw-w)/2:y=(ih-h)/2:w=iw:h=1:color=#7c84cc" -frames:v 1

I have added some tweaks of my own to boost the visual appeal but what I would like is to use the drawbox without the color filter. If I try to do that the line disappears during the silent part.
I have also attempted to use a transparent image as the background but that failed as well.
I have relied heavily on this question when approaching this problem
Generating a waveform using ffmpeg

A: One option would be to use the gradients filter, to add a changing colour gradient.
e.g.
ffmpeg -i input.mp3 -filter_complex "gradients=s=vga:c0=303030:c1=7c84cc:x0=0:x1=0:y0=0:y1=640 [bg];[0:a]showwaves=mode=p2p:s=vga:split_channels=1:scale=lin:draw=scale:colors=Yellow|White[v];[bg][v]overlay=shortest=1:format=rgb:alpha=premultiplied [vid]" -map "[vid]" -map 0:a  -vsync vfr -preset ultrafast -f matroska - | ffplay -autoexit -

There is a speed parameter as well to adjust the gradient rotation.


text:
Q: How to split attributes using FME I am trying to split an attribute into its component pieces with FME.
Ex: 1707 WILLINGTON ST, PHILADELPHIA PA 19121
into: 1707 WILLINGTON ST, PHILADELPHIA, PA, and 19121
I am using the AttributeSplitter using a comma Delimiter and I get this:
1707 WILLINGTON ST and PHILADELPHIA PA 19121
How do I get the state - city - ZIP in three separate fields?

A: In FME 2015.1 (used here)
Use the SubStringExtractor

If you need to work out the number of characters for the substringExtractor then use the StringSearcher it will have matched_characters you can use this as parameter for extracting multiple addresses.

A: Assuming a comma will sufficiently split your street address into a field and the City, State, ZIP into another field, you could just use another attribute splitter with a space.
Alternatively, you could use a PythonCaller Transformer to do the work for you.  Here, City/State/Zip are stored in an attribute called "Location".
The python script I used here is:
import fme
import fmeobjects
# Template Function interface:
def processFeature(feature):
    AttList = feature.getAttribute('Location').split(' ')
    City = AttList[0]
    State = AttList[1]
    Zip = AttList[2]

    feature.setAttribute("City", City)
    feature.setAttribute("State", State)
    feature.setAttribute("Zip", Zip)

    pass

The parameters of the transformer are:

Note, this is essentially the same as an attribute splitter.  But, there are a lot of ways to skin a cat.


text:
Q: Prove that every ideal in $\Bbb{Z}$ is a principal ideal. I have a question about the following proof for the theorem:

Prove that every ideal in $\Bbb{Z}$ is a principal ideal.

In Case 2, I do not understand how the principle of well-ordering is used. How it is known that $I$ is a subset of $\Bbb{N}$?

A: Note that the set $\lbrace z \in I\;|\; z \in \mathbb{N} \rbrace \neq \emptyset$. For this, take $0, a \in I$ so
$$0 - a\;\mathrm{and}\;0+a \in I$$
Thus, $a, -a \in I$. Therefore, theres exists a subset of natural numbers contained in $I$.


text:
Q: unable to get correct error with Node-PG pool.query I'm a total beginner attempting to make social media site with the PERN stack and I'm having trouble with my delete request, while debugging with Postman.
Basically, I've logged in as user X, created a post, logged out, THEN logged in as user Y and tried to delete said post. What happens is I get the response Post deleted with ID: ${post_id}
however, when I go to check the database the post still exists.
Even though this is what I functionally want it to do, I would love to have the correct error thrown. What am I missing?
  exports.deletePost = async (req, res) => {
 try {
  const userId = req.users
  const post_id = parseInt(req.params.id)
  await pool.query('DELETE FROM posts WHERE post_id = $1 AND user_id = $2', [post_id, userId])
  res.status(200).json(`Post deleted with ID: ${post_id}`)
 } catch (error) {
  console.log("Failed to delete post:" + error)
  res.sendStatus(500)
 }}

I'm receiving the logged in userId from an authenticator middleware:
module.exports = async (req, res, next) => {
 try {
  const jwtToken = req.header('token')
  if (!jwtToken) {
   return res.status(403).json('You are not authorized')
  }
  const payload = jwt.verify(jwtToken, process.env.jwtSecret)
  req.users = payload.users
  next();
 } catch (error) {
  console.error(error.message)
  return res.status(403).json('You are not authorized')
 }
}

It seems to me something is getting screwy with the logical AND operator in my PG request... any insight is greatly appreciated!

A: gonna go ahead and answer my own question here:
exports.deletePost = async (req, res) => {
 try {
  const userId = req.users
  console.log('logged in user', userId);
  const post_id = parseInt(req.params.id)
  const resp = await pool.query('DELETE FROM posts WHERE post_id = $1 AND user_id = $2', [post_id, userId])
  if (resp.rowCount === 0) {
   throw new Error('Failed to delete post')
  }
  res.status(200).json(`Post deleted with ID: ${post_id}`)
 } catch (error) {
  console.error(error.message)
  res.status(500).send(error.message)
 }

I put in an if statement to check the rowCount of resp and throw an error if appropriate...

A: I am having this same issue currently, if this was in mysql and php
i would have done
mysqli_query($db, "DELETE FROM post where id = $id and post_id = $post_id LIMIT 1") or die(mysqli_error($database_connection))
but i can't find a similar pattern for pg-node


text:
Q: CSV deleting first rows using java I have to set up a java  truck application whose converting a CSV file from GPS to a shapefile and i have to delete the first rows whose speed are less than 5, but once speed is more than 5 the function should stop and the points will be added normally.
Here is part of my code when the points are parsed, added and converted to a shapefile but I'm still wondering how I can delete just the first rows until speed is higher than 5 ...
    for (line = reader.readLine(); line != null; line = reader.readLine()) {
        if (line.trim().length() > 0) { // skip blank lines
            String tokens[] = line.split("\\,");
            String name1 = tokens[0].trim();
            String name2 = tokens[1].trim();
            double latitude = Double.parseDouble(tokens[2]);
            double longitude = Double.parseDouble(tokens[3]);
            String name = tokens[4].trim();
            String name4 = tokens[5].trim();

            /* Longitude (= x coord) first ! */
            Point point = geometryFactory.createPoint(new Coordinate(longitude, latitude));

            featureBuilder.add(point);
            featureBuilder.add(name1);
            featureBuilder.add(name2);
            featureBuilder.add(name);
            featureBuilder.add(name4);
            SimpleFeature feature = featureBuilder.buildFeature(null);
            features.add(feature);
        }
    }
} finally {
    reader.close();
}

A: OK - if tokens[5] is speed, you likely need to parse it from a String to a number, e.g. Integer.parseInt(tokens[5]), or Float.parseFloat(tokens[5]).  Then you can skip lines like you did for blanks, this time only when the speed is less than 5. And if you only want to skip the first lines below 5, you can keep a flag for foundAnyRowHigherThan5.  See an example below:
    boolean foundAnyRowHigherThan5 = false;
    for (line = reader.readLine(); line != null; line = reader.readLine()) {
        if (line.trim().length() > 0) { // skip blank lines
            String tokens[] = line.split("\\,");
            String name1 = tokens[0].trim();
            String name2 = tokens[1].trim();
            double latitude = Double.parseDouble(tokens[2]);
            double longitude = Double.parseDouble(tokens[3]);
            String name = tokens[4].trim();

            String speedString = tokens[5].trim();
            float speedFloat = Float.parseFloat(speedString);

          if(foundAnyRowHigherThan5 || speedFloat > 5.0) {
            // from this point forward, you will not skip lines based on speed.
            if(!foundAnyRowHigherThan5) {
              foundAnyRowHigherThan5 = true;
            }

            /* Longitude (= x coord) first ! */
            Point point = geometryFactory.createPoint(new Coordinate(longitude, latitude));

            featureBuilder.add(point);
            featureBuilder.add(name1);
            featureBuilder.add(name2);
            featureBuilder.add(name);
            featureBuilder.add(name4);
            SimpleFeature feature = featureBuilder.buildFeature(null);
            features.add(feature);
          }
       }
    }
} finally {
    reader.close();
}


text:
Q: How to enable default notifications with notify-osd? Some time ago I found that pretty ubuntu notifications are available as a package notify-osd in ArchLinux. I installed and tested it. The question is how to enable notifications running by default in ubuntu (volume up/dpwn, backlight, some programs notifications, etc)?
I'm using XMonad WM instead of desktop environment.

A: According to the Arch Wiki, notify-osd replaces notification daemon. So you will need applications which use this. Many applications, such as Pidgin, can be made to support it using plugins, configuration, or build options. For the volume, backlight, etc, things will be more difficult. These are probably provided in Ubuntu by Gnome. You will need to find some notification daemon-supporting software to replicate all of this functionality.


text:
Q: Average distance from centre of regular polygon to perimeter I am trying to find the average distance between the centre of an $n$-sided regular polygon, and all its points on the perimeter in terms of its side length $x$, and its number of sides $n$.
I have tried taking the maximum and minimum possible distances and then averaging them, however I am fairly certain this will only give a rough approximation. Maybe there is some calculus approach that I'm missing?
Any ideas?
Progress edit:
I simplified this question down (by symmetry) to finding the average distance from the corner of a right triangle (with shorter sides of $\frac{x}{2}\cot{\frac{\pi}{n}}$ and $\frac{x}{2}$) to the opposite edge:
I led the distance be $d$:
so $d=\frac{x}{2\tan{\frac{\pi}{n}}}\sec{\theta}$, where $\theta$ is the angle between the base of the triangle and $d$.
Then I took the average of $d$ as $\theta$ ranges from $0$ to $\frac{\pi}{n}$:
Average = $$\frac{n}{\pi}\int_0^{\frac{\pi}{n}}{\frac{x}{2\tan{\frac{\pi}{n}}}\sec{\theta}d\theta}$$
which I then found to be
$$=\frac{nx}{2\pi\tan{\frac{\pi}{n}}}ln{|\sec{\frac{\pi}{n}}+\tan{\frac{\pi}{n}}|}$$
Have I done something wrong here? Am I taking the average with respect to the wrong variable?

A: tl; dr: There are multiple ways to define and compute the average distance requested, depending on the "measure" we put on each side of our $n$-gon. No one of them is The True Mathematical Answer. Instead, the measure must be chosen as part of the question. (Many probability "paradoxes" result from glossing over this central detail by assuming "at random" has a single geometric meaning.)

To fix coordinates, parametrize one side of our $n$-gon using the polar angle $\theta$, so that
$$
(x, y) = (\cos\tfrac{\pi}{n}, \sin\theta),\qquad
0 \leq \theta \leq \tfrac{\pi}{n}.
$$
The distance function to the center is
$$
r = \sqrt{x^{2} + y^{2}} = \sqrt{\cos^{2}\tfrac{\pi}{n} + \sin^{2}\theta}.
$$
The average with respect to a measure $d\mu$ is
$$
\int_{-\pi/n}^{\pi/n} r\, d\mu.
$$
$n$-gon" />
Three measures are shown in the diagram:

*

*The "angle" measure $d\theta$, for which small pieces of the side are counted proportionally to the subtended angle at the origin. The probability density is the constant function (green) $\frac{n}{2\pi}$ on $(-\frac{\pi}{n}, \frac{\pi}{n}]$ whose integral is $1$. (The height is doubled for visual clarity.) The average distance in this measure is
$$
\frac{n}{2\pi}\int_{-\pi/n}^{\pi/n} \sqrt{\cos^{2}\tfrac{\pi}{n} + \sin^{2}\theta}\, d\theta
= \frac{n}{\pi}\int_{0}^{\pi/n} \sqrt{\cos^{2}\tfrac{\pi}{n} + \sin^{2}\theta}\, d\theta.
$$

*The "arc length" measure $ds = dy = \cos\theta\, d\theta$, for which small pieces of the side are counted proportionally to their Euclidean length. The probability density is the function $(\cos\theta)/2\sin(\pi/n)$ (blue, again with height doubled for clarity in the diagram). This density is smaller near the endpoints because an interval of length $ds$ subtends a smaller angle at the center the further the lies from the midpoint of its side. (Equivalently, a fixed angular increment describes a longer interval farther from the midpoint.) The average distance in this measure is
$$
\frac{1}{2\sin(\pi/n)}\int_{-\pi/n}^{\pi/n} \sqrt{\cos^{2}\tfrac{\pi}{n} + \sin^{2}\theta}\cos\theta\, d\theta
= \frac{1}{\sin(\pi/n)}\int_{0}^{\pi/n} \sqrt{\cos^{2}\tfrac{\pi}{n} + \sin^{2}\theta}\cos\theta\, d\theta.
$$
This may be evaluated using first-year calculus. (I haven't evaluated, but the formula in your post, which resembles the antiderivative of $\sqrt{a^{2} + u^{2}}\, du$, in not implausible.)

*The "delta" measure supported at the midpoint and vertex, for which a small piece of side has "mass" $\frac{1}{2}$ if it contains the midpoint or vertex. Loosely, the density function (purple) should be viewed as infinite at these two points, signified by the dashed arrows. (To make this intuition mathematically rigorous it's necessary to re-cast "measures as integrals of probability densities" in other terms.) The average distance in this measure is your first estimate:
$$
\tfrac{1}{2}(\cos\tfrac{\pi}{n} + 1).
$$


text:
Q: How to add users to Administrators group in new Azure API Management Developer Portal when only using Azure AD Identity? I have an API Management instance running where users can login using only Azure AD. There is a single Administrators account, but it is using the legacy User/Password Identity. I cannot remove the user. I want to assign a user from the Azure AD to the Administrators group, but I can not figure out how.
I have followed these steps by Microsoft but they just seem to redirect me to the legacy portal (or the new Developer portal if I change the URL normally) with my default Administrators account logged in.

A: As far as I know, we can't add another user into "Administrators" group.

The document you provided is used to login another user(which is not admin) as administrator. So the result page shows your default administrators account. The title "How do I add a user to the Administrators group?" of the document is not very accurate.


text:
Q: F# - Hex to ASCII
*

*There is something better than Convert for the 2 operations in the following code?

*I'd like to know if this solution (sprintf) is better (or worst) than one with the use of Substring

*I'd like to know if using a list here would be better

*The previous 2 questions change within the size of the string? (a short one (less than 20 chars) or a long one)

Assume the input is always correct (no odd lenght).
let hexToAscii (hex:string) =
    let chars = Array.zeroCreate<char> (hex.Length/2)
    for i in 1..2..hex.Length-1 do
        chars.[i/2] <- Convert.ToChar(Convert.ToByte(sprintf "%c%c" hex.[i-1] hex.[i] , 16))

    String(chars)

Is a question like this better suited for https://codereview.stackexchange.com ?

A: A more idiomatic solution would be this:
First deal with a single byte e.g. "42"
let hexByteToAscii (s:string) =
    System.Convert.ToByte(s,16)
    |> System.Convert.ToChar

and let's have helper function to convert char[] to string
let charsToString (chars:char[]) =
    new string (chars)

Then let's deal with a longer sequence like "4142" by taking chunks of 2 characters and use our existing function to deal with bytes.
let hexToAscii (value:string) =
    value
    |>Seq.chunkBySize 2
    |>Seq.map ( hexByteToAscii << charsToString)
    |>Seq.toArray
    |>charsToString

You can test it:
hexToAscii "4142" // "AB"

In terms of performance both are asymptotically O(n) where n is the size of your input string.   I wouldn't worry much more unless your n> 10000.  Which doesn't seem to be your scenario.  Perhaps there's some gains to be made by implementing your own hex byte to ascii function using a dictionary table.


text:
Q: Unable to access global variable through FirefoxDriver I'm trying to retrieve a JavaScript global variable's value and I always get undefined when I run the test in FireFox.
This test is successful in Chrome.
index.html
<html>
<head>
<script type="text/javascript">
   window.seleniumTesting = "Just A Test";
</script>
</head>
<body>
    ....
</body>
</html>

Test.java
WebDriver drive = new FirefoxDriver();
driver.get("http://localhost");
// Wait for the page to load. I know there are better ways of doing this.
synchronized (Thread.currentThread()) {
    try {
        Thread.currentThread().wait(55000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
String str = (String)((JavascriptExecutor) driver).executeScript("console.info(window.seleniumTesting); return window.seleniumTesting;");
System.out.println("str: |"+str+"|");

When I run this, str is null and in the browser's JavaScript console window.seleniumTesting is logged as undefined.
If I use a ChromeDriver instead of FirefoxDriver. Everything is as expected (str is Just A Test and the console logs: Just A Test).
This seems to be a JavaScript context problem. It seems that in FirefoxDrive the JavaScript context is not the web page's context.
Is this a known issue ? Can I change the driver's JavaScript context to the web page's context ?
[EDIT]
I'm using the geckodriver for OSX.
[EDIT] And FireFox version 47.

A: With the geckodriver currently v0.10.0, you must use window.wrappedJSObject to access a non-standard property of the window object:
String str = (String)((JavascriptExecutor)driver).executeScript("return window.wrappedJSObject.seleniumTesting;");


text:
Q: How to add an element to every row in a data frame? I have three types of columns in my dataframe: numeric, string and datetime.
I need to add the element | to the end of every value as a separator
I have tried:
df['column'] = (df['column']+ '|')

but it does not work for the datetime columns and I have to add .astype(str) to the numeric columns which may result in formatting issues later.
Any other suggestions?

A: you can use DataFrame.to_csv() with sep="|", if you want to create a csv.
further documentation :
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html

A: Not too sure why you would want to do this but if you want to make a CSV file with | as the delimiter, you can set that in the df.to_csv('out.csv', sep='|') method. I think a cleaner way of doing this would be to use a lambda function:
df['column'] = df['column'].apply(lambda x: f"{x}|")

You will always have to add .astype(str) though...

A: This may help you in this case:
df['column'] = df['column'].astype(str) + "|"


text:
Q: Console on snippet going behind contents I was googling for a code and I reached this Stack Overflow page.
Owl Carousel on change not working
I tried running the code in answer and it will log something in console in every slide change.
But after few slide changes, the console's height is crossed the content. Normally the console should be shown front side and the page should be scrollable and the content should be pushed to backward but it is not happening.
I then tried on MSE and the issue is here.
There are many sites that make use of Snippet not only Stack Overflow.

Here is a sample code to reproduce the issue. Try changing the slide for 4-5 times.

var owl;
$(document).ready(function(){
  owl = $(".owl-carousel").owlCarousel({
    autoplay: true,
    autoplaySpeed: 300,
    loop: true,
    navSpeed: 300,
    items: 1,
    margin: 2
  });
  owl.on('changed.owl.carousel', function(e) {
    console.log("test");
  });
});
body {
  margin: 0;
  padding: 0;
}

.owl-carousel .item {
  height: 120px;
  background: #4DC7A0;
  padding: 1rem;
  list-style: none;
  margin: 10px;
  text-align: center;
  color: white;
  font-size: 20px;
  line-height: 120px;
}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.1.6/assets/owl.carousel.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.1.6/assets/owl.theme.default.min.css">

 slide1

 slide2

 slide3

 slide4

 slide5

 slide6

 slide7

 slide8

 slide9

credit for code : Dekel


text:
Q: IntellijIDEA: Неактивна кнопка Run, Warning: "Method Main is never used" у меня небольшая программка. Создала класс MainWindow:
import javax.swing.*;

public class MainWindow extends JFrame {
    public static void Main(String[] args){
        MainWindow mw = new MainWindow();
    }
    public MainWindow(){
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(320,345);
        setLocation(400,400);
        setVisible(true);
        add(new GameField());
    }
}

Но неактивна кнопка Run, а также выданы следующие предупреждения:
Class 'MainWindow' is never used
Method 'Main(java.lang.String[])' is never used
Parameter 'args' is never used
Variable 'mw' is never used

Скажите, в чем у меня проблема.

A: В public static void main() main необходимо писать с маленькой буквы. Как и все другие названия методов (но для остальных это не столь критично).

A: Проблема решена. Редактированием опции возле кнопки Run "Edit Configurations" и добавлением в Build and Run класса MainWindow


text:
Q: Generate Junit Results in Jenkins from Groovy Script How can you get a jenkins groovy script to produce a junit xml results file? I'm doing this purely for the purpose of generating junit results with a specific number of passed/failed and skipped test cases. I need this so that I have a set of test data to test against for another application. This other app goes out to various jenkins jobs and analyzes the junit results from the job's json output. I want to point my functional tests at this jenkins job for testing. (I can't use my real continuous integration jobs because that wouldn't be deterministic).
I've got a basic groovy test case like what's below. It runs but doesn't produce junit output. I didn't expect it to, but I'm also not sure how to get it to generate one.
class BunchOfTests extends GroovyTestCase {
 void testOne(){}
 void testTwo(){fail()}
}

I also played around with writing code that prints the junit results xml but it's getting lengthy and quite ugly. I've seen the threads on here about what the junit results xsd looks like but I'm thinking there's got to be an easier route to generating some results without needing a pre-made results file. 10 results or so ought to be enough for what I need.

A: Generally unit testcases in groovy has to be written as below
import groovy.util.GroovyTestCase

class sampleTest extends GroovyTestCase {

assertEquals(true, val);
}

Incase you want only Junit reporting in groovy.
How would I produce JUnit test report for groovy tests, suitable for consumption by Jenkins/Hudson?


text:
Q: Karma Angular inject directives link function into root scope Hi I am testing a directives named controller like so:
beforeEach(inject(function ($rootScope, $controller, _$httpBackend_) {
    $scope = $rootScope.$new();
    $http = _$httpBackend_;

    $controller('coreAppController', {$scope : $scope});

    $http.flush();
}));

The problem is the controller needs to access some functions within the directives link block.  Is it possible to inject this into the scope without compiling the full directive?

A: As I´ve read in your comments, your Link-Function adds the Functions you call inside your  Controller to the scope. This is not really a nice architecture, since a Directives Controller is usually used to let several directives communicate with each other, so from Link to Controller, not the other way around. If you wanna keep up with this and NEED that architecture, you should probably MOCK the Functions you wanna call from the link function - after all, its a Unit Test, so you should only test the most atmoic units and therefore dont need the whole directive.
Just do something like
beforeEach(inject(function ($rootScope, $controller, _$httpBackend_) {
   $scope = $rootScope.$new();
   $scope.MYSCOPEFUNCTION = jasmine.createSpy('MyFunctionMock');
   $http = _$httpBackend_;

   $controller('coreAppController', {$scope : $scope});

   $http.flush();
}));


text:
Q: Vue js v-autocomplete does not update dynamically changed items correctly I'm trying to integrate a v-autocomplete select form with dynamically loaded items in my Vue component based on text input. The data for the items is obtained from a http get and is tested to be correct. At first, the items appear to be fine, but once I further specify my input I start getting zero items within the component although the received data contains more than zero entries. I've been stuck at this for the last few hours, so help will be appreciated! :-)
Below I've listed the relevant parts of the code and two images which illustrate the issue. Above the text input field I have printed out the first match of the inputs, which at the second photo are missing. I think there is something wrong with the v-autocomplete component but can't figure out what.

{{locations[0]? locations[0].name : null}}

<v-autocomplete
    item-value="osm_id"
    v-model="selectedLocationIndex"
    item-text="name"
    label="Location*"
    :items="locations"
    :search-input.sync="locationInput"
    placeholder="Start typing..."
    required
>
    <template slot="item" slot-scope="data">
         {{ data.item.name }}
    </template>
</v-autocomplete>

This is the rest of the code:
watch: {
    locationInput: function(newVal, oldVal) {
        this.locations = [];
        if (newVal !== null && newVal !== '') {
            this.getLocations(newVal).then((result) => {
                const hits = result.data.hits;
                hits.map(hit => {
                    this.locations.push(hit)
                })
            }).catch((err) => {
                console.log('we have obtained an error', err)
            });
        }
    }
}

And here are the two images:
Here it works -> https://imgur.com/z9GgQ1y
Here it doesn't -> https://imgur.com/B9EN7ms

A: Add the no-filter property.

{{locations[0]? locations[0].name : null}}

<v-autocomplete
    item-value="osm_id"
    no-filter
    v-model="selectedLocationIndex"
    item-text="name"
    label="Location*"
    :items="locations"
    :search-input.sync="locationInput"
    placeholder="Start typing..."
    required
>
    <template slot="item" slot-scope="data">
         {{ data.item.name }}
    </template>
</v-autocomplete>


text:
Q: Calling "this" from an external function? I am working on a validation script for a form and rather than setting up a separate validation function for every input that requires something to be entered, I would like to create a single function that will be fired on blur of any input in the form.
How can I associate jQuery's this selector from an external function? This is what I have tried:
function inputCheck() {
    if ($(this).val() == null || $(this).val() == "") {
        $(this).addClass('error');
        $(this).next().show();
    } else {
        $(this).removeClass('error');
    }
}

$('input').blur(function() {
    inputCheck();
});

A: Yes and that's one, for me, of the best javascript strenght  easily via bind or call:
inputCheck.call(this);

call function takes as param a this object which a hash of functions/objects/vars (so you can pass this as well as other objects, {foo: "bar"} will make a this var with foo property initialized), and the next arguments are the args passed to the function

A: You could just pass a reference to the function directly:
$('input').blur(inputCheck);


text:
Q: How to add 2nd horizontal x axis scale to jqplot and customize axis settings? Note: Although this is a self-answered question, I am always curious about better approaches.

sin(x) and cos(x) for x in degrees.
Goal: I would like to adjust this initial plot and add a 2nd X axis to show both degrees and radians.
How do I set up jqPlot PlotOptions to add x and y labels, change scales, and add a second X axis?
I am using a JavaScript library that I wrote called html5csv [License: GPL] that support various data analysis operations and interfaces to jqPlot for plotting. It allows the specification of the jqPlot plotOptions object for each plot.
The (currently blank) plotOptions are on the first line of code.  You may assume the plotOptions are correctly delivered to jqPlot by the subsequent code invoking CSV().jqplot() from the html5csv library.
html5csv + jqplot dual line graph without special axes
plotOptions = {};
CSV.begin('%F', {dim:[36,4],header:['deg','rad','sin','cos'],
                 func: function(i,j){
                     var deg = 10*(i);
                     var rad = deg*2*Math.PI/360.0;
                     if (j===0) return deg;
                     if (j===1) return rad;
                     if (j===2) return Math.sin(rad);
                     if (j===3) return Math.cos(rad);
                 }
                }).
    jqplot([['chart1',[['deg','sin'],['deg','cos']], plotOptions]]).
    table('tab1',{header:1}).
    go();

jsfiddle of single axes sine, cosine wave plot
This jqPlot documentation shows up to 2 X axes and 9 Y axes but when calling new Axis() I get Uncaught ReferenceError: Axis is not defined in the console.  To fix this I tried adding more of the jqplot .js files to the script headers but it did not help.
jqplot Axis formatting options documentation shows all the options to configure axis labels, ticks, etc. for a particular axis if I could create one.
How do I proceed from here?

A: Don't call new Axis(); This is done for you internally in jqPlot.
Basically, if you declare the right keys in plotOptions, the Axis will be set up for you.  But if the keys are missing or misnamed, it will obviously fail.
Here are the finished examples:
Part 1: Customized set of single axes
Output

jqplot PlotOptions Input
plotOptions = {
  axes: {
    xaxis: {
      show: true,
      label: 'deg',
      min: 0,
      max: 360,
      tickInterval: 45
    },
    yaxis: {
      show: true,
      label: 'y',
      min: -2.0,
      max: 2.0
    }
  }
};

Note:  You don't need to call new Axis, but you do need to name the object fields as shown.

plotOptions = {
  axes: {
    xaxis: {
      show: true,
      label: 'deg',
      min: 0,
      max: 360,
      tickInterval: 45
    },
    yaxis: {
      show: true,
      label: 'y',
      min: -2.0,
      max: 2.0
    }
  }
};
CSV.begin('%F', {
  dim: [36, 4],
  header: ['deg', 'rad', 'sin', 'cos'],
  func: function(i, j) {
    var deg = 10 * (i);
    var rad = deg * 2 * Math.PI / 360.0;
    if (j === 0) return deg;
    if (j === 1) return rad;
    if (j === 2) return Math.sin(rad);
    if (j === 3) return Math.cos(rad);
  }
}).
jqplot([
  ['chart1', [
    ['deg', 'sin'],
    ['deg', 'cos']
  ], plotOptions]
]).
table('tab1', {
  header: 1
}).
go();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqPlot/1.0.9/jquery.jqplot.css" />
<script src="https://cdn.rawgit.com/DrPaulBrewer/html5csv/7f39da16/html5csv.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqPlot/1.0.9/jquery.jqplot.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqPlot/1.0.9/plugins/jqplot.canvasAxisLabelRenderer.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqPlot/1.0.9/plugins/jqplot.canvasAxisTickRenderer.js"></script>

Part 2: Dual X axes, with degrees and radians scales
Output

jqPlot PlotOptions Input
plotOptions = {
  axes: {
    xaxis: {
      show: true,
      label: 'deg',
      min: 0,
      max: 360,
      tickInterval: 45
    },
    x2axis: {
      show: true,
      label: 'rad',
      min: 0,
      max: 2 * Math.PI,
      numberTicks: 9
    },
    yaxis: {
      show: true,
      label: 'y',
      min: -2.0,
      max: 2.0
    }
  }
};

plotOptions = {
  axes: {
    xaxis: {
      show: true,
      label: 'deg',
      min: 0,
      max: 360,
      tickInterval: 45
    },
    x2axis: {
      show: true,
      label: 'rad',
      min: 0,
      max: 2 * Math.PI,
      numberTicks: 9
    },
    yaxis: {
      show: true,
      label: 'y',
      min: -2.0,
      max: 2.0
    }
  }
};
CSV.begin('%F', {
  dim: [36, 4],
  header: ['deg', 'rad', 'sin', 'cos'],
  func: function(i, j) {
    var deg = 10 * (i);
    var rad = deg * 2 * Math.PI / 360.0;
    if (j === 0) return deg;
    if (j === 1) return rad;
    if (j === 2) return Math.sin(rad);
    if (j === 3) return Math.cos(rad);
  }
}).
jqplot([
  ['chart1', [
    ['deg', 'sin'],
    ['deg', 'cos']
  ], plotOptions]
]).
table('tab1', {
  header: 1
}).
go();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqPlot/1.0.9/jquery.jqplot.css" />
<script src="https://cdn.rawgit.com/DrPaulBrewer/html5csv/7f39da16/html5csv.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqPlot/1.0.9/jquery.jqplot.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqPlot/1.0.9/plugins/jqplot.canvasAxisLabelRenderer.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqPlot/1.0.9/plugins/jqplot.canvasAxisTickRenderer.js"></script>

Notes:  No need to call new Axis() here, either.  Name the plotOptions keys properly and it works.
Plotting of data used the original single X coordinate using the 1st X axis.

Reference
From the jqPlot Axis docs:

Axes options are specified within an axes object at the top level of the plot options like so:

{
   axes: {
       xaxis: {min: 5},
       yaxis: {min: 2, max: 8, numberTicks:4},
       x2axis: {pad: 1.5},
       y2axis: {ticks:[22, 44, 66, 88]}
       }
}

There are 2 x axes, 'xaxis' and 'x2axis', and 9 yaxes, 'yaxis', 'y2axis'.  'y3axis', ...  Any or all of which may be specified.

Useful axis options excerpted from the documentation
Note: Additional options do exist.  These are the most basic ones.
In a few of these I edited slightly for clarity.

show
true to display the axis on the graph.
label
Label for the axis
showLabel
true to show the axis label.
min
minimum value of the axis (in data units, not pixels).
max
maximum value of the axis (in data units, not pixels).
autoscale
true to Autoscale the axis min and max values to provide sensible tick spacing.
If axis min or max are set, autoscale will be turned off.  The  numberTicks, tickInterval and pad options do work with autoscale, although tickInterval has not been tested yet. padMin and padMax do nothing when autoscale is on.
ticks
1D [val, val, ...] or 2D [[val, label], [val, label], ...] array of ticks for the axis.  If no label is specified, the value is formatted into an appropriate label.
numberTicks
Desired number of ticks.  Default is to compute automatically.
tickInterval
number of units between ticks.  Mutually exclusive with numberTicks.
showTicks
true to show the ticks (both marks and labels) or not.  Will not override showMark and showLabel options if specified on the ticks themselves.
showTickMarks
true to show the tick marks (line crossing grid) or not.  Overridden by showTicks and showMark option of tick itself.
syncTicks
true to try and synchronize tick spacing across multiple axes so that ticks and grid lines line up.  This has an impact on autoscaling algorithm, however.  In general, autoscaling an individual axis will work better if it does not have to sync ticks.
tickSpacing
A number giving approximate pixel spacing between ticks on graph.  Used during autoscaling.  This number will be an upper bound, actual spacing will be less.


text:
Q: Equivalent of penalty.factor in caret? I would like to set the penalty of some coefficients to 0 while using Lasso. The glmnet function has an option called penalty.factor for this purpose. Is there an equivalent in the caret package?

A: Inside the train function:
model_fit <- train(Data[,-1], Data[,1],method = "glmnet",penalty.factor=rep(1,50),...)


text:
Q: Is this recursive reference with tuples safe? I'm experimenting and wrote this monster:
class my_tuple : public std::tuple < std::vector<my_tuple> > {};

And it compiles and actually works, it seems. And I find it dodgy because the following doesn't compile:
using my_other_tuple = std::tuple < std::vector<my_other_tuple> > ;

Ultimately, I'm trying to wrap my head around why my_tuple works and if there's any potential terrible consequences. I'm trying to learn what tuples are all about and what I can/am supposed to do with them. So if anyone would care to comment on that, give some nifty insights, I would appreciate it.
Windows 7 and VS 2013.

A: class my_tuple : public std::tuple < std::vector<my_tuple> > {};

This is currently undefined behavior because it instantiates a standard library container, std::vector, with an incomplete type, my_tuple, which does not become complete until the closing } of its definition. However, there is a proposal to permit instantiating certain standard containers, including std::vector, with incomplete types. Boost.Containers supports incomplete types as well.
using my_other_tuple = std::tuple < std::vector<my_other_tuple> > ;

This is ill-formed. [dcl.typedef]/p2, emphasis mine:

A typedef-name can also be introduced by an alias-declaration. The
  identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier
  appertains to that typedef-name. It has the same semantics as if it
  were introduced by the typedef specifier. In particular, it does not
  define a new type and it shall not appear in the type-id.


text:
Q: Magento 2 - How to change Mega Menu sort order in store views alphabetical for each store view? maybe one of you is facing the same issue and has solved it already.
We are using the Mega Menu for Magento 2. We have 5 store views (German, English, Spanish, Italian, French)
Our default language shop and store view is german.
Now I sort my categories alphabetical for german in the backend which then is reflected in the sort order in the mega menu in the front end as well.
But this sort order of the categories is then taken for all other languages as well and mixed up. I have not found a way to sort each store views categories alphatebically individually.
How would you solve this? Is a styling via CSS or such possible for the other languages than German possibly?
Maybe one of the experts out there has a hint.
Thanks a ton in advance.

A: You need to create different root category for each store.
Apply it to particular store from Admin > Stores > Edit Store > Root Category

Set different root category for each store you can manage sort order of category

A: Hopefully you got the answer you needed for this but just in case anyone else stumbles across this issue, here is my solution.
You need to check what scope you're altering when changing category sorting

If you're on "All Store Views" then it will re-arrange them in all views.
Also, as you have already said, if you're re-arranging your default store then you need to make sure that the "use default value" button within all dropdowns of your other store views is disabled so any changes you make aren't reflected across the board.


text:
Q: How to automate BusyBox telnet I need an automated telnet script between two embedded Linux targets using BusyBox v1.22.1 on the client and BusyBox v1.10.3 on the host. Note: Expect is not available on this system. I've tried the recommendations here without success. For example, this
host=1.1.1.2
port=23 # note - port is not required
pass=xxxx # note - pass is not required
cmd1=24

( echo open ${host} ${port}
  sleep 1
  echo -e "\r"
  sleep 1
  echo ${pass}
  sleep 1
  echo -e "\r"
  sleep 1
  echo ${cmd1}
  sleep 1
  echo -e "\r"
  sleep 1
  echo exit ) | telnet

returns this
Usage: telnet [-a] [-l USER] HOST [PORT]
Connect to telnet server
        -a      Automatic login with $USER variable
        -l USER Automatic login as USER

So I tried various combinations of 'Usage' (above) without success (it always asks for a manually entered 'login').
Is telnet automatic login broken on BusyBox v1.22.1 or am I just missing something simple?

A: Eventually got it to work using the original example I pointed to. The confusing part was that the telnet session was exiting without the exit command at the final ")". Also, none of the commands during the telnet session block so the sleep for each command has to be long enough. In this case the 'user' is root and there is no password. I may need to insert a few echo -e "\r" but here is the working command that will be incorporated into the script:
( echo -e "\r"
  sleep 1
  echo root
  sleep 2
  echo ${cmd1}
  sleep 65
  echo ${cmd2}
  sleep 2
  echo ${cmd3}
  sleep 52 ) | telnet $host


text:
Q: Running wyd.pl in Cygwin - Can't locate object method "init" via package "wlgmod::doc" After a few days of trying to get wyd.pl running on my Windows 7 machine, I'm finally pretty close. I've installed a working version of Cygwin on what must be the 5th attempt, and I now have a working bash shell.
However, when running the following WyD command in bash:
$ wyd.pl -b -e -t -s 3 -o "OUTPUTFILE" "TARGETDIRECTORY"
...I get an error for a single missing dependency:

Can't locate object method "init" via package "wlgmod::doc" (perhaps you forgot to load "wlgmod::doc"?) at /cygdrive/c/WYD/wyd.pl line 284.

Sometimes wlgmod::doc is replaced with wlgmod:jpeg or wlgmod::plain, but it's the same basic error. This is a welcome change from when I tried to run the program in CMD, which came back with tens of missing dependencies, but I'd like to figure out how to make this final one go away so I can finally run the program.
Looking in the directory where WyD is installed on Windows - C:\WYD - I see a folder called wlgmod, which contains doc.pm, jpeg.pm, html.pm, etc. Presumably, these are the 2packages" that bash is asking for, but judging by the output of the above error, it seems to be running WyD from that very same directory, so I'm confused as to why it can't find those files.
The only thing I can guess is that all this has something to do with the version of Perl being run. Doing perl -v in both consoles bolsters this a little.
CMD - V5.24.1
Cygwin/bash - V5.22.3

Other than that... I'm really confused and I have no idea what I'm doing.

A: wyd.pl is perl script and it needs some perl modules to parse the files. Here's how to resolve:

*

*Get OpenOffice::OOD

perl -MCPAN -e shell

install OpenOffice::OOD

*Get catdoc

 tar xzvf catdoc-0.94.tar.gz

 ./configure

 make

 make install

*Get jhead

  tar xzvf jhead-latest.tar.gz

  cd jhead-2.90

  make

*Get mp3info

 cd mp3info-0.8.5a

 make mp3info

 make install-mp3info

*apt-get install libncurses5-dev libncursesw5-dev


text:
Q: Assume $y(t)$ is a solution of the problem $y''+e^{-t}y'+y=0,y(0)=1,y'(0)=2$ then $(y'(t))^2+(y(t))^2\le 5,\quad \forall t\in[0,\infty)$ Assume $y(t)$ is a solution of the problem $$y''+e^{-t}y'+y=0,y(0)=1,y'(0)=2$$
then $$(y'(t))^2+(y(t))^2\le 5,\quad \forall t\in[0,\infty)$$
I have considered to use mean value theorem but did not end up so well.
Then I comment on the $e^{-t}y$ term since as t goes infinity this term vanishes so we end up with $y''+y=0$ which has periodic solution $$c_1 \cos(t)+c_2 \sin(t)$$ and applying initial values we have $$y=\cos(t)+2\sin(t)$$
and taking derivative we see that $y^2+(y')^2\le \sqrt5^2+\sqrt5^2$
If we tried to start with equation as $$y''+y'+y=0$$ assuming $e^{-t}$ is max at $t=0$ so start with maximum (But it doesnot imply maximality of the desired equality so again failed)
I think there should be more simple way to analyse the question, any hint answer would be appreciated!

A: Let $H = y'^2 + y^2.$ Then, differentiating in $t$, $$H' = 2 y' (y'' + y) = - 2 e^{-t} y'^2 \le 0.$$
So, $H$ is non-increasing for $t \ge 0$. Its initial value is $5$, so we're done.
In physical terms, the $e^{-t} y'$ term in your differential equation is some sort of "friction", dissipating the "total energy" $H$. The fact that it decays to zero for large $t$ is a red herring; this reasoning works if we substitute $e^{-t}$ with any non-negative coefficient.


text:
Q: Is there a reason not to use part and part of instead of import in a Flutter app? I know when to use part and part of in pure dart, but I haven't found any information about using it in a flutter app (for Widget for example) instead of import, so I'm curious if there is a reason that in that case.
Consider an example where you have a page with a tab bar. To improve maintainability you create the pages in separate files.
Now there are two options: import the pages or make them part of the tab bar page. The latter has the advantage that the pages can be private classes, and you can have private classes in the tab bar page if there are components that are shared between the pages.
To me this seems like a good solution, but since I haven't found anyone that has done it this way I'm starting to think that there might be some drawbacks. Is there a reason to use import instead of part and part of in this case?
tab_bar_demo.dart
part 'page1.dart';
part 'page2.dart';
part 'page3.dart';
part 'page4.dart';

class TabBarDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DefaultTabController(
        length: 3,
        child: Scaffold(
          appBar: AppBar(
            bottom: TabBar(
              tabs: [
                Tab(icon: Icon(Icons.directions_car)),
                Tab(icon: Icon(Icons.directions_transit)),
                Tab(icon: Icon(Icons.directions_bike)),
              ],
            ),
            title: Text('Tabs Demo'),
          ),
          body: TabBarView(
            children: [
              _Page1(),
              _Page2(),
              _Page3(),
            ],
          ),
        ),
      ),
    );
  }
}

class _PageContentWrapper extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

page1.dart:
part of 'tab_bar_demo.dart';

class _Page1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}


text:
Q: Populate controls of dynamically instantiated Page from ASPX file? Currently I have a single Example.aspx file (with no code behind) and I want to load it, populate the controls it has, get the ouput of it and do something with it (inside a http handler).
What I am doing is this:
// Gets the page and instantiates it?
Type type = BuildManager.GetCompiledType("~/Example.aspx");
Page page = (Page)Activator.CreateInstance(type);

// ProcessRequest of page here?

// Error happens here, the page doesn't have any controls (but there is a label).
((Label)page.FindControl("Label")).Text = "Hello World";

using (StringWriter output = new StringWriter())
{
    // Execute the page and output the result into the string writer.
    HttpContext.Current.Server.Execute(page, output, false);

    // Do something with the output (or save it, email it, etc)
    // ...in this case we render it.
    context.Response.ContentType = "text/html";
    context.Response.Write(output.ToString());
}

But it doesn't work since the page instance doesn't have any controls (needs to create child controls?).
If I add:
page.ProcessRequest(HttpContext.Current);

it works, but I think it runs the whole page life cycle and that includes rendering the page to the response, something I don't want.

A: When creating page instance with activator, you could hook up with init or load event to execute additional code while proccesing http request. Dont forget it is still an event driven model! I hope it helps.


text:
Q: jQuery fade image gradient to 0 Is it possible using jQuery to fade an image from 100% at the top to 0% at the bottom.
The idea being to create a gradual fade of an image across its height.

A: If you don't want to use transparent png in the background, then u can use the jQuery way that is provided here
I hope this will help!


text:
Q: Grails restrict old browsers I'm running in Grails v2.4.4. How can I prevent user access web in the old browsers. This page works only on IE9 or higher. How can I stop them with lower?
I looked on Grails plug in and found browser detection plugin. But in seems to work on view site instead of server site.

A: The browser detection plugin can be used outside of GSP, from the documentation:
"or you can use the UserAgentIdentService anywhere in your code"
Though I can't locate any documentation for that service, so browse the source and have a look at the methods there. Try this:
userAgentIdentService.isMsie(org.geeks.browserdetection.ComparisonType.LOWER, "9")


text:
Q: How can I set up an alert to send an email when someone does a vip swap in azure I have several individuals across multiple organizations that would like to know when a change has been made to our azure platforms. They only connect through the production environment.
I would like to set up an email alert that goes out when a Virtual IP swap has been performed but it does not seem to be an option in the cloud alert services.
Is there something I am missing or another way to do this?

A: I dont believe there is anyway to do this without custom coding.
Edit thanks to kwill's correct responses:
1) You can install something on the Webrole that would periodically check RoleEnvironment.CurrentInstance.
var roleInstance = RoleEnvironment.CurrentRoleInstance;
foreach (RoleInstanceEndpoint instanceEndpoint in roleInstance.InstanceEndpoints.Values)
{
   Trace.WriteLine("Instance endpoint address and port: " + instanceEndpoint.IPEndpoint, "Information");
   Trace.WriteLine("Protocol for the endpoint: " + , instanceEndpoint.Protocol, "Information");
}

2) You can create a custom application that would use Service Management API to get at the RoleInstance object from the "outside" by using management certificates and navigating the hierarchy of services, roles, etc.  If using Visual Studio/.NET here's a library to help you get started: http://www.nuget.org/packages/microsoft.windowsazure.management.libraries


text:
Q: Android: Кодировка в WebView Проблемка такая: есть готовый HTML-код (таблица в основном своём).
Я его записываю в переменную и вывожу через WebView.
И фишка в том,что у меня текст нормальный, русский в эмуляторе и на смартфоне. А у друга крякозяблы - что-то с кодировкой не то.
В чём может быть проблема. Пробовал текст хранить и просто как переменная и в файле - одна малина.
webView = (WebView) findViewById(R.id.webView);
webView.loadData(text,"text/html","utf-8");

Строка примерного плана:
<!Doctype html><meta charset=utf-8>Не найдено.

A: Попробуй вот это :
webView.loadDataWithBaseURL(null, text,"text/html", "UTF-8", null);


text:
Q: Kernel / determinant of this continuous operator Consider the operator $\phi_1$ which takes a continuous function $u$ defined over $[0,1]$ and returns the function $\phi_1(u)$ defined over $\mathbb{R}$ constructed such that it is odd and $2$-antiperiodic. Simarly, consider $\phi_2$ such that $\phi_2(u)$ is odd and $2$-periodic.
Lastly, for any $t_1>0$ and $t_2>0$, define the operator $\Delta$ which maps two continuous functions $u,v$ defined over $[0,1]$ to a function of $\mathbb{R}$:
\begin{align}
\Delta(u,v):x\mapsto \,&\phi_1(u)(x+ct_1)  + \phi_1(u)(x-ct_1) - \phi_2(u)(x+ct_2)  - \phi_2(u)(x-ct_2)
\\ &\quad + \dfrac{1}{c}\int_{x-ct_1}^{x+ct_1} \phi_1(v)(s)\,\mathrm{d}s - \dfrac{1}{c}\int_{x-ct_2}^{x+ct_2} \phi_2(v)(s)\,\mathrm{d}s
\end{align}
where $c>0$ is a scalar (you will probably have recognized the difference of two d'Alembert solutions).
I would like to characterize $t_1,t_2,u,v$ such that $\Delta(u,v)$ has a non trivial kernel. I must say I have never faced such a problem in the continous framework and have no idea how to start or even if it is possible to solve it.