text:
Q: Let $A$ be non singular, prove that $\frac{1}{\|A^{-1}\|} = \min_{\|x\| = 1} \|Ax\|$ Let $A$ be non singular, prove that $\frac{1}{\|A^{-1}\|} = \min_{\|x\| = 1} \|Ax\|$
I know that $\|A\| = \sup_{\|x\| = 1} \|Ax\|$
but I have no idea how to proceed from here.

A: $\|A\|$ equals to the largest singular value of $A$. Since $A$ is nonsingular, all singular values are nonzero. Hence, the singular values of $A^{-1}$ are the inverses of the singular values of $A$. Therefore, $\|A^{-1}\|$ is the inverse of the smallest singular value of $A$.
Sine $\min_{\|x\|=1}\|Ax\|$ is the smallest singular value of $A$, the equality holds!
More precisely, assume that $\newcommand{\reals}{{\mathbf R}} A\in \reals^{n\times n}$. Suppose that $A=U\Sigma V^T$ is the singular value decomposition of $A$ with $U^TU = V^TV = I_n$, $\newcommand{\diag}{{\bf diag}}\diag(\sigma_1,\ldots,\sigma_n)$ and $\sigma_1\geq \sigma_2 \geq \cdots \geq \sigma_n$. Since $\sigma_i$ are singular values, $\sigma_i\geq0$. Since $\newcommand{\det}{{\bf det}}|\det A| = |\det(U)||\det(\Sigma)||\det(V)| = |\sigma_1 \cdots \sigma_n|$, nonsingularity of $A$ implies that $\sigma_i > 0$ for all $1\leq i\leq n$.
Now
\begin{eqnarray}
\|A\|
&=& \sup_{\|x\|=1}\|Ax\|
= \sup_{\|x\|=1}\sqrt{\|Ax\|^2}
= \sup_{\|x\|=1}\sqrt{x^TA^TAx}
= \sup_{\|x\|=1}\sqrt{x^TA^TAx}
\\
&=&
\sup_{\|x\|=1}\sqrt{x^TV\Sigma U^T U\Sigma V^Tx}
\\
&=&
\sup_{\|x\|=1}\sqrt{x^TV\Sigma^2V^Tx}
\\
&=&
\sup_{\|x\|=1} \|\Sigma V^Tx\|
\\
&=&
\sup_{y=V^Tx,\ \|x\|=1} \|\Sigma y\|
\\
&=&
\sup_{\|y\|=1} \|\Sigma y\|
\\
&=&
\sup_{\|y\|=1} \sqrt{\sigma_1^2 y_1^2 + \cdots + \sigma_n^2 y_n^2}
\end{eqnarray}
since $\|y\|^2 = y^T y = x^T V V^T x = x^T x = \|x\|^2$.
Now
\begin{equation}
\sigma_1^2 y_1^2 + \cdots + \sigma_n^2 y_n^2
\leq \sigma_1^2 y_1^2 + \cdots + \sigma_1^2 y_n^2 = \sigma_1^2 \|y\|^2 = \sigma_1^2
\end{equation}
with the equality achieved when $y_1=1$ and $y_2=\cdots=y_n = 0$.
Therefore
\begin{equation}
\|A\| = \sigma_1,
\end{equation}
i.e., $\|A\|$ equals to the largest singular value of $A$.
Therefore
\begin{equation}
\frac{1}{\|A^{-1}\|}
= \frac{1}{1/\sigma_n}
= \sigma_n,
\end{equation}
i.e., the smallest singular value.
Now the same derivation as before gives
\begin{equation}
\inf_{\|x\|=1} \|Ax\| = \inf_{\|y\|=1} \|\Sigma y\|.
\end{equation}
Since
\begin{equation}
\sigma_1^2 y_1^2 + \cdots + \sigma_n^2 y_n^2
\geq \sigma_1^2 y_n^2 + \cdots + \sigma_n^2 y_n^2 = \sigma_n^2 \|y\|^2 = \sigma_n^2
\end{equation}
with the equality achieved with $y_1=\cdots=y_{n-1}=0$ and $y_n=1$,
\begin{equation}
\inf_{\|x\|=1} \|Ax\| = \sigma_n,
\end{equation}
hence the proof!

A: Maybe this will help to grasp the idea:
$$
\begin{split}
\|A^{-1}\|
&=
\max_{x\neq 0}\frac{\|A^{-1}x\|}{\|x\|}
=
\max_{y\neq 0}\frac{\|y\|}{\|Ay\|}
=
\left(\min_{y\neq 0}\frac{\|Ay\|}{\|y\|}\right)^{-1}.
\end{split}
$$

A: Let $v\in \mathbb{R}^n$ such that $\|v\|=1$. Then $$1=\|v\|=\|A^{-1}Av\|\leq \|A^{-1}\|\|Av\|$$ This means $\frac{1}{\|A^{-1}\|}$ is a lower bound of $\{\|Av\|:\|v\|=1\}$. Thus $\frac{1}{\|A^{-1}\|}\leq\inf_{\|x\|=1}\|Ax\|$. On the other hand, $$\begin{eqnarray} 1 &=& \|v\|  \\ &=& \|Av\| \cdot \Bigg\|A^{-1}\Bigg(\frac{Av}{\|Av\|}\Bigg)\Bigg\| \\& \geq & \inf_{\|x\|=1}\|Ax\|\cdot \Bigg\|A^{-1}\Bigg(\frac{Av}{\|Av\|}\Bigg)\Bigg\|\end{eqnarray}$$ Since $u\mapsto \frac{Au}{\|Au\|}$ is a surjection on $S^{n-1}$ we see $\frac{1}{\inf_{\|x\|=1}\|Ax\|}$ is an upper bound of $\{\|A^{-1}v\|:\|v\|=1\}$. Thus $$\|A^{-1}\|\leq \frac{1}{\inf_{\|x\|=1}\|Ax\|} \iff \inf_{\|x\|=1}\|Ax\|\leq \frac{1}{\|A^{-1}\|}$$ The result follows.


text:
Q: Capture text between two different char. Between the first{ and the last } Capture text between two different char using PowerShell.  Between the first{ and the last } .  Basically there is text with Json in it and I want to capture the json from it.  I have looked for examples but so far no luck.

PROJECT Description: Azure Test Project Description

PROJECT ADMINISTRATORS: jjohnson

CONTRIBUTORS: jdoe

BOARD PROCESS: Agile

SPECIAL INSTRUCTIONS:

{
"organization": "https://dev.azure.com/cloudops",
"projectName": "Test Project",
"projectDescription": "Azure Test Project Description",
"projectProcessType": "Agile",
"specialInstructions": "",
"adminMembers": [
{
"userSamAccountName": "jjohnson",
"userEmailAddress": "jjohnson@test.com",
"userPrincipalName": "jjohnson@test.com",
"projectGroupType": "projectAdministrator"
}
],
"contribMembers": [
{
"userSamAccountName": "jdoe",
"userEmailAddress": "jdoe@test.com",
"userPrincipalName": "jdoe@test.com",
"projectGroupType": "projectContributor"
}
]
}

A: Is this what you were looking for?
[Regex]::Match((Get-Content "sampleinputfile.txt" -Raw),
  '^{.+}',
  [Text.RegularExpressions.RegexOptions]::Multiline -bor
  [Text.RegularExpressions.RegexOptions]::Singleline).Value

Basically this converts the input file to a single (newline-delimited) string (Get-Content -Raw), and then uses the .NET Framework's Match method to do a regular expression match for the lines of text between the { and } characters (inclusive).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Implementation of a function to check who wins on a TicTacToe game This is my first approach to programming and I'm trying to create a TicTacToe game.At the moment, I'm doing a function that checks if a winning play is happening, but I'm sure that there are better ways to do this that my actual code. Any suggestions?
This is what I have:
let boardGame = new Array(9)
let turn = 'x';
let winner;
let squares = document.getElementsByClassName('board') // this variable it is used in other functions that I'm not transcribing it.

let whoWins = (boardGame) =>{

    if(boardGame[0] == 'x' && boardGame[1] == 'x' && boardGame[2]== 'x' || boardGame[3] == 'x' && boardGame[4] == 'x' && boardGame[5]== 'x' || boardGame[6] == 'x' && boardGame[7] == 'x' && boardGame[8]== 'x' || boardGame[0] == 'x' && boardGame[4] == 'x' && boardGame[8]== 'x' || boardGame[2] == 'x' && boardGame[4] == 'x' && boardGame[6]== 'x' || boardGame[0] == 'x' && boardGame[3] == 'x' && boardGame[6]== 'x' || boardGame[1] == 'x' && boardGame[4] == 'x' && boardGame[7]== 'x' || boardGame[2] == 'x' && boardGame[5] == 'x' && boardGame[8]== 'x'){

       winner = 'x'

}
    else if(boardGame[0] == 'o' && boardGame[1] == 'o' && boardGame[2]== 'o' || boardGame[3] == 'o' && boardGame[4] == 'o' && boardGame[5]== 'o' || boardGame[6] == 'o' && boardGame[7] == 'o' && boardGame[8]== 'o' || boardGame[0] == 'o' && boardGame[4] == 'o' && boardGame[8]== 'o' || boardGame[2] == 'o' && boardGame[4] == 'o' && boardGame[6]== 'o' || boardGame[0] == 'o' && boardGame[3] == 'o' && boardGame[6]== 'o' || boardGame[1] == 'o' && boardGame[4] == 'o' && boardGame[7]== 'o' || boardGame[2] == 'o' && boardGame[5] == 'o' && boardGame[8]== 'o'){
            winner = 'o'
    }
else{}
}

A: I came up with this function hoping it's not too difficult to approach with.
In case I can simplify it just let me know:)
let whoWins = (boardGame) => {

  const winningConditions = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8]
    [2, 4, 6],
  ];

  const winner = winningConditions.find(
    (condition) =>
      boardGame[condition[0]] === boardGame[condition[1]] &&
      boardGame[condition[1]] === boardGame[condition[2]]
  );

  // if the game is not finished exit
  if (winner === undefined) return;

  winner = boardGame[winner[0]];
};

Grazie


text:
Q: What's the best way to expose and compose errors in Node.js? I'm writing a module that talks to a REST API, and since the REST API provides nice, semantic error responses (e.g. 403 vs. 503), I want to convey those semantic errors to callers.
(Edit: what I mean by that is, the caller should be able to programmatically understand the cause of the error and act accordingly, e.g. display the appropriate UI.)
What's the best way for me to do so?

*

*Create my own Error subclasses for those semantics, e.g. mymodule.ForbiddenError, mymodule.ServiceUnavailableError? Callers would then check instanceof to derive semantics. This is most typical in statically-typed languages like C# and Java.

*Add e.g. a mymoduleCode property to standard Error instances, with semantic strings like 'Forbidden' or 'ServiceUnavailable'. Node.js itself does this, e.g. code: 'ECONNREFUSED'.

*Some other way?
==
I'm writing another module now, that wraps the first module. I don't want to expose the internal module's errors directly, but it'd be nice to compose/wrap them, for debuggability.
What's again the best way for me to do so?

*

*Add e.g. an internalError property to my Error instances that references the internal module's Error instance. Again C# and Java do this. (Exception#InnerException / Throwable#cause)

*Some other way?
Most tooling I've seen, though, only displays the stack property of Error instances, so this data would get lost in those cases. Is there a typical/conventional way that already exists?

A: The use case you describe is one that is definitely underserved by Node right now. Inasmuch as there are conventions in use, they tend to be some mixture of:

*

*Creating new error types that simply derive from the Error constructor. Useful mostly for creating high-level categories of errors. You can use instanceof to discriminiate between types of errors, but that doesn't feel very JavaScripty.

*Creating Java-style Error subtypes that take another error as a constructor argument and then wrap them. If you make the subtype expose an API, you're basically using polymorphism instead of direct dispatch to handle the errors based on types.

*Creating semantically useful error messages via the Error constructor. This is a pattern I tend to use a lot.

*Attaching properties to Errors, which is also extremely common.

*Create a decoupled error-handling API that can be invoked from wherever the error originates. This gives you a single place to concentrate all the code that figures out what kind of error you have and what you should do with it, and inject whatever dependencies you need to handle the errors.

The real problem here is that these are all ad hoc mechanisms and I wouldn't say that any of them have reached critical mass. I think this is in part due to the fact that the combination of asynchronicity and JavaScript makes it tough to correctly and completely handle errors, so the recommendation is generally to shut down the whole process after capturing information about the error.
This doesn't do a great job of dealing with expected errors, but I think most of those errors are either captured by the framework (e.g. Express error handlers) or put into the Node callback convention. In short, I think there's room here to define some conventions, because the state of the art isn't that artful.

A: Found this great article that talks about this:
http://www.joyent.com/developers/node/design/errors
Too much to paste here, but under "Specific recommendations", items 2 through 5 address this:

*

*Be clear about what your function does.

*Use Error objects (or subclasses) for all errors, and implement the Error contract.

*Use the Error's name property to distinguish errors programmatically.

*Augment the Error object with properties that explain details

*If you pass a lower-level error to your caller, consider wrapping it instead.

And in particular, the article links to this module for wrapping/composing errors:
https://github.com/joyent/node-verror
I'm not sure I'll necessary follow these exact conventions — e.g. I see value in having an application-domain code property — but the principles are very helpful.

A: Edit I'm new to StackOverflow and Node.js. Someone else should answer this question! :-)
If you're coming from Java/C# welcome to JavaScript! I've never seen a Node.js library use instanceof to check for error types but as you've stated is pretty common in static  languages.
With that said, it's typical to just create new errors, and callback with those using NodeJS's style of callbacks (err, response).
I run into error messages from other modules all the time, and it's helpful to know where they came from vs. creating wrapped error messages that may hide where it actually died on me (requiring more on my part to dig around).
An example of creating a function that could handle rest error messages that are strings (or in your case, invalid response):
function myFunction(callback) {
    callRestAPI('http://someApi.com/request', function(errorString, jsonResponse) {
        if (errorString) {
            callback(new Error("something wrong in myFunction! " + errorString));
        } else {
            callback(null, JSON.parse(jsonResponse));
        }
    });
}

In your case the "errorString" check would basically be the response (403 / 503) and you can structure your error message to be sent into new Error( ... ), e.g. new Error('Failed! Got response 403!')
I may have missed your point, maybe someone else can be more thorough.

After a re-read, can you post what module you are wrapping. Is it node-request?

A: I'm pretty new to node as well, so take this with a grain of salt, but I'd go with your #2 option, adding a property.  (This is also suggested here).
This is pretty much your original #2 option.  If the error handlers just log the stack, not the error itself, that's their fault.  :-)    (seriously, not sure how you can do any better)

A: I'll simply attach an httpCode property to the error object. KISS


text:
Q: Как деплоить docker-контейнер без простоя? Что имеем:
2 docker-контейнера: app (node.js) и nginx (reverse-proxy)
Требование:
Иметь минимальный простой сервиса.
Некоторые запросы могут выполняться долгое время. Важно вернуть ответ на запрос, который пришел до деплоя.
Суть проблемы:
При обновлении проекта (docker-compose build && docker-compose up -d) имеем простой 5-10сек. (время запуска node.js в контейнере app).
Как я себе представляю решение:

*

*Использование Green/Blue паттерна. Не смог найти простого решения (без костылей)

*Стек Docker Swarm

Подскажите максимально простой подход к деплою с нулевый простоем (при отсутсвии DevOps'a).
docker-compose.yml

services:

  app:
    build:
      context: .
    restart: unless-stopped
    env_file: .env

  nginx:
    build: ./docker/nginx
    restart: unless-stopped
    depends_on:
      - app
    ports:
      - ${APP_PORT}:80
    volumes:
      - ./static:/var/www:cached

A: Сама идея с тем, чтобы вернуть ответ на запрос, который пришел до начала деплоя является крайне утопической, так как во время деплоя останавливается процесс, который этот запрос обслуживал, а также уничтожается TCP соединение (и сессия TLS), которые этот запрос обслуживали. Восстановить эту парочку не получится.
Можно изобрести жуткие костыли с реверсивным прокси (решает проблему с соединением и сессией) и насочинять транзакционную модель отправки ответа клиенту, но это будет очень усложнено.
Более технологичный ответ - это интернет, детка - запрос всегда может отвалиться просто потому, что данные идут через интернет. Клиенты должны это учитывать и посылать запрос повторно, если с первым не сложилось.


text:
Q: How to exit from spark program how do i exit (by forcing an error message) from Spark program if for example -my join condition fails?
Example-
Employee data-  emp_id, dep_no
1,1001
2,2001
Department data- dep_no,dept_name, location
1001,xyz,NY
3001,pqr,PA
Now if i want to enrich Employee data, i need to do a join with department data. All i want is whenever I don't find a department in dept data (my join will fail), i want to stop the process (error out) with a custom error message in Spark (Scala).
Thanks,
Sid

A: Depending on your use case you may want to use one of the following SparkContext's methods:
def cancelJob(jobId: Int, reason: String): Unit
def cancelJobGroup(groupId: String)
def cancelAllJobs()

A few useful calls:
def applicationId: String // to get current jobId
def setJobGroup(groupId: String, description: String, interruptOnCancel: Boolean = false) // to set groupId for all Spark jobs to be created by the current thread


text:
Q: How do I play random songs from variables and lists with python and pygame? I'm brand new here and I'm trying to make a simple program to play shuffle music in python.
I've tried using pygame.mixer.music and list variables to pick a random song and play it. keep in mind I'm brand new and have no idea what I'm doing.
import pygame
from pygame.locals import *
import random
import pygame.mixer

L = ['Relax.mp3', 'Wanchu_Back.mp3', 'Some_Chords.mp3', 'Green_Gusher.mp3',]
S = random.randint(0, len(L))

pygame.mixer.init()
pygame.mixer.music.set_volume(0.50)
pygame.mixer.music.load(L)
pygame.mixer.music.play(S)

I tried multiple things but I keep getting this message
pygame.error: Couldn't read from RWops

A: pygame.mixer.music.load() expects single filename or single file-object, not list.
pygame.mixer.music.load( filename )

ie.
pygame.mixer.music.load( L[0] )

If you need random filename then you can use
filename = random.choice(L)
pygame.mixer.music.load( filename )

To make sure it is good to use full path to file.


text:
Q: addSublayer not displaying image I'm having trouble getting an image in a CAlayer to display in an imageView. I can get it to work with a CAGradientLayer, but as soon as I change it to a CALayer with an image, nothing seems to work. It doesn't even display part of the image as I would expect it to, if the frame was shifted.
I've made sure the image name is correct and exists. For background: testImageView is the only imageView and covers the entire screen.
let strokeLayer = CALayer()
strokeLayer.contents = UIImage(named: "test.png")
strokeLayer.frame = CGRect(x: 0, y: 0, width: testImageView.frame.width, height: testImageView.frame.height)
testImageView.layer.addSublayer(strokeLayer)

Any help is appreciated!

A: Figured out I was just missing .cgImage at the end of the second line

A: If you want to display a image in CALayer you have to pass as
CGImage.strokeLayer.contents = UIImage(named: "test.png")?.cgImage


text:
Q: Android 3.0 Web Dev initial orientation issue I have noticed an issue with the way Android (so far both 2.2 and 3.0) sets the window.orientation javascript variable. When you initially load a web page everything works fine window.orientation is correctly set to the orientation the device is in (0, 90, -90, 180). The problem arises when you launch a new page via a window.open("newpage") javascript call. When the new page opens the window.orientation value is always 0 no matter what orientation you are in. Below is a sample webpage that can demonstrate this:

<button onclick="window.open('AndroidTesting.html')">Click Me</button>

    <script type="text/javascript">

    orientationEvent = "resize";
    window.addEventListener(orientationEvent, function () {
        setTimeout(displayChange(), 0);
    }, false);

        var myPageWidth = 0;
        var myPageHeight = 0;

        var lastOrientation = "Landscape";

        function displayChange() {

            if ((window.orientation == 90) || (window.orientation == -90)) {
                lastOrientation = "Portrait";
            }
            if ((window.orientation == 0) || (window.orientation == 180)) {
                lastOrientation = "Landscape";
            }

            document.getElementById('storydiv').innerHTML = "In " + lastOrientation + " mode";

        }

    </script>

When you click the button to open the same page in a new tab the orientation is wrong if you are not in the default mode (Android 2.2 the default mode or 0 angle is portrait in Android 3.0 the 0 angle is landscape), but once you rotate to the other mode and then back the orientation works.
Has anyone seen this issue before? Is there a work around, or is it just a problem because I am doing something wrong?
Thanks for the help!

A: I don't know if it's a good approach, but it seems that on Android, screen.width and screen.height depends of the device orientation.
if(android){
    if(screen.width>screen.height){
        return 90;
    }else{
        return 0;
    }
}else{
    return window.orientation;
}

The main problem of this solution is in the os detection.


text:
Q: Lens setter to add element to end of tuple Is there any lens that will help me do the following transformation for a tuple of any length (say up 10-15 elements, at least):
(a, b, c) -> d -> (a, b, c, d)

A: To get a lens you need a getter an setter functions. Unfortunately, there is no way to obtain a fourth element of a triple, (except for Nothing,  or any other unit type). So, you end up with a bunch of setters, which are trivial pattern-matching functions (one for each n-tuple), but not a lens.
Probably, you need a simple list, or some free construction, if you really need non-uniform container?


text:
Q: Conflict between jquery and prototype I am using prototype and jquery, plus I'm creating a slide with another plugin which requires jquery.
Now try jQuery.noConflict (), but still does not work.
var $j = jQuery.noConflict();
$j(document).ready(function(){
    $j('#slides').slides({
        play: 5000,
        pause: 2500,
        hoverPause: true
    });
});

This is the error that gives me the chrome and it does not work the slide.
Uncaught RangeError: Invalid array length
Object.extend.shift         prototype.js:464
d.extend.dequeue            jquery.min.js:16
d.fn.extend.dequeue         jquery.min.js:16
d.extend.each               jquery.min.js:16
d.fn.d.each                 jquery.min.js:16
d.fn.extend.dequeue         jquery.min.js:16
d.extend.speed.e.complete   jquery.min.js:16
d.fx.step                   jquery.min.js:16
g                           jquery.min.js:16
d.extend.tick

A: Is this a problem of variable scope? Did you tried removing the "var" next to j to declare j as global? Hope that helps.


text:
Q: Interoperability between System.Windows.Forms.Application and System.Windows.Application I have to integrate a WPF UI into a .NET 2.0 application.
ObservableCollection needs to be modified in the GUI Dispatcher thread, so I came up with a solution involving InvokeLater()
ObservableCollection<Item> items;
public delegate void AddItemDelegate(Item i);

public void AddItem(Item item)
{
    System.Windows.Application.Current.Dispatcher.BeginInvoke(
        new AddItemsDelegate(i => items.Add(i), item);
}

However, since the project was originally written with .NET 2.0, the main thread uses a System.Windows.Forms.Application, so System.Windows.Application.Current is null.
I can't just replace the current System.Windows.Forms.Application with a System.Windows.Application since my application heavily relies on this API and the two classes are widely incompatibles.
Is there a way to get the current System.Windows.Application ? Or a way to call BeginInvoke() on my System.Windows.Forms.Application ? Or am I deemed to write my own DIY system to delegate edition of the collection from the correct thread ?

A: You should save a reference to SynchronizationContext.Current from the UI thread (perhaps in a static property) and use it instead of the Dispatcher.
In WPF, this will return a DispatcherSynchronizationContext; in WinForms, it will return a WindowsFormsSynchronizationContext.
You can then call Post on the saved SynchronizationContext, which is equivalent to BeginInvoke.


text:
Q: IDOC segment SAP ABAP Hi an IDoc segment z1esui has two fields:

*

*zzdeanqty

*zzceanqty

I want these two fields which tables are fecting in sap ABAP

A: It is custom IDOC type with custom fields. Maybe you can try below alternatives:

*

*Location of this type usage

*Abap code scan


text:
Q: Left vs. left from I was under the impression that "left" and "left from" have very different meanings – for example, we can say:
"The car left the garage an hour ago"
Or
"A pile of rubble is all that's left from the garage after the bombing",
However, it is incorrect to say:
"The car left from the garage".
Am I right or wrong?

A: There's nothing wrong with using "left from" (in the sense you object to). It isn't usual, except in the case where you are specifying more precisely where the journey started, for example:

He left Bradford this morning. Oh, which station did he leave from?


text:
Q: Trying to get an Android WebView to zoom correctly I need to be able to display an image with zoom and scroll capabilities. Since this seems a bit too tedious with ImageView, I'm doing it with a WebView which loads the local image and then displays it. This is my current code:
    WebView image = (WebView)findViewById(R.id.image);
    image.getSettings().setBuiltInZoomControls(true);
    image.getSettings().setLoadWithOverviewMode(true);
    image.getSettings().setUseWideViewPort(true);
    image.setInitialScale(40);
    image.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
    image.loadUrl("file:///android_asset/image.png");

While this loads the image, I can't get it to display only the image. There is always a decent amount of white space below it since setUseWideViewPort(true) makes it go all the way out to scale the width.
Any suggestions on allowing it to only scroll over the image that is loaded? Thanks. I've also tried setDefaultZoom and can't get it to go out far enough.

A: I think using a static percentage 40 within your setInitialScale method is decent, however, it does not take into consideration screen density or size per say.  Currently your 40 means that you are scaled to 40% of the actual size.
Think about when you open up an image only in your web browser on your PC, this is going to essentially respond the same way, put it in the upper left corner.  Yes you can scale it with a WebView, but in this case to make it work for all platforms you are going to have to calculated your scaling factor based upon the screen resolution minus any bounding rectangle (top and bottom in the Android' case) related to the actual width and height of the image.
I suggest you go back to the ImageView!


text:
Q: Does the word "apparent" have ambiguity? I'm learning the word "apparent" which has two apparently different meanings: (1) obvious (2) looks true, but not.
How do people solve the ambiguity here? For example, republicans could describe president-elect Biden as an apparent victory, which may imply that the result could be turned over after recounting. On the other hand, democrats can also say Biden has an apparent victory because of no clue of wide-spreading fraud. Are there any convention to separate the two opposite meanings?

A: One of use of "apparent" (likewise "apparently") is literal - the word means that something is observable. The other use is the opposite - it suggests that some people claim to have observed it, but you have yet to see anything convincing yourself. It could be described as a sarcastic use of the word, and often is said in a sarcastic tone.
When someone is sarcastic, their tone of voice and body language, as well as the context, usually tells you so. Likewise, the use of the words "apparent" and "apparently" are usually shown by their context to be either literal and sincere or not.
As a rule of thumb, if there is no need to say that something is apparent, then it is probably being used to cast doubt as in your example of "the apparent winner". If someone has been declared winner, that would not normally be in doubt. Adding "apparent" suggests that while some people have declared that to be true, others may still doubt it.
When the word is used literally ("apparent" literally means that something is observable) it is usually to clarify something that is already doubted by someone else.


text:
Q: attoparsec: "nested" parsers -- parse a subset of the input with a different parser Well in fact I'm pretty sure I'm using the wrong terminology. Here is the problem I want to solve: a parser for the markdown format, well a subset of it.
My problem is with the blockquote feature. Each line in a blockquote starts with >; otherwise everything is the normal structure in a markdown file.
You can't look at individual lines separately, because you need to separate paragraphs from normal lines, eg
> a
> b

is not the same as
> a
>
> b

and things like that (same if a list is blockquoted you don't want x lists but one list with x elements). A natural and trivial way is to "take off" the > signs, parse the blockquote on its own, ignoring anything around it, wrap it with a BlockQuote type constructor, put that in the outer AST and resume parsing of the original input. It's what pango does if I'm not wrong:
https://hackage.haskell.org/package/pandoc-1.14.0.4/docs/src/Text-Pandoc-Readers-Markdown.html#blockQuote
blockQuote :: MarkdownParser (F Blocks)
blockQuote = do
  raw <- emailBlockQuote
  -- parse the extracted block, which may contain various block elements:
  contents <- parseFromString parseBlocks $ (intercalate "\n" raw) ++ "\n\n"
  return $ B.blockQuote <$> contents

And then:
http://hackage.haskell.org/package/pandoc-1.5.1/docs/src/Text-Pandoc-Shared.html#parseFromString
-- | Parse contents of 'str' using 'parser' and return result.
parseFromString :: GenParser tok st a -> [tok] -> GenParser tok st a
parseFromString parser str = do
  oldPos <- getPosition
  oldInput <- getInput
  setInput str
  result <- parser
  setInput oldInput
  setPosition oldPos
  return result

Now parseFromString looks quite hacky to me and besides that it's also Parsec not attoparsec so I can't use it in my project. I'm not sure how I could take that Text from the blockquote and parse it and return the parsing result so that it "fits" within the current parsing. Seems impossible?
I've been googling on the issue and I think that pipes-parse and conduit can help on that area although I struggle to find examples and what I see appears considerably less nice to look at than "pure" parsec/attoparsec parsers.
Other options to parse blockquotes would be to rewrite the usual parsers but with the > catch... Complicating and duplicating a lot. Parsing blockquotes counting each line separately and writing some messy "merge" function. Or parsing to a first AST that would contain the blockquotes as Text inside a first BlockquoteText type constructor waiting for a transformation where they would be parsed separately, not very elegant but it has the benefit of simplicity, which does count for something.
I would probably go for the latter, but surely there's a better way?

A: I have asked myself the same question. Why is there no standard combinator for nested parsers like how you describe? My default mode is to trust the package author, especially when that author also co-wrote "Real World Haskell". If such an obvious capability is missing, perhaps it is by design and I should look for a better way. However, I've managed to convince myself that such a convenient combinator is mostly harmless. Useful whenever an all-or-nothing type parser is appropriate for the inner parse.
Implementation
import Data.Attoparsec.Text
import qualified Data.Text as T
import Data.Text(Text)
import Control.Applicative

I've divided the required functionality into two parsers. The first, constP, performs an "in place" parse of some given text. It substitutes the constant parser's fail with empty (from Alternative), but otherwise has no other side effects.
constP :: Parser a -> Text -> Parser a
constP p t = case parseOnly p t of
  Left _ -> empty
  Right a -> return a

The second part comes from parseOf, which performs the constant, inner parse based on the result of the outer parse. The empty alternative here allows a failed parse to return without consuming any input.
parseOf :: Parser Text -> Parser a -> Parser a
parseOf ptxt pa = bothParse <|> empty
  where
    bothParse = ptxt >>= constP pa

The block quote markdown can be written in the desired fashion. This implementation requires the resulting block to be totally parsed.
blockQuoteMarkdown :: Parser [[Double]]
blockQuoteMarkdown = parseOf blockQuote ( markdownSurrogate <*
                                          endOfInput
                                        )

Instead of the actual markdown parser, I just implemented a quick parser of space separated doubles. The complication of the parser comes from allowing the last, non-empty line, either end in a new line or not.
markdownSurrogate :: Parser [[Double]]
markdownSurrogate = do
  lns <- many (mdLine <* endOfLine)
  option lns ((lns ++) . pure <$> mdLine1)
  where
    mdLine = sepBy double (satisfy (==' '))
    mdLine1 = sepBy1 double (satisfy (==' '))

These two parsers are responsible for returning the text internal to block quotes.
blockQuote :: Parser Text
blockQuote = T.unlines <$> many blockLine

blockLine :: Parser Text
blockLine = char '>' *> takeTill isEndOfLine <* endOfLine

Finally, a test of the parser.
parseMain :: IO ()
parseMain = do

  putStrLn ""
  doParse "a" markdownSurrogate a
  doParse "_" markdownSurrogate ""
  doParse "b" markdownSurrogate b
  doParse "ab" markdownSurrogate ab
  doParse "a_b" markdownSurrogate a_b
  doParse "badMarkdown x" markdownSurrogate x
  doParse "badMarkdown axb" markdownSurrogate axb

  putStrLn ""
  doParse "BlockQuote ab" blockQuoteMarkdown $ toBlockQuote ab
  doParse "BlockQuote a_b" blockQuoteMarkdown $ toBlockQuote a_b
  doParse "BlockQuote axb" blockQuoteMarkdown $ toBlockQuote axb
  where
    a = "7 3 1"
    b = "4 4 4"
    x = "a b c"

    ab = T.unlines [a,b]
    a_b = T.unlines [a,"",b]
    axb = T.unlines [a,x,b]

    doParse desc p str = do
      print $ T.concat ["Parsing ",desc,": \"",str,"\""]
      let i = parse (p <* endOfInput ) str
      print $ feed i ""

    toBlockQuote = T.unlines
                 . map (T.cons '>')
                 . T.lines

*Main> parseMain

"Parsing a: \"7 3 1\""
Done "" [[7.0,3.0,1.0]]
"Parsing _: \"\""
Done "" []
"Parsing b: \"4 4 4\""
Done "" [[4.0,4.0,4.0]]
"Parsing ab: \"7 3 1\n4 4 4\n\""
Done "" [[7.0,3.0,1.0],[4.0,4.0,4.0]]
"Parsing a_b: \"7 3 1\n\n4 4 4\n\""
Done "" [[7.0,3.0,1.0],[],[4.0,4.0,4.0]]
"Parsing badMarkdown x: \"a b c\""
Fail "a b c" [] "endOfInput"
"Parsing badMarkdown axb: \"7 3 1\na b c\n4 4 4\n\""
Fail "a b c\n4 4 4\n" [] "endOfInput"

"Parsing BlockQuote ab: \">7 3 1\n>4 4 4\n\""
Done "" [[7.0,3.0,1.0],[4.0,4.0,4.0]]
"Parsing BlockQuote a_b: \">7 3 1\n>\n>4 4 4\n\""
Done "" [[7.0,3.0,1.0],[],[4.0,4.0,4.0]]
"Parsing BlockQuote axb: \">7 3 1\n>a b c\n>4 4 4\n\""
Fail ">7 3 1\n>a b c\n>4 4 4\n" [] "Failed reading: empty"

Discussion
The notable difference comes in the semantics of failure. For instance, when parsing axb and blockquoted axb, which are the following two strings, respectively
7 3 1
a b c
4 4 4

and
> 7 3 1
> a b c
> 4 4 4

the markdown parse results in
Fail "a b c\n4 4 4\n" [] "endOfInput"

whereas the quoted results in
Fail ">7 3 1\n>a b c\n>4 4 4\n" [] "Failed reading: empty"

The markdown consumes "7 3 1\n", but this is nowhere reported in the quoted failure. Instead, fail becomes all or nothing.
Likewise, there is no allowance for handling unparsed text in the case of partial success. But I don't see a need for this, given the use case. For example, if a parse looked something like the following
"{ <tok> unhandled }more to parse"

where {} denotes the recognized block quote context, and <tok> is parsed within that inner context. A partial success then would have to lift "unhandled" out of that block quote context and somehow combine it with "more to parse".
I see no general way to do this, but it is allowed through choice of inner parser return type. For instance, by some parser parseOf blockP innP :: Parser (<tok>,Maybe Text). However, if this need arises I would expect that there is a better way to handle the situation than with nested parsers.
There may also be concerns about the loss of attoparsec Partial parsing. That is, the implementation of constP uses parseOnly, which collapses the parse return Fail and Partial into a single Left failure state. In other words, we lose the ability to feed our inner parser with more text as it becomes available. However, note that text to parse is itself the result of an outer parse; it will only be available after enough text has been fed to the outer parse. So this shouldn't be an issue either.


text:
Q: Как сохранить страницу в .pdf? В WF приложении есть браузер (CefSharp). Нужно распечатать страницу сайта в формате .pdf и сохранить его в какую-либо папку на компьютере. Как это сделать?
Например вот эту страницу - https://kad.arbitr.ru/PrintCard/b48828b6-9fce-4eb6-907a-11089efa75d7
Должно получиться что-то такое:

Код:
   private ChromiumWebBrowser ChromeBrowser;

        public Form1()
        {
            InitializeComponent();
            InitializeChromium();
        }

   private void InitializeChromium()
        {
            CefSettings Settings = new CefSettings();
            Cef.Initialize(Settings);
            ChromeBrowser = new ChromiumWebBrowser("https://kad.arbitr.ru/");
            panel1.Controls.Add(ChromeBrowser);
            ChromeBrowser.Dock = DockStyle.Fill;
        }


text:
Q: Are Storyboards a good idea for apps that access the cloud? I'm just about to delve into the world of app development (I'm usually a game developer) in iOS, and I've read the debates of using Storyboards Vs doing it programmatically, and I get for simple apps Storyboards is the way to go, but what about for Apps that access a server? and need to do lots of things dynamically? it seems most Apps these days would be like that, if that's the case are Storyboards  a good idea in that situation?

A: You have to remember that Storyboards are not an alternative to code. They are a tool that can be used along with coded view, nibs, etc...
The real skill comes in using all of these in such a way that takes least effort and gives most maintainability, readability and reliability.
Many of my apps combine several storyboards and a lot of nibs.
Having said that. Nothing that can be done in a storyboard should be anywhere near any cloud code.
The classes that access the cloud should not change whether you are coding views using nibs or using storyboards.
The article that was linked in the other answer is very odd indeed. To dismiss storyboards as things that are only used for prototyping is just plain wrong.
A well structured app (or part of an app) that access some network stuff should be modelled something like...
[Networking stuff]----[View Controller Stuff]----[View Stuff]
It doesn't matter whether the view controller is created in a storyboard, nib or in code. The networking stuff is unchanged.
Also, the article mentions "custom views" as something that you can't do with Storyboards. Again, that's just wrong. My latest app Emojicate was written using a combination of Storyboards (the project has 2 storyboards), nibs (for custom cells etc...) and a couple of coded views (the emoji message view is coded).
It sounds like the guy writing that hasn't really looked into the various tools in any amount of detail.

A: Please take a look at the this article. I think it's summarised really nice and briefly the pros and cons:
http://andrewrauh.com/2013/09/01/storyboardsnibs-vs-doing-everything-with-code-in-ios/


text:
Q: How take url Attachments for all items in list I have an SPList. How I can get attachment URLs for every item in the list?

A: Keep in mind that bit of code might be slow depending on the size of the list:
foreach (SPListItem listItem in list.Items)
{
    var attachmentURLs = GetAttachmentUrls(listItem)
}

private IEnumerable<string> GetAttachmentUrls(SPListItem item)
{
  return from string fileName in item.Attachments
         orderby fileName
         select SPUrlUtility.CombineUrl(item.Attachments.UrlPrefix, fileName);
}

Credit to this post: How do I get the url for attachments on an SPListItem using C#? I just added a foreach loop.

A: You can get list item attachments using REST api as in below code:
var url = url + "/_api/web/lists/getbytitle('ListTitle')/items(1)/AttachmentFiles";

$.ajax({
    url: url,
    accepts: {
        json: "application/json;odata=verbose"
    },
    method: "GET",
    success: onQuerySuccess,
    error: onQueryError
});

function onQuerySuccess(data) {
    if (data) {
        $.each(data.d.results, function () {
            // do something
            this.ServerRelativeUrl;
        });
    }
}

Here "items(1)" is the id of the list item


text:
Q: zooming buttons for image - don't know how For a website I'm making I made a custom map, which is an image. Though, for this website I need to make this image zoomable, and draggle inside a specific 'box'.
I got the Image inside "item" with JS, which makes the image scrollable and draggable. The image i am using is pretty big, since it needs to be zoomed in/out.
code:

var dragItem = document.querySelector("#item");
var container = document.querySelector("#container");

var active = false;
var currentX;
var currentY;
var initialX;
var initialY;
var xOffset = 0;
var yOffset = 0;

container.addEventListener("touchstart", dragStart, false);
container.addEventListener("touchend", dragEnd, false);
container.addEventListener("touchmove", drag, false);

container.addEventListener("mousedown", dragStart, false);
container.addEventListener("mouseup", dragEnd, false);
container.addEventListener("mousemove", drag, false);

function dragStart(e) {
  if (e.type === "touchstart") {
    initialX = e.touches[0].clientX - xOffset;
    initialY = e.touches[0].clientY - yOffset;
  } else {
    initialX = e.clientX - xOffset;
    initialY = e.clientY - yOffset;
  }

  if (e.target === dragItem) {
    active = true;
  }
}

function dragEnd(e) {
  initialX = currentX;
  initialY = currentY;

  active = false;
}

function drag(e) {
  if (active) {

    e.preventDefault();

    if (e.type === "touchmove") {
      currentX = e.touches[0].clientX - initialX;
      currentY = e.touches[0].clientY - initialY;
    } else {
      currentX = e.clientX - initialX;
      currentY = e.clientY - initialY;
    }

    xOffset = currentX;
    yOffset = currentY;

    setTranslate(currentX, currentY, dragItem);
  }
}

function setTranslate(xPos, yPos, el) {
  el.style.transform = "translate3d(" + xPos + "px, " + yPos + "px, 0)";
}
#container {
  width: 9109px;
  height: 5963px;
  background-color: #3ab0c9;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  touch-action: none;
}

#item {
  width: 9109px;
  height: 5963px;
  background-image: url("map.png");
  touch-action: none;
  user-select: none;
}

#item:hover {
  cursor: pointer;
  border-width: 20px;
}

I only need to create zoom buttons, but I don't know how! Can someone help me? I just can't get it working...

A: You should be using a canvas element to draw your image on.
The code below will be a good start for building an HTML5 canvas zoom and pan tool.
Please see HTML5 Canvas Zoom and Pan Image for a working example of the code below.
<canvas></canvas>

    var canvas = document.getElementsByTagName('canvas')[0];
    canvas.width = 800;
canvas.height = 600;

    var gkhead = new Image;

    window.onload = function(){

            var ctx = canvas.getContext('2d');
            trackTransforms(ctx);

    function redraw(){

          // Clear the entire canvas
          var p1 = ctx.transformedPoint(0,0);
          var p2 = ctx.transformedPoint(canvas.width,canvas.height);
          ctx.clearRect(p1.x,p1.y,p2.x-p1.x,p2.y-p1.y);

          ctx.save();
          ctx.setTransform(1,0,0,1,0,0);
          ctx.clearRect(0,0,canvas.width,canvas.height);
          ctx.restore();

          ctx.drawImage(gkhead,0,0);

        }
        redraw();

      var lastX=canvas.width/2, lastY=canvas.height/2;

      var dragStart,dragged;

      canvas.addEventListener('mousedown',function(evt){
          document.body.style.mozUserSelect = document.body.style.webkitUserSelect = document.body.style.userSelect = 'none';
          lastX = evt.offsetX || (evt.pageX - canvas.offsetLeft);
          lastY = evt.offsetY || (evt.pageY - canvas.offsetTop);
          dragStart = ctx.transformedPoint(lastX,lastY);
          dragged = false;
      },false);

      canvas.addEventListener('mousemove',function(evt){
          lastX = evt.offsetX || (evt.pageX - canvas.offsetLeft);
          lastY = evt.offsetY || (evt.pageY - canvas.offsetTop);
          dragged = true;
          if (dragStart){
            var pt = ctx.transformedPoint(lastX,lastY);
            ctx.translate(pt.x-dragStart.x,pt.y-dragStart.y);
            redraw();
                }
      },false);

      canvas.addEventListener('mouseup',function(evt){
          dragStart = null;
          if (!dragged) zoom(evt.shiftKey ? -1 : 1 );
      },false);

      var scaleFactor = 1.1;

      var zoom = function(clicks){
          var pt = ctx.transformedPoint(lastX,lastY);
          ctx.translate(pt.x,pt.y);
          var factor = Math.pow(scaleFactor,clicks);
          ctx.scale(factor,factor);
          ctx.translate(-pt.x,-pt.y);
          redraw();
      }

      var handleScroll = function(evt){
          var delta = evt.wheelDelta ? evt.wheelDelta/40 : evt.detail ? -evt.detail : 0;
          if (delta) zoom(delta);
          return evt.preventDefault() && false;
      };

      canvas.addEventListener('DOMMouseScroll',handleScroll,false);
      canvas.addEventListener('mousewheel',handleScroll,false);
    };

    gkhead.src = 'http://phrogz.net/tmp/gkhead.jpg';

    // Adds ctx.getTransform() - returns an SVGMatrix
    // Adds ctx.transformedPoint(x,y) - returns an SVGPoint
    function trackTransforms(ctx){
      var svg = document.createElementNS("http://www.w3.org/2000/svg",'svg');
      var xform = svg.createSVGMatrix();
      ctx.getTransform = function(){ return xform; };

      var savedTransforms = [];
      var save = ctx.save;
      ctx.save = function(){
          savedTransforms.push(xform.translate(0,0));
          return save.call(ctx);
      };

      var restore = ctx.restore;
      ctx.restore = function(){
        xform = savedTransforms.pop();
        return restore.call(ctx);
              };

      var scale = ctx.scale;
      ctx.scale = function(sx,sy){
        xform = xform.scaleNonUniform(sx,sy);
        return scale.call(ctx,sx,sy);
              };

      var rotate = ctx.rotate;
      ctx.rotate = function(radians){
          xform = xform.rotate(radians*180/Math.PI);
          return rotate.call(ctx,radians);
      };

      var translate = ctx.translate;
      ctx.translate = function(dx,dy){
          xform = xform.translate(dx,dy);
          return translate.call(ctx,dx,dy);
      };

      var transform = ctx.transform;
      ctx.transform = function(a,b,c,d,e,f){
          var m2 = svg.createSVGMatrix();
          m2.a=a; m2.b=b; m2.c=c; m2.d=d; m2.e=e; m2.f=f;
          xform = xform.multiply(m2);
          return transform.call(ctx,a,b,c,d,e,f);
      };

      var setTransform = ctx.setTransform;
      ctx.setTransform = function(a,b,c,d,e,f){
          xform.a = a;
          xform.b = b;
          xform.c = c;
          xform.d = d;
          xform.e = e;
          xform.f = f;
          return setTransform.call(ctx,a,b,c,d,e,f);
      };

      var pt  = svg.createSVGPoint();
      ctx.transformedPoint = function(x,y){
          pt.x=x; pt.y=y;
          return pt.matrixTransform(xform.inverse());
      }
    }


text:
Q: How to set the requested configurations from scratch to run spark on yarn? I am newbie to running spark on yarn and I have tried it on an HPC cluster. Since I could not figure out how to set the configurations properly, I can't connect to yarn successfully and my logs are as below:
Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
16/11/22 18:35:59 INFO SparkContext: Running Spark version 1.4.1
16/11/22 18:36:00 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
16/11/22 18:36:00 WARN SparkConf: In Spark 1.0 and later spark.local.dir will be overridden by the value set by the cluster manager (via SPARK_LOCAL_DIRS in mesos/standalone and LOCAL_DIRS in YARN).
16/11/22 18:36:00 INFO SecurityManager: Changing view acls to:
16/11/22 18:36:00 INFO SecurityManager: Changing modify acls to:
16/11/22 18:36:00 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users with view permissions: Set( ); users with modify permissions: Set( )
16/11/22 18:36:01 INFO Slf4jLogger: Slf4jLogger started
16/11/22 18:36:01 INFO Remoting: Starting remoting
16/11/22 18:36:01 INFO Remoting: Remoting started; listening on addresses :[akka.tcp://sparkDriver@172.23.9.106:35138]
16/11/22 18:36:01 INFO Utils: Successfully started service 'sparkDriver' on port 35138.
16/11/22 18:36:01 INFO SparkEnv: Registering MapOutputTracker
16/11/22 18:36:01 INFO SparkEnv: Registering BlockManagerMaster
16/11/22 18:36:01 INFO DiskBlockManager: Created local directory at /local/tmp/spark-c335cd9f-7719-4ffd-942c-2bbcc543e3c8/blockmgr-2057f8aa-e074-4910-a1fa-3fc9c73ad1f1
16/11/22 18:36:01 INFO MemoryStore: MemoryStore started with capacity 16.6 GB
16/11/22 18:36:01 INFO HttpFileServer: HTTP File server directory is /local/tmp/spark-c335cd9f-7719-4ffd-942c-2bbcc543e3c8/httpd-63876231-4681-4e75-bfd9-f46edf02087c
16/11/22 18:36:01 INFO HttpServer: Starting HTTP Server
16/11/22 18:36:01 INFO Utils: Successfully started service 'HTTP file server' on port 46754.
16/11/22 18:36:01 INFO SparkEnv: Registering OutputCommitCoordinator
16/11/22 18:36:01 INFO Utils: Successfully started service 'SparkUI' on port 4040.
16/11/22 18:36:01 INFO SparkUI: Started SparkUI at http://172.23.9.106:4040
16/11/22 18:36:02 INFO SparkContext: Added JAR file:/hard-mounts/user/311/ /cosine-lsh.jar at http://172.23.9.106:46754/jars/cosine-lsh.jar with timestamp 1479836162928
16/11/22 18:36:03 INFO RMProxy: Connecting to ResourceManager at /127.0.0.1:8032
16/11/22 18:36:04 INFO Client: Retrying connect to server: localhost/127.0.0.1:8032. Already tried 0 time(s); retry policy is RetryUpToMaximumCountWithFixedSleep(maxRetries=10, sleepTime=1000 MILLISECONDS)
16/11/22 18:36:05 INFO Client: Retrying connect to server: localhost/127.0.0.1:8032. Already tried 1 time(s); retry policy is RetryUpToMaximumCountWithFixedSleep(maxRetries=10, sleepTime=1000 MILLISECONDS)
16/11/22 18:36:06 INFO Client: Retrying connect to server: localhost/127.0.0.1:8032. Already tried 2 time(s); retry policy is RetryUpToMaximumCountWithFixedSleep(maxRetries=10, sleepTime=1000 MILLISECONDS)
16/11/22 18:36:07 INFO Client: Retrying connect to server: localhost/127.0.0.1:8032. Already tried 3 time(s); retry policy is RetryUpToMaximumCountWithFixedSleep(maxRetries=10, sleepTime=1000 MILLISECONDS)
16/11/22 18:36:08 INFO Client: Retrying connect to server: localhost/127.0.0.1:8032. Already tried 4 time(s); retry policy is RetryUpToMaximumCountWithFixedSleep(maxRetries=10, sleepTime=1000 MILLISECONDS)
16/11/22 18:36:09 INFO Client: Retrying connect to server: localhost/127.0.0.1:8032. Already tried 5 time(s); retry policy is RetryUpToMaximumCountWithFixedSleep(maxRetries=10, sleepTime=1000 MILLISECONDS)
16/11/22 18:36:10 INFO Client: Retrying connect to server: localhost/127.0.0.1:8032. Already tried 6 time(s); retry policy is RetryUpToMaximumCountWithFixedSleep(maxRetries=10, sleepTime=1000 MILLISECONDS)
16/11/22 18:36:11 INFO Client: Retrying connect to server: localhost/127.0.0.1:8032. Already tried 7 time(s); retry policy is RetryUpToMaximumCountWithFixedSleep(maxRetries=10, sleepTime=1000 MILLISECONDS)
16/11/22 18:36:12 INFO Client: Retrying connect to server: localhost/127.0.0.1:8032. Already tried 8 time(s); retry policy is RetryUpToMaximumCountWithFixedSleep(maxRetries=10, sleepTime=1000 MILLISECONDS)

I use spark 1.4.1 and I have downloaded Hadoop 2.6 to my local folder in the cluster. Here is my spark configuration lines in my app code:
val conf = new SparkConf()
      .setAppName("LSH-Cosine")
      .setMaster("yarn-client") //local[*]
      .set("spark.driver.maxResultSize", "0")
      .set("spark.local.dir", "/local/tmp");

And I run my code through the jar file via the bash file as below:
#!/bin/bash -l

#PBS -l walltime=00:45:00

module load Spark/1.4.1
module load Hadoop

cd $PBS_O_WORKDIR

export HADOOP_CONF_DIR=/vsc-hard-mounts/user/311/31182/hadoop-2.6.0-src/hadoop-yarn-project/hadoop-yarn/conf

spark-submit \
  --class com.soundcloud.lsh.MainCerebro \
  --master yarn-client \
  --num-executors 50 \
  --driver-memory 32g \
  --executor-memory 32g \
  --executor-cores 2 \
  cosine-lsh.jar

I tried to designate HADOOP_CONF_DIR to the conf folder found in hadoop 2.6 which I have downloaded to my local folder. In addition, I changed yarn-site.xml as
<configuration>

<property>
    <name>yarn.resourcemanager.hostname</name>
    <value>127.0.0.1:8032</value>
</property>

</configuration>

I have wrapped up all the trials above from the related stackoverflow posts. Since many of them have no a clear answer, I want to post this question.
Thanks in advance.


text:
Q: What is wrong with my java method code? - Stacks I have spent the last few hours creating a method that will take null elements from stack s1, and place them into s2. The class should then print the stacks. The method is as follows
import net.datastructures.ArrayStack;
import net.datastructures.Stack;
import javax.imageio.IIOException;

public class Stacks {
    public static <E> void compress(Stack<E> s1, Stack<E> s2) {
        int counter = 0;
        while (!s1.isEmpty()) {
            s1.peek();
            if (s1.peek() == null) {
                s1.pop();
            } else if (s1.peek() == !null) {
                s1.pop();
                s2.push();
                counter++;
            }
            for (counter=10;counter>s1.size(); counter--){
            }
            s2.pop();
            s1.push();
        }
    }

    public static void main(String[] args) {
        // test method compress
        Stack<Integer> S1 = new ArrayStack<Integer>(10);
        S1.push(2);
        S1.push(null);
        S1.push(null);
        S1.push(4);
        S1.push(6);
        S1.push(null);
        Stack<Integer> s2 = new ArrayStack<Integer>(10);
        s2.push(7);
        s2.push(9);
        System.out.println("stack S1: " + S1);
        // prints: "stack S: [2, null, null, 4, 6, null]"
        System.out.println("stack s2: " + s2);
        // prints: "stack X: [7, 9]"
        compress(S1, s2);
        System.out.println("stack S1: " + S1);
        // should print: "stack S: [2, 4, 6]"
        System.out.println("stack s2: " + s2);
        // should print: "stack X: [7, 9]"
    }
}

Eclipse is giving me errors for both peek() and push() methods; it allows the pop() method. It was my understanding that these methods are inherited? Any help is much appreciated!

A: else if (s1.peek() == !null)

That is not correct.  Use this:
else if (s1.peek() != null)

A: This:
    if (s1.peek() == null) {
        s1.pop();

    } else if (s1.top() == !null) {
        s1.pop();
        s2.push();

        counter++;
    }

Should be:
    if (s1.top() == null) {
        s1.pop();

    } else {
        s2.push(s1.pop());

        counter++;
    }

You don't need to double check s1.peek()is not null. Plus, !null is not the correct syntax.
I edited my answer to use top() instead of peek() and to pop() s1 into s2.

A: In addition to the error with the comparison, you have a few more syntax errors:
push() requires a parameter: what are you pushing onto the stack? Even if it's null it'll still need to be s1.push(null). If it's what you're pop()-ing, you need to assign the result of pop() to something -- right now it's being lost to the ether.
The object you're using (net.datastructures.Stack) doesn't have a peek() method; instead it has top() which performs the same function.


text:
Q: express config from json stranges Good time to all. Recently started learn javascript and experiment with node server coding and now really can't understand what is happening..
I have classic app.js
...
var view = require('./routes/view');
...
app.use('/mix', view);
...

And this is my view.js
var express = require('express');
var router = express.Router();
var moment = require("moment");

var DB = require('../modules/mysql')

/*  */
router.get('/:mixId', (req, res, next) => {

  /** set defaults */
  let config = require('../cfg/hbs.json'); // config load (see example below)
  var page = "pages/viewFail",
    alert = {};

  /** select info about mix */
  DB.query('SELECT startTS, targetAdr, received FROM mixes m WHERE name=?', [req.params.mixId], (err, results) => {

    /** if not exist */
    if (results.length === 0) {
      alert = { // danger alert
        "color": "danger",
        "text": "this mix does not exist"
      }
    }
    /** exist */
    else {

      var mix = {
        "adr": results[0].targetAdr,
        "received": results[0].received,
        /** calculate endin in minudes */
        "endin": parseInt(120 - moment.duration(moment().diff(moment(results[0].startTS))).asMinutes()),
      }

      /** check end time and ballance. if no transactions and time ends - exit */
      if (mix.endin <= 0 && mix.received <= 0) {
        alert = {
          "color": "danger",
          "text": "this mix does not exist"
        }
      } else {

        if (mix.received == 0) {
          page = 'pages/viewStart'
        } else {
          config.meta.js.push("/js/viewEnd.js"); /** add common page js {} */
          page = 'pages/viewEnd'

          console.log(config.meta)
          console.log("\n------------\n")

        }
      }
    }

    /** send response */
    res.render(page, {
      layout: 'layout',
      meta: config.meta,
      alert: alert,
      mix: mix,
    });
  });
});

module.exports = router;

Here is my config file:
{
  "meta": {
    "title": "test partials",
    "css": [
      "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css",
      "/css/c.css"
    ],
    "js": [
      "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js",
      "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js",
      "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"
    ],
    "tmp": [
      "https://code.jquery.com/jquery-3.2.1.slim.min.js"
    ]

  }
}

And the problem is: when I restart page meta.js add time after time and result is:
{ title: 'test partials',
  css:
   [ 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css',
     '/css/c.css' ],
  js:
   [ 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js',
     'https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js',
     'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js',
     '/js/viewEnd.js',  // ??????
     '/js/viewEnd.js',  // ??????
     '/js/viewEnd.js' ],// ??????
  tmp: [ 'https://code.jquery.com/jquery-3.2.1.slim.min.js' ] }

So what am I doing wrong?

A: Consider the following:
let config1 = require('../cfg/hbs.json');
let config2 = require('../cfg/hbs.json');

console.log(config1 === config2);

This will log the value true, meaning that config1 and config2 refer to the exact same object.
The reason for this is that require performs caching. It will only read the file the first time. Subsequent calls to require the same file will just return the cached object.
This is what's happening in your code. Each time the route is called it's pulling in the same config object and then pushing an extra entry into the same array.
There are several ways to resolve this. One simple solution is to take a deep copy of the object by JSON encoding it:
let config = JSON.parse(JSON.stringify(require('../cfg/hbs.json')));


text:
Q: explanation of a triple integral $\iiint _{x^2+y^2+z^2I'm trying to figure out how the my book solve this exercise:
$$\iiint _{x^2+y^2+z^2<R^2}\left|xz\right|y^2dxdydz\:$$
BOOK SOLUTION:
$$\iiint _{x^2+y^2+z^2<R^2}\left|xz\right|y^2dxdydz\: = 8\iiint _Sxzy^2dxdydz\:$$
with:
$$S=\{(x,y,z):x^2+y^2+z^2<R^2, x\ge0, y\ge0, z\ge0\}$$
We transform in spherical coordinates:
$$S=\{(\rho,\phi,\theta): \rho \in [0,R], \phi\in[0,\frac{\pi}{2}], \theta \in [0,\frac{\pi}{2}]\}, dxdydz=\rho^2\sin\phi d\phi d\theta d\rho$$
then, the exercise continues with the triple integral solution after the transformation (which is not difficult).
MY DOUBT
i will report below, what I am not clear (outlined in red)
$$\iiint _{x^2+y^2+z^2<R^2}\left|xz\right|y^2dxdydz\: = \color{red}{8\iiint_Cxzy^2dxdydz\:}$$
I just can not understand how these two integrals can be equal.
Then:
$$S=\{(\rho,\phi,\theta): \rho \in [0,R], \color{red}{\phi\in[0,\frac{\pi}{2}]}, \color{red}{\theta \in [0,\frac{\pi}{2}]}\}, dxdydz=\rho^2\sin\phi d\phi d\theta d\rho$$
why in that range?
Thanks

A: Let
$$
\begin{aligned}
D_1&=\{(x,y,z)\in\mathbb R^3~|~x^2+y^2+z^2\leq R^2\},\\
D_2&=\{(x,y,z)\in\mathbb R^3~|~x^2+y^2+z^2\leq R^2,\ x\geq 0\}\\
D_3&=\{(x,y,z)\in\mathbb R^3~|~x^2+y^2+z^2\leq R^2,\ x\geq 0,\ y\geq 0\}\\
D_4&=\{(x,y,z)\in\mathbb R^3~|~x^2+y^2+z^2\leq R^2,\ x\geq 0,\ y\geq 0,\ z\geq 0\}.
\end{aligned}
$$
Then, since your function $f(x,y,z)=|xz|y^2$ is even in all three variables,
$$
\begin{aligned}
\iiint_{D_1}f(x,y,z)\,dx\,dy\,dz
&=
2\iiint_{D_2}f(x,y,z)\,dx\,dy\,dz\\
&=
4\iiint_{D_3}f(x,y,z)\,dx\,dy\,dz\\
&=
8\iiint_{D_4}f(x,y,z)\,dx\,dy\,dz
\end{aligned}
$$
Moreover, in $D_4$ you have $f(x,y,z)=xy^2z$.
For the second question, in spherical coordinates the first octant satisfies the bound for the angles, i.e. $0\leq\phi\leq\pi/2$ and $0\leq\theta\leq\pi/2$. Draw a picture and make sure you understand that.


text:
Q: Can't get 100% Height to work on Wrapper. html, body and outer wrapper are at 100% need visible overflow Solved : had to float the #main div, plus quite a lot of other major changes to the structure. But the coup-de-gras was the float.
The site in question can be viewed at http://thepremium.ca/amodestblog
Problem is I need the #main div to have a visible overflow in order to show the date divs that are -positioned to the left, outside the visible div.
If I set the overflow (which is currently hidden) I lose my background color because the div shrinks down to about 20px in height. 100% doesn't work.
I traced it back to a problem with the #wrapper div which is also not taking to the 100% height which it is assigned, which isn't making a lot of sense because the #wrapper-background div it is inside is adopting the full height of the browser, along with  and
Hopefully someone can come up with a solution to this one. Please view the source on the site itself, I've got too many different css files (using wordpress thematic theme) to put all the different css in here.

A: It's a bit of a hack, but you could change the ribbon-front div to fixed position and then use left and top to position the div where you want it.
.dateRibbon .ribbon-front {
  background-color: #84C036;
  height: 55px;
  position: fixed;
  width: 71px;
  z-index: 2;
  top: 50;   // You'd have to work out what the exact values should be.
  left: 70;
}

Otherwise I'd restructure the page to ensure the date ribbon was not a child of the #main div.


text:
Q: How to find the joint probability function where one of your parameters is a random variable? Here is the question that I am trying to do.
The number of defects per yard $Y$ for a certain fabric is known to have a Poisson distribution with parameter $x\,$ (i.e. $f(Y|X = x)$ has a Poisson distribution with parameter x$)$. However, $x$ itself is a random variable with probability density function given by
$f(x) = e^{-x},\ x\ge 0$
and $\,f(x)$ is equal to $0$ everywhere else.
Find the joint probability function for $X$ and $Y$.
So what I was thinking you know that you want a function of $f(x,y)$. Since they tell you that it follows a Poisson distribution you would need a $\lambda$ and a $k$ value where the $\lambda$ is your average number of events per interval and $k$ is the number of events that occur. The way the question is worded $\lambda$=y and $k$=$x$.
$$P(k) = \frac{\lambda^{k}e^{-\lambda}}{k!}=\frac{y^{x}e^{-y}}{x!}=f(x,y)$$
So what I think is that $f(x,y)$ is the joint probability function since $x$ and $y$ are variables and not constants. What I was wondering is whether this is right or not? I'm a bit unsure because I'm not why they gave us the information that $f(Y|X = x)$. Did I have the correct approach or not? If not can I know what is wrong with my answer and how to correctly do this problem?

A: Recall that a conditional probability mass/density function can be written as follows:
$ f_Y(y|X=x) = \frac{f_{Y,X}(y,x)}{f_X(x)} $
You can solve for $ f_{Y,X}(y,x) $ to get:
$ f_{Y,X}(y,x) = f_Y(y|X=x) \times f_X(x) = \frac{e^{-x}y^x}{y!} \times e^{-x} = \frac{e^{-2x}y^x}{y!} $


text:
Q: Pandas "replace" method not working to replace a dot (.) character I wrote 2 very similar codes to replace characters (?, .) to nan values in Python. Unfortunately one of them worked perfectly but other did not.  Here are the codes
df_train['SES'].replace('?',np.nan, inplace= True)

That worked perfectly, but
df_train['CLUSTER_CODE'].replace('.', np.nan, inplace= True)

this one is very similar code to above, but did not work. Any advice please as i'm very new to python and trying to learn.


text:
Q: java.lang.RuntimeException on Google console I have an application ANDROID on the Play Store.
On Google Play console, I access to the ANR report and to the errors report.
Until now I had no anomalies. However, I recently discovered that when I set the filters to "installation from any source", I had 6 error reports.
First does it mean that my app is available "illegally"?
Second, I don't understand the error report. Can someone help me on the subject?
java.lang.RuntimeException:

at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11 (Unknown Source)
at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1589)
at android.os.Handler.dispatchMessage (Handler.java:106)
at android.os.Looper.loop (Looper.java:164)
at android.app.ActivityThread.main (ActivityThread.java:6494)
at java.lang.reflect.Method.invoke (Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:807)

I think the error occurs before entering my application but I'm not sure


text: Q: Why use Link component in React-Router instead of just anchor tag? I am new to react-router and I understand that the Link component will be translated to Anchor tag. So my question, What is the real difference between the two?


text:
Q: Can't update from OSX 10.9.5 to OSX Yosemite 10.10 I bought my 13 inch non-retina MacBook Pro on December 2013. It's got...
4 GB of 1600 MHz DDR3 SDRAM
500 GB 5400-rpm hard drive
To update to OSX Yosemite 10.10 takes 5.64 GB. So does it mean I CAN'T update from 10.9.5 to 10.10 OSX Yosemite with my MacBook Pro?

A: I think you are misreading the numbers.
Yosemite takes a little more than 5 Gig.
Your Hard drive is 500 Gig. Even if you have used (consumed) lots of it, if you still have about 10 Gig of free space you can upgrade to Yosemite.
To look how much space you have on your Hard drive:
Click on the top left Apple symbol and then on the About this Mac.
In the new window click on "More Info", now click on the Storage Tab.
It looks like this on my Mac, showing I have 108 Gig free.

The other storage is called RAM (that is not your hard disk). Yosemite needs minimum 2 Gig and you have 4 Gig, so no problem there.

A: You have 4GB of RAM. RAM however in this case doesn't impact whether or not you can upgrade an OS. That 5G of space is hard drive space, not RAM. Since you have 100 times that on your hard drive, you should have plenty of room.

A: If you are trying to update and it is not updating, you can always create a bootable USB drive with the installer of OS X 10.10.x, boot your system using alt key, choose to boot from the previously made USB drive and just say upgrade or open Disk Utilities, erase your drive and reinstall a fresh copy of your operating system.
But be sure to backup all your data before proceeding.
To create a bootable USB drive for your installer just search for creating bootable usb for Yosemite installer.


text:
Q: weird IF statement error " Conversion from string "FAIL" to type 'Long' is not valid." I'm basically running through rows in a table. I'm checking each row to see if at least 1 of the columns im interested is = "pass" and that the rest = either "pass" or "N/A".
But im getting an error:

"An exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll but was not handled in user code

Additional information: Conversion from string "FAIL" to type 'Long' is not valid."
The statuses can either be "PASS", "FAIL", OR "N/A" in the DB is you're wondering where the FAIL came from.
Here's the code:
Private Function HasAuditPassed(activeLotId As String) As Boolean
    Dim sql = String.Format("SELECT STEPID, CAVITYPAIRASTATUS,CAVITYPAIRBSTATUS,CAVITYPAIRCSTATUS,CAVITYPAIRDSTATUS FROM " & _
                "TB_BL_AMMSSTEPSTATUS WHERE AUDITLOT = '{0}'", activeLotId)

    Dim dynaset = DB.CreateDynaset(sql, DBWrapper.DynasetOptions.ORADYN_READONLY)

    Do Until dynaset.EOF
        Dim cavityPairAStatus = dynaset.GetFieldData(Of String)("CAVITYPAIRASTATUS")
        Dim cavityPairBStatus = dynaset.GetFieldData(Of String)("CAVITYPAIRBSTATUS")
        Dim cavityPairCStatus = dynaset.GetFieldData(Of String)("CAVITYPAIRCSTATUS")
        Dim cavityPairDStatus = dynaset.GetFieldData(Of String)("CAVITYPAIRDSTATUS")

        If (cavityPairAStatus Or cavityPairBStatus Or cavityPairCStatus Or cavityPairDStatus) = "PASS" And
            (cavityPairAStatus And cavityPairBStatus And cavityPairCStatus And cavityPairDStatus) = ("PASS" Or "N/A") Then
            Return True
        End If
    Loop
    Return False
End Function

A: Sadly, you can't do if statements that way. You have to write the entire statement out because VB .Net does not handle string comparison that way. So a statement that would be the equivalent and work would be much longer and look like this:
If (cavityPairAStatus = "PASS" OrElse cavityPairBStatus = "PASS" OrElse
    cavityPairCStatus = "PASS" OrElse cavityPairDStatus = "PASS")
    And (cavityPairAStatus = "PASS" OrElse cavityPairAStatus = "N/A" AndAlso
    cavityPairBStatus = "PASS" OrElse cavityPairBStatus = "N/A" AndAlso
    cavityPairCStatus = "PASS" OrElse cavityPairCStatus = "N/A" AndAlso
    cavityPairDStatus = "PASS" OrElse cavityPairDStatus = "N/A") Then
        Return True
End If

A few more elegant solutions with creating lists are below, and can be used to help out readability some if you have to write statements like this repeatedly.

A: There are a couple of issues here. You can't write a If stytement in this style and you can't use binary operators (And and Or) with String.
Your If statement should be something like this:
If (cavityPairAStatus = "PASS" OrElse cavityPairBStatus = "PASS" OrElse  …

If you want something a little more elegant you may consider something like this:
Dim values = {cavityPairAStatus, cavityPairBStatus, cavityPairCStatus, cavityPairDStatus}
If values.Any(Function(v) v.Equals("PASS")) AndAlso values.All(Function(v) v.Equals("PASS") OrElse v.Equals("N/A")) Then
   …
End If

A: The way IF statement you have used is incorrect.
To compare so many conditions you need to write them separately.
Instead of using IF condition here I would suggest you to use a list.
Here's the sample code
 Dim cavityPairStatus As New List(Of String)
    cavityPairStatus.Add(dynaset.GetFieldData(Of String)("CAVITYPAIRASTATUS"))
    cavityPairStatus.Add(dynaset.GetFieldData(Of String)("CAVITYPAIRBSTATUS"))
    cavityPairStatus.Add(dynaset.GetFieldData(Of String)("CAVITYPAIRCSTATUS"))
    cavityPairStatus.Add(dynaset.GetFieldData(Of String)("CAVITYPAIRDSTATUS"))
    If cavityPairStatus.Contains("PASS") OrElse cavityPairStatus.Contains("N/A") Then
        Return True
    End If


text:
Q: Why do I get 'data2' has not been initiliazed error here? It makes no sense at this code. I am trying to grab some strings from the ALREADY INITIALIZED from the futurebuilder data, but can't do so. It gives me the data2 has not been initialized error. Here is data and data2, they are almost similiar, data works fine but data2 doesn't. Why is that?
late List<Album> data;
late List<String> data2;

Here is my code:
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

const List<String> list = <String>['One', 'Two', 'Three', 'Four'];
Future<List<Album>> fetchAlbum() async {
  final response = await http.get(
      Uri.parse('https://my-json-server.typicode.com/fluttirci/testJson/db'));

  print(response);
  Map<String, dynamic> userMap = jsonDecode(response.body);
  if (response.statusCode == 200) {
    return (userMap['employees'] as List)
        .map((e) => Album.fromJson(e))
        .toList();
  } else {
    throw Exception('Failed to load album');
  }
}

class Album {
  final int userId;
  final int id;
  final String title;

  Album(this.userId, this.id, this.title);

  Album.fromJson(Map<String, dynamic> json)
      : userId = json['userId'],
        id = json['id'],
        title = json['title'];

  Map<String, dynamic> toJson() => {
        'userId': userId,
        'id': id,
        'title': title,
      };
}

void main() => runApp(const MyApp());

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late Future<Album> futureAlbum;
  late Future<List<Album>> user;
  late List<Album> data;
  late List<String> data2;
  @override
  void initState() {
    super.initState();
    user = fetchAlbum();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fetch Data Example',
      theme: ThemeData(
        brightness: Brightness.dark,
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Fetch Data Example'),
        ),
        body: Column(children: <Widget>[
          Expanded(
            child: const DropdownButtonExample(),
          ),
          Expanded(
            child: FutureBuilder<List<Album>>(
              future: user,
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  data = snapshot.data ?? [];
                  print('${data[4].title}');

                  return ListView.builder(
                    itemBuilder: (context, index) {
                      data2[index] = data[index].title;
                      return Column(children: [
                        Text(data[index].title ?? ""),
                      ]);
                    },
                    itemCount: data.length,
                  );
                } else if (snapshot.hasError) {
                  return Text('${snapshot.error}');
                }
                return Center(
                  child: const CircularProgressIndicator(),
                );
              },
            ),
          )
        ]),
      ),
    );
  }
}

class DropdownButtonApp extends StatelessWidget {
  const DropdownButtonApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('DropdownButton Sample')),
        body: const Center(
          child: DropdownButtonExample(),
        ),
      ),
    );
  }
}

class DropdownButtonExample extends StatefulWidget {
  const DropdownButtonExample({super.key});

  @override
  State<DropdownButtonExample> createState() => _DropdownButtonExampleState();
}

class _DropdownButtonExampleState extends State<DropdownButtonExample> {
  String dropdownValue = list.first;

  @override
  Widget build(BuildContext context) {
    return DropdownButton<String>(
      value: dropdownValue,
      icon: const Icon(Icons.arrow_downward),
      elevation: 16,
      style: const TextStyle(color: Colors.deepPurple),
      underline: Container(
        height: 2,
        color: Colors.deepPurpleAccent,
      ),
      onChanged: (String? value) {
        // This is called when the user selects an item.
        setState(() {
          dropdownValue = value!;
        });
      },
      items: list.map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
    );
  }
}

A: For RangeError issue, your data2 is empty so you can search for index and pass your value to it, just add your string to it normally it will put that in right index, so change your listview's builder to this:
return ListView.builder(
    itemBuilder: (context, index) {
      data2.add(data[index].title);//<--- change this
      return Column(children: [
        Text(data[index].title ?? ""),
      ]);
    },
    itemCount: data.length,
  );


text:
Q: generate forecast using glm probit model I am trying to generate a simple one-period forecast for a glm (probit regression) model, using the forecast command. But when running the below code I get the following message: Error in as.data.frame(newdata) : argument "newdata" is missing, with no default
#generate dataset with unknown value for last period dependent variable
data.set <- data.frame(date= seq(as.Date('2015-01-01'), by = 'days' , length = 100),
                       replicate(100, sample(0:1,1)), runif(1e2),runif(1e2),runif(1e2))
colnames(data.set) <- c("date", "dv", "iv1", "iv2", "iv3")
data.set.ts <- xts(data.set[-1], order.by=data.set$date)
rm(data.set)
data.set.ts$dv[100] <- NA

#run glm probit model
PRmodel <- glm(dv ~ iv1 + iv2 + iv3, data = data.set.ts[-nrow(data.set.ts),],
               family = binomial(link = "probit"))

#generate forecast for last period dv
iv_input <- xts(data.set.ts[, which(colnames(data.set.ts) %in% c("iv1" , "iv2" , "iv3"))],
                order.by = index(data.set.ts))
start.date <- index(data.set.ts)[length(index(data.set.ts))]
fcastFn_output <- forecast(PRmodel, xreg=window(iv_input, start = start.date))

I have also tried using the predict command but R won't seem to generate a forecasted value for an observation if the actual is missing.

A: Code that generates a forecast should be along these lines
data.set <- data.frame(date= seq(as.Date('2015-01-01'), by = 'days' , length = 100),
                       replicate(100, sample(0:1,1)), runif(1e2),runif(1e2),runif(1e2))
colnames(data.set) <- c("date", "dv", "iv1", "iv2", "iv3")
# Load the required package.
require(xts)
data.set.ts <- xts(data.set[-1], order.by=data.set$date)
rm(data.set)
data.set.ts$dv[100] <- NA

#run glm probit model
PRmodel <- glm(dv ~ iv1 + iv2 + iv3, data = data.set.ts[-nrow(data.set.ts),],
               family = binomial(link = "probit"))

#generate forecast for last period dv
iv_input <- xts(data.set.ts[, which(colnames(data.set.ts) %in% c("iv1" , "iv2" , "iv3"))],
                order.by = index(data.set.ts))
start.date <- index(data.set.ts)[length(index(data.set.ts))]
# Generate the forecast for 2015-04-10.
fcastFn_output <- predict(PRmodel, window(iv_input, start = start.date))
# Create a time series with all the forecasts.
fcastFn_all <- c(predict(PRmodel), fcastFn_output)

Hope this helps


text:
Q: fastest way to make an element in a list as the first element I have  list and I want a short and fast way to make one of its element as the first.
I have in mind to use the code below to select the 10th element and make it first. But  looking for a better soln
tempList.Insert(0, tempList[10]);
tempList.RemoveAt(11);

A: if you don't mind the ordering of the rest, you actually could swap the two items at position 0 and 10, believe it's better than doing insertion and deletion:
var other = tempList[0];
tempList[0]=tempList[10];
tempList[10] = other;

and you can even make this an extension of List for ease of use, something like:
 public static void Swap<T>(this List<T> list, int oldIndex, int newIndex)
 {
      // place the swap code here
 }

A: There are some special cases when you could get better performance (for the sake of simplicity, I'm assuming that the value is always inserted before the position where it was taken from):
class Program
{
    const int Loops = 10000;
    const int TakeLoops = 10;
    const int ItemsCount = 100000;
    const int Multiplier = 500;
    const int InsertAt = 0;

    static void Main(string[] args)
    {
        var tempList = new List<int>();
        var tempDict = new Dictionary<int, int>();
        for (int i = 0; i < ItemsCount; i++)
        {
            tempList.Add(i);
            tempDict.Add(i, i);
        }

        var limit = 0;
        Stopwatch
            sG = new Stopwatch(),
            s1 = new Stopwatch(),
            s2 = new Stopwatch();
        TimeSpan
            t1 = new TimeSpan(),
            t2 = new TimeSpan();

        for (int k = 0; k < TakeLoops; k++)
        {
            var takeFrom = k * Multiplier + InsertAt;
            s1.Restart();
            for (int i = 0; i < Loops; i++)
            {
                tempList.Insert(InsertAt, tempList[takeFrom]);
                tempList.RemoveAt(takeFrom + 1);
            }
            s1.Stop();
            t1 += s1.Elapsed;
            s2.Restart();
            for (int i = 0; i < Loops; i++)
            {
                var e = tempDict[takeFrom];
                for (int j = takeFrom - InsertAt; j > InsertAt; j--)
                {
                    tempDict[InsertAt + j] = tempDict[InsertAt + j - 1];
                }
                tempDict[InsertAt] = e;
            }
            s2.Stop();
            t2 += s2.Elapsed;
            if (s2.Elapsed > s1.Elapsed || limit == 0)
                limit = takeFrom;
        }

        sG.Start();
        for (int k = 0; k < TakeLoops; k++)
        {
            var takeFrom = k * Multiplier + InsertAt;
            if (takeFrom >= limit)
            {
                for (int i = 0; i < Loops; i++)
                {
                    tempList.Insert(InsertAt, tempList[takeFrom]);
                    tempList.RemoveAt(takeFrom + 1);
                }
            }
            else
            {
                for (int i = 0; i < Loops; i++)
                {
                    var e = tempDict[takeFrom];
                    for (int j = takeFrom - InsertAt; j > InsertAt; j--)
                    {
                        tempDict[InsertAt + j] = tempDict[InsertAt + j - 1];
                    }
                    tempDict[InsertAt] = e;
                }
            }
        }
        sG.Stop();
        Console.WriteLine("List:       {0}", t1);
        Console.WriteLine("Dictionary: {0}", t2);
        Console.WriteLine("Optimized:  {0}", sG.Elapsed);

        /***************************
        List:       00:00:11.9061505
        Dictionary: 00:00:08.9502043
        Optimized:  00:00:08.2504321
        ****************************/
    }
}

In the example above, a Dictionary<int,int> is being used to store the index of each element. You will get better results if the gap between insertAt and takeFrom is smaller. As this interval increases, the performance will degrade. I guess you might want to evaluate this gap and take the optimal branch based on it's value.


text:
Q: How do I continue to upsert with a SOAP call that has lookups that can't find a record via external id? I have a SOAP request that sets the lookup fields using the lookup object's external IDs. However, for one particular lookup, I can't guarantee that it will find a matching Salesforce record. If that's the case, I still want it to insert, but insert with the lookup field set to null.
Currently, it will just throw an error saying the lookup value is not found. Is there a way to get around this in the SOAP message?
I'm using XSL transformations via the Oracle Service Bus.
Example:

:Foreign key external ID: 123456 not found for field Order_External_Key__c in entity Order:INVALID_FIELD;

A: Basically, no. You need to know the record exists, or create it beforehand. Your best bet would be to upsert the parent records beforehand and/or perform a query to check, thus ensuring that the records exist. This will double the number of API calls you need to use, but you can upsert in batches of 200 at a time, so it shouldn't be a significant problem.


text:
Q: struts not populating new selected value while using jquery dialog for hidden td I have one struts html form fields( containing publish date, cutoff date) and on below those fields I have one dynamic table and the data are coming from db. And in one column of the table there is a link when I want to click the link it will open one dialog with data in same form.
I changed any value on that dialog and then close it. and then when I change the publish date it will call struts action and get the cutoff date and will show in the cutoff date field(its not ajax call). But my problem is the selected items in the modal is setting to default one after changing the publish date.
Here is my code.

    <form action="abc.do">

         Name
         Address

        <logic:notEmpty property="addressList" name="AddressBean">
        <logic:iterate property="addressList" name="AddressBean"
                        scope="session" id="addressList" indexId="rownum">

            ABC

         City:

                - Select -
                <logic:iterate property="cityList" name="AddressBean" scope="session" id="cityCodeList">
                <c:if test='${cityCodeList.city != ""}'>
                                                        ${cityCodeList.city}
                                                    </c:if>
                </logic:iterate>

      </logic:iterate>
      </logic:notEmpty>

    </form>

but if I remove display:none from the  it is showing the value what I selected after changing the publish date. Could you please help me out?


text:
Q: Chrome debugger simulate memory limit I am trying to debug out of memory issues when my JS code runs on an old ipad
Is there a way to set a simulated memory limit in Chrome dev tools so that I will get Out of memory exceptions etc when it is breached ?


text:
Q: How to convert 64 bit binary string to a double float in ruby? I am wondering how to convert a 64 bit binary string to a double float in ruby. The string that I have is as follows:
binaryString = "0011111111110000000000000000000000000000000000000000000000000000"

Using an online converter (http://www.binaryconvert.com/convert_double.html?) I know that the value should be 1.0. However, I'm attempting to use the ruby unpack to convert to double, and I'm not getting the correct result.
double_value = binaryString.unpack("G")

Gives me double_value = 1.3983819593719592e-76
I've tried other directives like "F" and "D", but none yield correct results.
Any ideas what I am doing wrong? Thank you for the help!

A: unpack expects binary data, so you have to pack your bit string first using B:
b = '0011111111110000000000000000000000000000000000000000000000000000'

[b].pack('B*').unpack1('G')
#=> 1.0


text:
Q: My controller always shoots wide compared to keyboard in FIFA '15? In FIFA 15 I'm using Assist for the shot assistance, but the shot is not accurate at all. The ball directly goes to the direction that I press from the stick like in manual shot assistance. Is that normal?
I can't figure out how to avoid going wide of the goal every time. Always this happens to me even inside the box. I don't have this problem when I play using keyboard and always happens when I play using my controller and I didn't have this problem in FIFA 14.
How can I fix this problem ?


text:
Q: Download dynamic generated pdf from dynamic url which is being viewed in webbrowser control in adobe viewer in vb.net I am developing a windows application in vb.net in which i have a url which first ask me to login on the website and then display a view pdf link. As i make it click it again redirect to another page where instead of asking for download pdf it opens it in my web browser control. Now i want to save that opened pdf on my specified path. I have googled a lot but didn't find any solution for the same. I even found some related posts but none of them have my answer. Here my pdf url doesnt contains any file name like '.pdf'. Url contains some token values. To open this url it requires login on the website. I am trying to download pdf file for many days. Please help me.

A: you have to push your file using http headers
Unique HTTP Headers Returned
because these headers are the only thing controlling how your browser handles the file.
Save As Mode (askapache_pdf=s)
Content-Disposition: attachment
Content-Type: application/pdf
for more info goto http://www.askapache.com/htaccess/pdf-cookies-headers-rewrites.html#Unique_HTTP_Headers_Returned

A: This does not have anything to do with server side scripting language its same that you have to add a response in your header of http request. But anyway in ASP you should try something like below
Response.AddHeader("content-disposition", "attachment;filename=somefile.ext")


text:
Q: Air Density as a function of Altitude ONLY I have read this question and doesn't really achieve what I am trying to do.
I am looking for a function of the type

r(x)=....

Which returns the density of air at altitude x for Earth conditions and the changing temperatures that come with altitude difference for the earth like conditions.
I really couldn't find any. Any help appreciated it.

A: The Wikipedia article that has been linked to already gives a complete description of how to create the function you are looking for. It starts with a given temperature distribution, which is given as a piecewise linear function in various layers. From there you can then integrate the equations for pressure and density to obtain what you want. Ready-to-use models are also available, see here for an example.

A: In a comment, the OP referenced wanting to use a simple drag formula for aerodynamic drag, from grc.nasa.gov/www/k-12/airplane/drageq.html. For altitudes up to 10,000m, the data can be represented by formulas, as in http://www.dtic.mil/dtic/tr/fulltext/u2/a278141.pdf.
The temperature is assumed to change linearly with the altitude $h$:
$$T(h) = T_0 - \alpha h$$
Assuming that air is an ideal gas, this gives a pressure profile is
$$\frac {P(h)}{P_0} = \left(\frac{T(h)}{T_0}\right)^n$$
and the density profile is
$$\frac{\rho(h)}{\rho_0} = \left(\frac{T(h)}{T_0}\right)^{n-1}$$.
In SI units, $$\begin{align}
T_0 &= 288.16\, \text{K}\\
\alpha &= 0.0065\,\text{K/m}\\
P_0 &= 101325\,\text{Pa}\\
\rho_0 &= 1.225\, \text{Kg/m}^3\\
n &= 5.2561
\end{align}$$
For altitudes greater than 10,000m, the variation of temperature against altitude is more complicated, though it can be approximated as a graph containing several straight-line segments, as shown in https://en.wikipedia.org/wiki/Atmospheric_temperature. The constants in the above formulas are different for each segment, and you can't make "one equation" that covers the complete altitude range.

A: $$\rho_z=\rho_0exp(-mgz/kT)$$
where
$\rho_z$, $\rho_0$, $m$, $g$, $z$, $k$ and $T$ are density at $z$, density at sea level, mass of air, gravitational acceleration, altitude, Boltzmann constant and temperature, respectively.
* Intermolecular and Surface Forces (Third Edition), Jacob N. Israelachvili, p 27.


text:
Q: The elementary methods to compute $\int_0^\pi\frac{e^{ix}}{x-\alpha e^{ix}}\,dx\quad;\quad\text{for}\, \alpha>0$
How to compute the following integral using elementary methods (high school methods).
\begin{equation}\int_0^\pi\frac{e^{ix}}{x-\alpha e^{ix}}\,dx\qquad;\qquad\text{for}\, \alpha>0\end{equation}

Honestly, I don't know how to compute this integral. I have posted this problem in other forum and I only got a link direction to another problem but it didn't help me so that's why I post the problem here. So far I could manage to get
\begin{equation}
\frac{e^{ix}}{x-\alpha e^{ix}}=\frac{x\cos x-\alpha}{x^2-2\alpha x\cos x+\alpha^2}+i\frac{x\sin x}{x^2-2\alpha x\cos x+\alpha^2}
\end{equation}
or
\begin{equation}
\frac{e^{ix}}{x-\alpha e^{ix}}=\frac{1}{\alpha(\beta xe^{-ix}-1)}\qquad;\qquad\text{where}\, \beta=\frac{1}{\alpha}
\end{equation}
but none of them is easy to be computed. These are related questions that might help: [1] and [2]. Any help would be greatly appreciated. Thank you.

A: Inserting $k$ parameter to the problem :
$$f(k) \overset{\mathrm{def}}{=} \int_{0}^{\pi}\frac{e^{ikx}}{x-\alpha e^{ix}}$$
Where the original integral $I$ is the same as $f(1)$ i.e. $$I=f(0)$$
Differentiating with respect to k assuming that we can do that :
$$f'(k) = \int_{0}^{\pi}\frac{ix e^{ikx}}{x-\alpha e^{ix}} $$
See that f(k) solves delay differential equation
$$f'(k)-i\alpha f(k+1) = \int_{0}^{\pi}\frac{i(x - \alpha e^{ix}) e^{ikx}}{x-\alpha e^{ix}} = \frac{1}{k}\left(e^{ik\pi}-1\right) $$
Taking the limit as $k\to 0$
$$f'(0)-i\alpha I = i\pi $$
Then maybe you may proceed further...


text:
Q: Django HttpResponse generating csv but not downloading it I am taking queryset turning into csv file, I am even getting the response back. But the browser is not downloading the returned csv file. I am on chrome.
class CSVMixin(object):
csv_filename = 'csvfile.csv'

def get_csv_filename(self):
    return self.csv_filename

def render_to_csv(self, queryset):
    response = HttpResponse(content_type='text/csv')
    cd = 'attachment; filename="{0}"'.format(self.get_csv_filename())
    response['Content-Disposition'] = cd

    headers = queryset[0].keys()
    dict_writer = csv.DictWriter(response, fieldnames=headers)

    dict_writer.writeheader()
    dict_writer.writerows(queryset)
    return response

class EmailCampaignViewSet(CSVMixin, OrionAdminModelViewset):
    queryset = MyObject.objects.all()

    pagination_class = DefaultLimitOffsetPagination
    filter_class = EmailCampaignFilter

    @list_route()
    def report(self, request):
        query = self.request.query_params
        data_format = query['data_format'] if query['data_format'] else None

        if data_format == 'csv':
            return self.render_to_csv(queryset)

When I call the report route, I get the csv formatted text in my response. But it is not triggering the download.
Here is my request from react:
this.getReport = (format="json") => {
        this.setState({btnDisabled: true});
        const requestObj = {
            method: 'GET',
            headers: {
                'Authorization': 'Token ' + this.props.session_token,
                'Content-Type': 'application/json',
            }
        };

        const uri = new URI(`${API_ENDPOINT}/email-campaign/report`);
        const campaigns = this.state.campaignList.map((campaign)=>(
            campaign.value
        ));
        uri.setSearch({
            campaigns: [campaigns],
            date_from: stringToDateISOString(this.state.dateFrom),
            date_to: stringToDateISOString(this.state.dateTo),
            data_format: format,
        });
        return fetch(uri.toString(), requestObj).then(restJSONResponseToPromise).then(responseJSON => {
            if (responseJSON.results){
                this.setState({report: responseJSON.results, btnDisabled: false});
            }
        }, (response) => {
            clearSessionIfInvalidToken(this.props.clearSession);
            this.setState({btnDisabled: false});
        });
    }

Response Headers:
HTTP/1.0 200 OK
Date: Mon, 12 Jun 2017 19:58:03 GMT
Server: WSGIServer/0.2 CPython/3.5.3
Content-Type: text/csv
X-Frame-Options: SAMEORIGIN
Access-Control-Allow-Origin: http://localhost:3000
Vary: Accept, Origin
Allow: GET, OPTIONS
Content-Disposition: attachment; filename=emailcampaign_export.csv;
Cache-Control: no-cache

A: Try this:
from cStringIO import StringIO

def render_to_csv(self, queryset):
    file_io = StringIO()
    headers = queryset[0].keys()
    dict_writer = csv.DictWriter(file_io, fieldnames=headers)
    dict_writer.writeheader()
    dict_writer.writerows(queryset)
    response = HttpResponse(file_io.getvalue(), content_type='text/csv')
    file_io.close()
    cd = 'attachment; filename="{0}"'.format(self.get_csv_filename())
    response['Content-Disposition'] = cd
    return response


text:
Q: Convergence to a 2-dimensional vector of independent exponential variables Let $Y_{n(1)}$ and $Y_{n(n)}$ be the minimum and maximum of a random sample $Y_1,Y_2,...,Y_n$ from the uniform distribution on $[0,1]$.
The sequence $(n(Y_{n(1)}),n(1-Y_{n(n)})$ converges in distribution to $(U,V)$ where $U$ and $V$ are independent exponential variables.
To show this, I started with
\begin{align}
P(nY_{n(1)}\leq x, n(1-Y_{n(n)})\leq y)\\
= P(Y_{n(1)}\leq \frac{x}{n}, (1-Y_{n(n)})\leq \frac{y}{n})\\
= P(Y_{n(1)}\leq \frac{x}{n} | Y_{n(n)}\geq \frac{-y}{n}+1)P(Y_{n(n)}\geq \frac{-y}{n}+1)
\end{align}
I'm sure that $Y_{n(1)}$ and $Y_{n(n)}$ are not independent and I know that
\begin{align}
P(Y_{n(n)}\geq \frac{-y}{n}+1)\rightarrow 1-e^{-y}
\end{align}
Then the conditional one, I thought about integrals but then also the density of $Y_{n(n)}$ is needed. And of course $\frac{-y}{n}+1\rightarrow 1$ but then it would be a too large step (I think) to conclude that the conditional one is simply converging to $1-e^{-x}$, by which the proof would be done.
Is there anyone who can help?

A: You're taking the right approach, but it becomes much easier if you instead consider
 $$\mathbb P(n Y_{n(1)} \ge x, n(1 - Y_{n(n)}) \ge y),$$
because this is true if and only if $\frac xn \le Y_i \le 1 - \frac yn$ for all $i$. This has probability $\left(1 - \frac{x+y}{n}\right)^n$, and $$\lim_{n \to \infty} \left(1 - \frac{x+y}{n}\right)^n = e^{-(x+y)} = e^{-x} e^{-y}.$$
From here, things are straightforward, because this matches $\mathbb P(U \ge x, V \ge y)$ if $U$ and $V$ are independent exponential variables with rate $1$.
In general, when dealing with exponential distribution, the tail distribution function $\mathbb P(X \ge x)$ is much easier to deal with than the ordinary cdf, and here is no exception.