text:
Q: C# HttpClient 4.5 multipart/form-data upload Does anyone know how to use the HttpClient in .Net 4.5 with multipart/form-data upload?
I couldn't find any examples on the internet.

A: This is an example of how to post string and file stream with HTTPClient using MultipartFormDataContent. The Content-Disposition and Content-Type need to be specified for each HTTPContent:
Here's my example. Hope it helps:
private static void Upload()
{
    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Add("User-Agent", "CBS Brightcove API Service");

        using (var content = new MultipartFormDataContent())
        {
            var path = @"C:\B2BAssetRoot\files\596086\596086.1.mp4";

            string assetName = Path.GetFileName(path);

            var request = new HTTPBrightCoveRequest()
                {
                    Method = "create_video",
                    Parameters = new Params()
                        {
                            CreateMultipleRenditions = "true",
                            EncodeTo = EncodeTo.Mp4.ToString().ToUpper(),
                            Token = "x8sLalfXacgn-4CzhTBm7uaCxVAPjvKqTf1oXpwLVYYoCkejZUsYtg..",
                            Video = new Video()
                                {
                                    Name = assetName,
                                    ReferenceId = Guid.NewGuid().ToString(),
                                    ShortDescription = assetName
                                }
                        }
                };

            //Content-Disposition: form-data; name="json"
            var stringContent = new StringContent(JsonConvert.SerializeObject(request));
            stringContent.Headers.Add("Content-Disposition", "form-data; name=\"json\"");
            content.Add(stringContent, "json");

            FileStream fs = File.OpenRead(path);

            var streamContent = new StreamContent(fs);
            streamContent.Headers.Add("Content-Type", "application/octet-stream");
            //Content-Disposition: form-data; name="file"; filename="C:\B2BAssetRoot\files\596090\596090.1.mp4";
            streamContent.Headers.Add("Content-Disposition", "form-data; name=\"file\"; filename=\"" + Path.GetFileName(path) + "\"");
            content.Add(streamContent, "file", Path.GetFileName(path));

            //content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");

            Task<HttpResponseMessage> message = client.PostAsync("http://api.brightcove.com/services/post", content);

            var input = message.Result.Content.ReadAsStringAsync();
            Console.WriteLine(input.Result);
            Console.Read();
        }
    }
}

A: Try this its working for me.
private static async Task<object> Upload(string actionUrl)
{
    Image newImage = Image.FromFile(@"Absolute Path of image");
    ImageConverter _imageConverter = new ImageConverter();
    byte[] paramFileStream= (byte[])_imageConverter.ConvertTo(newImage, typeof(byte[]));

    var formContent = new MultipartFormDataContent
    {
        // Send form text values here
        {new StringContent("value1"),"key1"},
        {new StringContent("value2"),"key2" },
        // Send Image Here
        {new StreamContent(new MemoryStream(paramFileStream)),"imagekey","filename.jpg"}
    };

    var myHttpClient = new HttpClient();
    var response = await myHttpClient.PostAsync(actionUrl.ToString(), formContent);
    string stringContent = await response.Content.ReadAsStringAsync();

    return response;
}

A: Here is another example on how to use HttpClient to upload a multipart/form-data.
It uploads a file to a REST API and includes the file itself (e.g. a JPG) and additional API parameters. The file is directly uploaded from local disk via FileStream.
See here for the full example including additional API specific logic.
public static async Task UploadFileAsync(string token, string path, string channels)
{
    // we need to send a request with multipart/form-data
    var multiForm = new MultipartFormDataContent();

    // add API method parameters
    multiForm.Add(new StringContent(token), "token");
    multiForm.Add(new StringContent(channels), "channels");

    // add file and directly upload it
    FileStream fs = File.OpenRead(path);
    multiForm.Add(new StreamContent(fs), "file", Path.GetFileName(path));

    // send request to API
    var url = "https://slack.com/api/files.upload";
    var response = await client.PostAsync(url, multiForm);
}

A: my result looks like this:
public static async Task<string> Upload(byte[] image)
{
     using (var client = new HttpClient())
     {
         using (var content =
             new MultipartFormDataContent("Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture)))
         {
             content.Add(new StreamContent(new MemoryStream(image)), "bilddatei", "upload.jpg");

              using (
                 var message =
                     await client.PostAsync("http://www.directupload.net/index.php?mode=upload", content))
              {
                  var input = await message.Content.ReadAsStringAsync();

                  return !string.IsNullOrWhiteSpace(input) ? Regex.Match(input, @"http://\w*\.directupload\.net/images/\d*/\w*\.[a-z]{3}").Value : null;
              }
          }
     }
}

A: Here's a complete sample that worked for me. The boundary value in the request is added automatically by .NET.
var url = "http://localhost/api/v1/yourendpointhere";
var filePath = @"C:\path\to\image.jpg";

HttpClient httpClient = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();

FileStream fs = File.OpenRead(filePath);
var streamContent = new StreamContent(fs);

var imageContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);
imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");

form.Add(imageContent, "image", Path.GetFileName(filePath));
var response = httpClient.PostAsync(url, form).Result;

A: It works more or less like this (example using an image/jpg file):
async public Task<HttpResponseMessage> UploadImage(string url, byte[] ImageData)
{
    var requestContent = new MultipartFormDataContent();
    //    here you can specify boundary if you need---^
    var imageContent = new ByteArrayContent(ImageData);
    imageContent.Headers.ContentType =
        MediaTypeHeaderValue.Parse("image/jpeg");

    requestContent.Add(imageContent, "image", "image.jpg");

    return await client.PostAsync(url, requestContent);
}

(You can requestContent.Add() whatever you want, take a look at the HttpContent descendant to see available types to pass in)
When completed, you'll find the response content inside HttpResponseMessage.Content that you can consume with HttpContent.ReadAs*Async.

A: I'm adding a code snippet which shows on how to post a file to an API which has been exposed over DELETE http verb. This is not a common case to upload a file with DELETE http verb but it is allowed. I've assumed Windows NTLM authentication for authorizing the call.
The problem that one might face is that all the overloads of HttpClient.DeleteAsync method have no parameters for HttpContent the way we get it in PostAsync method
var requestUri = new Uri("http://UrlOfTheApi");
using (var streamToPost = new MemoryStream("C:\temp.txt"))
using (var fileStreamContent = new StreamContent(streamToPost))
using (var httpClientHandler = new HttpClientHandler() { UseDefaultCredentials = true })
using (var httpClient = new HttpClient(httpClientHandler, true))
using (var requestMessage = new HttpRequestMessage(HttpMethod.Delete, requestUri))
using (var formDataContent = new MultipartFormDataContent())
{
    formDataContent.Add(fileStreamContent, "myFile", "temp.txt");
    requestMessage.Content = formDataContent;
    var response = httpClient.SendAsync(requestMessage).GetAwaiter().GetResult();

    if (response.IsSuccessStatusCode)
    {
        // File upload was successfull
    }
    else
    {
        var erroResult = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
        throw new Exception("Error on the server : " + erroResult);
    }
}

You need below namespaces at the top of your C# file:
using System;
using System.Net;
using System.IO;
using System.Net.Http;

P.S. You are seeing a number of using blocks(IDisposable pattern) in the above code snippet which doesn't look very clean. Unfortunately, the syntax of using construct doesn't support initializing multiple variables in single statement.

A: Example with preloader Dotnet 3.0 Core
ProgressMessageHandler processMessageHander = new ProgressMessageHandler();

processMessageHander.HttpSendProgress += (s, e) =>
{
    if (e.ProgressPercentage > 0)
    {
        ProgressPercentage = e.ProgressPercentage;
        TotalBytes = e.TotalBytes;
        progressAction?.Invoke(progressFile);
    }
};

using (var client = HttpClientFactory.Create(processMessageHander))
{
    var uri = new Uri(transfer.BackEndUrl);
    client.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", AccessToken);

    using (MultipartFormDataContent multiForm = new MultipartFormDataContent())
    {
        multiForm.Add(new StringContent(FileId), "FileId");
        multiForm.Add(new StringContent(FileName), "FileName");
        string hash = "";

        using (MD5 md5Hash = MD5.Create())
        {
            var sb = new StringBuilder();
            foreach (var data in md5Hash.ComputeHash(File.ReadAllBytes(FullName)))
            {
                sb.Append(data.ToString("x2"));
            }
            hash = result.ToString();
        }
        multiForm.Add(new StringContent(hash), "Hash");

        using (FileStream fs = File.OpenRead(FullName))
        {
            multiForm.Add(new StreamContent(fs), "file", Path.GetFileName(FullName));
            var response = await client.PostAsync(uri, multiForm);
            progressFile.Message = response.ToString();

            if (response.IsSuccessStatusCode) {
                progressAction?.Invoke(progressFile);
            } else {
                progressErrorAction?.Invoke(progressFile);
            }
            response.EnsureSuccessStatusCode();
        }
    }
}

A: X509Certificate clientKey1 = null;
clientKey1 = new X509Certificate(AppSetting["certificatePath"],
AppSetting["pswd"]);
string url = "https://EndPointAddress";
FileStream fs = File.OpenRead(FilePath);
var streamContent = new StreamContent(fs);

var FileContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);
FileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("ContentType");
var handler = new WebRequestHandler();

handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ClientCertificates.Add(clientKey1);
handler.ServerCertificateValidationCallback = (httpRequestMessage, cert, cetChain, policyErrors) =>
{
    return true;
};

using (var client = new HttpClient(handler))
{
    // Post it
    HttpResponseMessage httpResponseMessage = client.PostAsync(url, FileContent).Result;

    if (!httpResponseMessage.IsSuccessStatusCode)
    {
        string ss = httpResponseMessage.StatusCode.ToString();
    }
}

A: public async Task<object> PassImageWithText(IFormFile files)
{
    byte[] data;
    string result = "";
    ByteArrayContent bytes;

    MultipartFormDataContent multiForm = new MultipartFormDataContent();

    try
    {
        using (var client = new HttpClient())
        {
            using (var br = new BinaryReader(files.OpenReadStream()))
            {
                data = br.ReadBytes((int)files.OpenReadStream().Length);
            }

            bytes = new ByteArrayContent(data);
            multiForm.Add(bytes, "files", files.FileName);
            multiForm.Add(new StringContent("value1"), "key1");
            multiForm.Add(new StringContent("value2"), "key2");

            var res = await client.PostAsync(_MEDIA_ADD_IMG_URL, multiForm);
        }
    }
    catch (Exception e)
    {
        throw new Exception(e.ToString());
    }

    return result;
}


text:
Q: Error while starting the integration node in IIB 10.0.0.24 Getting the following error while creating and starting the integration node in IIB 10.0.0.24 on windows 10 Pro 64-bit
Begin running task [The local integration node is being created]
mqsicreatebroker DEV_NODE -i LocalSystem -S yes
BIP8071I: Successful command completion.
End running task [The local integration node is being created]
Begin running task [The local integration node is being started]
mqsistart DEV_NODE
BIP8015E: The component cannot be started.
The command cannot start the required component.
The possible causes of this error are: insufficient user ID permissions; lack of system resources (not enough memory); the WebSphere MQ environment is not configured correctly for the user who is running the command (for example, the mqm library is missing from the user's path).
The task was unsuccessful: The command failed.
I have added the username in the mqbrkrs, though my user in not a local user but in one of the network domains.
Kindly, help.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why are Nvidia proprietary drivers not visible on Ubuntu 19.04? The recommended Nvidia driver for my card (1050ti) is 435.12.  However, I cannot get any proprietary drivers to show up in the Additional Drivers list, nor can I install the Nvidia binary package directly.
So far, this is a clean Ubuntu 19.04 install, with the exception that I've disabled Wayland (made no difference).

Update: I manually added ppa:graphics-drivers/ppa but still it did not show me the correct proprietary driver packages.


text:
Q: How to structure code when introducing new If statement before chunk of logic So lets say I have a function like so:
function doStuff () {
    let myVar = 3;
    doSomething()
    ......doManyThings()
}

And now I want to introduce some logic like so:
function doStuff () {
    if( true ) {
        doThis()
        ....do All The Stuff Above
        doThat()
    } else {

        ....do All The Stuff Above
        doAnotherThing()
    }
}

What is a good solution to handle the refactoring of this function without introducing a completely new function?

A: You could use the condition only for doThis()
function doStuff () {
    if ( true ) {
        doThis()
    }
    ....do All The Stuff Above
}

EDIT
If you use the same part again, use the don't repeat yourself (DRY) principle and move the parts into a new function, maybe inside of the actual function for the right scope.

A: function doStuff () {
    let myNewFunction = function () {
          ....do All The Stuff Above
    }
    if( true ) {
        doThis()
        myNewFunction()
        doThat()
    } else {
        myNewFunction()
        someOtherNewFunction()
    }
}

Should be fine.
Consider moving the common functions into an object. Check out this article for more details.


text:
Q: Set string value with formatting symbols in js/jsp I have on jsp page:
<script type="application/javascript">
    var test = {};
    test.id = ${docId};
    test.message = ${message};
</script>

If message equal:
'hello world'

I'll get error in page: "Uncaught SyntaxError: Invalid or unexpected token"
How set string value in js? if value have \n, \' or other formatting symbols

A: An Example on Glassfish4 server.
The following JSP:
<!DOCTYPE html>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>initJsObject</title>
</head>
<body>
<!-- prepare attributes, just for testing -->
<c:set var="docId" value="123"></c:set>
<c:set var="message" value="'hello world'"></c:set>
<c:set var="lines" value="'line1\nline2'"></c:set>
<c:set var="backslashN" value="'\\\\\n'"></c:set>

<textarea id="txt" style="height: 200px; width: 200px;"></textarea>

<script type="text/javascript">
    var test = {};
    test.id = ${docId};
    test.message = ${message};
    test.lines = ${lines};
    test.backslashN = ${backslashN};
    console.log(test);

    document.getElementById("txt").value += "id: " + test.id + "\n";
    document.getElementById("txt").value += "message:" +  test.message + "\n\n";
    document.getElementById("txt").value += "lines:\n"+ test.lines + "\n\n";
    document.getElementById("txt").value += "backslashN: ("+ test.backslashN + ")\n\n";
</script>
</body>
</html>

generates the html:
<!DOCTYPE html>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>initJsObject</title>
</head>
<body>
<!-- prepare attributes fot testing -->
<textarea id="txt" style="height: 200px; width: 200px;"></textarea>

<script type="text/javascript">
    var test = {};
    test.id = 123;
    test.message = 'hello world';
    test.lines = 'line1\nline2';
    test.backslashN = '\\n';
    console.log(test);

    document.getElementById("txt").value += "id: " + test.id + "\n";
    document.getElementById("txt").value += "message:" +  test.message + "\n\n";
    document.getElementById("txt").value += "lines:\n"+ test.lines + "\n\n";
    document.getElementById("txt").value += "backslashN: ("+ test.backslashN + ")\n\n";
</script>
</body>
</html>

And outputs in browser:

id: 123
  message:hello world
lines:
  line1
  line2
backslashN: (\n)

As you see the \n in the attribute string 'line1\nline2' will be evaluated as new line.
On the other side, if you need the sting \n to be presented as text, you need to escape '\\\\\n'


text:
Q: Latest version of ReSharper breaks both Bower and project.json 'version intellisense' in ASP.NET Core 1.0 projects This issue has been going on for a while. I noticed that when my ReSharper is enabled it messes up the version intellisense when in bower.json and project.json.
I like being able to see the latest version at this point:
jquery": ...

As soon as I disable ReSharper and restart vs2015 all intellisense works again.

A: I have notice also with new update Resharper Ultimate 2016.2. As soon as i select VS2015 intellisense it work fine in project.json files but when select resharper it break. Then i select custom option and select json as visualstudio intellisense  and all other select resharper intellisense. After that it work smoothly.


text:
Q: How to search for a pattern in a file from the end of a directory using grep? I need to search for files containing a pattern in a directory (to search from the end of the directory to the start).
This is the command I use now,
grep -rl 'pattern'
Is there any command to search for a pattern from the last file of a directory to the first file?

A: If you want to grep to search in some order, you need to pass it a list of file names in the order you want. If you want the files in the current directory in reverse order of name, ls -r would do the job. How about something like this?
ls -1br | xargs grep 'pattern'

Note the -b, which is needed to mitigate problems with spaces and metacharacters in file names.
Note also that this won't cope well with sub-directories. But the principle is sound - generate a list of files in the order you want and pass it to grep using xargs.


text:
Q: Amazon cloudsearch describedoamin usage I am trying to use describeDomains function of AWS CloudSearch. But I am getting the below error.

exception 'ReflectionException' with message 'Method Aws\CloudSearch  \CloudSearchClient::describeDomains() does not exist

A: You've probably already figured this out by now, but I think you just need to fix the casing of the DescribeDomains() method (note the initial capital D).
See PHP SDK documentation:
https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-cloudsearch-2013-01-01.html#describedomains


text:
Q: Number of vertices of a complete graph with $n$ edges I am given this problem: Suppose you have a complete graph with $n$ edges. How many vertices does your graph have?
I have this math figured out so far: We know that a complete graph has $m$ vertices, with $m-1$ edges connected to each. This makes the sum of the total number of degrees $m(m-1)$. Then, since this sum is twice the number of edges, the number of edges is $\frac{m(m-1)}{2}$.
But I don't think that is the answer. I think I am missing a piece of the math, but I can't figure out what else I need to do. Can anyone help me with what I'm missing or doing wrong?

A: Since your complete graph has $n$ edges, then $n = m(m-1)/2$, where $m$ is the number of vertices. You want to express $m$ in terms of $n$, and you can rewrite the above equation as the quadratic equation
$$m^2/2-m/2 - n = 0,$$
which you can then solve for $m$. The solution will depend on $n$.
The equation is equivalent to $m^2-m-2n=0$, whose discriminant is $d=1+8n$, and thus
$$m = \frac{1\pm\sqrt{1+8n}}{2}.$$
You of course throw away the negative solution.


text:
Q: TestNG Selenium Grid 2 not running tests in parallel I seem to be having an issue when attempting to run tests in parallel using TestNG alongside Selenium Grid 2.
Although the right number of browsers are opened to match the amount of tests that I'm running , all instructions for all tests are being fired to the same browser window. For example, each test will open a page and attempt to log in. Four browser windows will open, but one browser window will navigate to the login page four times and then type the username in 4 times, whilst the rest of the browser windows remain inactive.
Here's how I'm starting grid:
java -jar selenium-server-standalone-28.0.jar -role hub
java -jar selenium-server-standalone-28.0.jar -webdriver.chrome.driver="*location*/chromedriver_mac" -role node

This is how the suite xml is set up:
<suite name="testng" verbose="1" parallel="classes">
    <test name="chrome">
        <packages>
            <package name="login"/>
            <package name="lists"/>
        </packages>
    </test>
</suite>

And here's an example of how the tests are laid out:
public class login_logout extends TestBase {
    @Test
    public void login(){
        //initiates login page object and call super user login
        LoginPage login = LoginPage.navigateTo(driver, base_url)
        LoggedInPage loggedIn = login.superuserlogin();
        }
    }

Test Base is laid out as follows:
public class TestBase {
    public static WebDriver driver;
    public static DesiredCapabilitiess capabilities;
    @BeforeClass
    public static void setUp(){
        base_url = "*login page url*;
        capabilities = DesiredCapabilities.chrome();
        driver = new RemoteWebDriver(capabilities);
        driver.get(base_url);
    }
}

It's probably something really obvious that I'm missing but any help would be appreciated.
Thanks in advance.

A: The driver object is static.  So you have 4 initializations happening and 4 browsers launching but the driver being a static , it would hold only the reference to the last initialized browser and hence all your commands are being executed against the same driver.  You can try exploring  Threadlocal objects for your parallel runs.

A: From my point of view, you made the right decision in choosing WebDriver and TestNG.
But due to the fact these are really powerful tools there are some basics you should know.
In the first step, it's important to have some programming experience in general.
Secondly there are some specific tricks you can add.
Why don't you initialize a WebDriver in every single Test Class (either in the constructor or a @BeforeClass)?
Later on, you can also use the @DataProvider and @Factory pattern to do the configuration.
That's kinda cool!


text:
Q: Regarding the Existence of Approximate Identities for C$^{*}$-Algebras I am confused about one part in a proof on page 78 of Murphy's book. Let $A$ be a C$^{*}$-algebra and let $\Lambda=\{a\in A:a\geq 0\text{ and }\|a\|<1\}$. While proving that $A$ is upwards directed, Murphy states the following:

Observe that if $a\in A^{+}$, then $a(1_{\widetilde{A}}+a)^{-1}$ belongs to $\Lambda$ (use the Gelfand representation applied to the C$^{*}$-algebra generated by $1_{\widetilde{A}}$ and $a$).

I understand the hint: using the spectral mapping theorem, I can prove that $\sigma_{\widetilde{A}}(a(1_{\widetilde{A}}+a)^{-1})\subset[0,1]$, but this shows that $a(1_{\widetilde{A}}+a)^{-1}$ is positive in $\widetilde{A}$. I do not know how to prove that $a(1_{\widetilde{A}}+a)^{-1}\in A^{+}$. In fact, this seems false since $a(1_{\widetilde{A}}+a)^{-1}$ may not even be in $A$. I know in general that $A^{+}=\widetilde{A}^{+}\cap A$, but I am unsure how or if this is being used here. I would really appreciate some clarification regarding why Murphy is able to pass to the unitisation here.
Thank you!

A: When you consider the unitization, $A$ sits inside it as an   ideal. Also, since $a$ and $(1_{\tilde A}+a)^{-1}$ commute, you have
$$
a(1_{\tilde A}+a)^{-1}=a^{1/2}(1_{\tilde A}+a)^{-1}a^{1/2}\geq0.
$$
So $a(1_{\tilde A}+a)^{-1}\in A_+$.


text:
Q: Auto close stories on all tasks completed Our developers work from Sprint Boards, and they drag tasks into Closed stage. However, this leaves stories as New / Active when all tasks are done, and there is no easy way to know if story has all tasks completed

*

*Is there a way to auto-close story when all tasks are done (without any additional plugins)?

*Is there a way to identify what stories have all tasks closed/resolved?

A: Work items have independent states. Most of our experiences will not include automatic updates based on hierarchy. Either based on parent to update child or based on child to update parent.
You could refer Taylor's comment in this thread--User Story status closed but child Task still active?
Even though there is not any build-in solution, you could use some 3-rd party tool to auto change parent states: TFS Aggregator .
Another sample using Webhook to handle this.  Detail solution here: https://twitter.com/danhellem/status/1173614918333030400?s=20
which leads to: https://github.com/microsoft/azure-boards-automate-state-transitions


text:
Q: Does projective geometry assume all scene points are in or beyond the view plane? I should add that Jennings is developing abstract projective geometry on the basis of perspective drawing; motivating concepts such as "point at infinity", and indirectly, the zero value coordinate in ideal points and ideal lines.  If there is a formal mathematics involved it is called projectivization.  It is (I believe) the mathematics used in Persistence of Vision Ray-tracer http://www.povray.org/ and robotics http://www.ipb.uni-bonn.de/html/teaching/3dcs-ge-2020/stachniss/2020-3dcs-02-homogeneous-coords-4.pdf
My question is about the mathematical formalism of this particular aspect of "concrete" projective geometry.  There may be no consistent answer to this; since it is apparently not considered an essential topic in theoretical projective geometry.
Does the mathematical formalism of perspective (central) projection assume all scene points are in or beyond the view plane, or at least "in front" of the central point (i.e., eye)?
The excerpt below is from Modern Geometry with Applications ,by George A. Jennings.  His pictures do not appear to agree with his words.  For example

Only one radial line in the plane $\overline{OP}$ does not connect a point on $L$ to the eye.

For that to be true, we would have to include points of $L$ "behind" the eye.
Jennings is clearly appealing strongly to intuition, which is exactly what I like about his book.  In other places his mathematical statements are typically correct and transcend his heuristics.  Am I to assume the same in this case?

A:
Does projective geometry assume all scene points are […] "in front" of the central point […]?

No.
Projective geometry typically uses homogeneous coordinate vectors, where you may multiply all coordinates with the same (non-zero) scalar factor without changing the point it represents. Using a negative factor exchanges a representative "in front of the eye" with one "behind the eye".
In a less coordinate-based view, the points of projective geometry correspond to lines through the origin one dimension higher. Lines, not rays, so the part behind is just as valid as the part in front of the central point, the origin.
There are certainly variations of this. Situations where you employ a machinery very much like projective geometry but talking signs and rays into account. Such a system would not be considered standard projective geometry, though.
However you could also take the thought from the opposite direction. Given that every line though the origin represents a point, where in the viewing plane does that represented point lie? Well, just intersect the line with the viewing plane, and you get a represented point that lies in the viewing plane. An intuitive setup would have that viewing plane in front of the eye, so most points would indeed be in front of the eye.
The one notable exception to this is the situation where the line representing a point doesn't intersect the viewing plane because it runs parallel to that. Then you get a point at infinity, which can't be represented as a finite point in the viewing plane.
In your diagram, the line $OL$ plays the role of the viewing plane. Lines or rays through the eye represent points on that line. So take care to not assume a viewing plane vertical in front of the eye in that diagram.
Your edit changed the question from "projective geometry" to "central projection". This shifts away from a rich and well defined field of mathematics, where many things have specific meaning to make sense in combination, towards a specific operation that has far fewer strings attached and thus far more leeway to be used in whatever way makes most sense in a given situation. So for example a ray tracer indeed traces rays, not lines, and might even discard parts of the scene that are in front but too close to the eye. When it comes to ideal points and infinity, central projection using rays might be useful for building intuition but less suitable for a rigorous framework. Identifying "opposite" ideal points is a critical aspect of projective geometry.

A: This isn't really an answer, because it is a hand-waving math history lecture, but Wildberger (an eccentric and highly competent mathematician) presents a very interesting assertion that one can complete a hyperbola by joining the vanishing points of the branch behind the viewplane with those of the branch in front of the view plane to form an ellipse. Projective Geometry: Math History https://youtu.be/NYK0GBQVngs?t=2282 But the implication is that points on a non-radial plane behind the observer map to points in the viewplane above the vanishing line of the plane.


text:
Q: What is the IntelliJ shortcut key to create a javadoc comment? In Eclipse, I can press Alt+Shift+J and get a javadoc comment automatically generated with fields, returns, or whatever would be applicable for that specific javadoc comment. I'm assuming that IntelliJ IDEA has this feature. Can anyone tell me if there is a keyboard shortcut for this?

A: You can use the action 'Fix doc comment'. It doesn't have a default shortcut, but you can assign the Alt+Shift+J shortcut to it in the Keymap, because this shortcut isn't used for anything else.
By default, you can also press Ctrl+Shift+A two times and begin typing Fix doc comment in order to find the action.

A: Shortcut Alt+Enter shows intention actions where you can choose "Add Javadoc".

A: Typing /** + then pressing Enter above a method signature will create Javadoc stubs for you.


text:
Q: A class as data member of another class I have two classes A and C, where I need to have object of C in class A as a private member. This is the basic structure I have and I have following issues:
1. How can I create the itsC object in constructor?
2. I am getting following error 'function call missing argument list' as shown below
C::C(String strc)
    {
    //do something
    }

Class A
{
public:
A(String stra, String strb)  ;
~A();
C GetC();   //method

private:
C itsC(String str1);   //data member
}

A::A(String stra, String strb)
{
  //create object itsC
  //strb is needed for str1
}

C A::GetC()
{
  return itsC;  //error::function call missing argument list
}

Thanks.

A: C itsC(String str1);

Is a member function declaration, not a data member. It should be
C itsC;

Then you can initialise it in A::A
A::A(String stra, String strb) : itsC(stra) { }


text:
Q: How do I remove the yellow border when an object has focus in Flash? How do i remove the yellow border - focusRect - in as3
I've tried Stage.focusRect = false but that doesn't do the job.

A: I faced the same problem while I was making a Game. I wanted focus on my main class by typing:
stage.focus = this;

but a yellow rectangle appeared.
Then I typed:
stage.focus = this;
this.focusRect = false;

but this time, not a yellow rectangle but a yellow line appeared.
Then I typed:
this.focusRect = false;
stage.focus = this;

And this time it worked. No yellow rectangle or line appeared. So, I realized that order does matter sometimes.
If you're working with class just import:
import flash.display.Stage;

A: Try:
focusRect = false;

In your class' constructor. Worked for me :-)
From the docs: flash.display.InteractiveObject.focusRect(focusRect:Object):void
Specifies whether this object displays a focus rectangle. It can take one of three values: true, false, or null. Values of true and false work as expected, specifying whether or not the focus rectangle appears. A value of null indicates that this object obeys the stageFocusRect property of the Stage.

A: stage.stageFocusRect = false;

More info: Rockabit blogpost
:)


text:
Q: DIV innerText fills but not trigger the change event I'm trying to simulate a search on web version of Whatsapp (https://web.whatsapp.com). My goal is to do this task using pure JS, for study purposes. By looking the source code, i can see the search field is actually an editable DIV element :

With this source :

Here is what i tried :
1 - I first locate the element on page :
var node = document.getElementsByClassName('_13NKt copyable-text selectable-text')[0];

2 - I then set innertext :
node.innerText = 'test';

3 - The div is filled (although the placeholder is still there) , but the event that makes the search is not triggered :

4 - So i try to dispatch events that could trigger the 'search' event of the div :
node.dispatchEvent(new Event('input', { bubbles: true }));
node.dispatchEvent(new Event('change', { bubbles: true }));
node.dispatchEvent(new Event('keydown', { bubbles: true }));

Nothing really helped. At this point, the only way to make the page really search for 'test' string, is to manually click on the div and hit space bar.
What am i missing ?

A: I've tried to replicated web.whatsapp.com. As mentioned above by myf for the solution need those attributes
 and the change event not fire in that case.
The input event works and for intercept the string we  can to use event.target.textContent instead event.target.value.

document.addEventListener('DOMContentLoaded', function () {
  const searchBar = document.querySelector('.search-bar');
  const input = document.querySelector('.search-input');
  const clearButton = document.querySelector('.clear-button');

  const focusedField = () => {
    searchBar.classList.add('focused');
    input.focus();
  };

  const outSideClick = ev => {
    ev.stopPropagation();
    const isSearchBar = ev.target.closest('.search-bar');
    const isEmptyField = input.textContent.length;

    if (!isSearchBar && isEmptyField === 0) {
      searchBar.classList.remove('focused');
      document.removeEventListener('click', outSideClick);
    }
  };

  const showClearBtn = ev => {
    const isEmptyFiled = ev.target.textContent.length;
    console.log(ev.target.textContent);
    if (isEmptyFiled === 0) {
      clearButton.classList.remove('active');
      return;
    }
    clearButton.classList.add('active');
  };

  const clearText = () => {
    input.textContent = '';
    clearButton.classList.remove('active');
  };

  clearButton.addEventListener('click', clearText);
  input.addEventListener('input', showClearBtn);
  searchBar.addEventListener('mouseup', focusedField);
  document.addEventListener('mouseup', outSideClick);
});
*,
::after,
::before {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell,
    'Open Sans', 'Helvetica Neue', sans-serif;
}

:root {
  --bg: hsl(201, 27%, 10%);
  --input-field: hsl(197, 7%, 21%);
  --font-color: hsl(206, 3%, 52%);
  --search-bar-height: 48px;
}

html {
  height: 100%;
}

body {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: var(--bg);
}

.search-bar {
  height: var(--search-bar-height);
  width: 350px;
  display: flex;
  align-items: center;
  position: relative;
  padding-inline: 1em 1.5em;
  overflow: hidden;
  background-color: var(--input-field);
  border-radius: 50px;
  z-index: 10;
}

.search-bar.focused .icon[data-icon='search'] {
  opacity: 0;
  transform: rotate(45deg);
}
.search-bar.focused .icon[data-icon='back'] {
  opacity: 1;
  transform: rotate(0deg);
}

.search-bar.focused .search-placeholder {
  display: none;
}

.search-button,
.clear-button {
  width: calc(var(--search-bar-height) / 2);
  height: calc(var(--search-bar-height) / 2);
  display: flex;
  position: relative;
  background-color: transparent;
  border: none;
  outline: none;
  transition: opacity 0.3s ease-in-out;
}

.icon {
  position: absolute;
  inset: 0;
  transition: all 0.3s ease-in-out;
  cursor: pointer;
}
.icon path {
  fill: var(--font-color);
}
.icon[data-icon='back'] {
  transform: rotate(-45deg);
  opacity: 0;
}
.clear-button {
  opacity: 0;
  pointer-events: none;
}
.clear-button.active {
  opacity: 1;
  pointer-events: initial;
}

.search-field {
  height: 2em;
  display: flex;
  margin-inline-start: 1em;
  flex-grow: 1;
  position: relative;
  overflow: hidden;
}

.search-placeholder,
.search-input {
  height: inherit;
  position: absolute;
  top: 3px;
  font-size: 1rem;
  color: var(--font-color);
  transition: all 0.3s ease-in-out;
  white-space: nowrap;
}

.search-placeholder {
  text-overflow: ellipsis;
  pointer-events: none;
  user-select: none;
}

.search-input {
  width: 100%;
  outline: none;
  border: 1px solid transparent;
  /* border transparent for caret visibility  */
}

  <button class="search-button">

          <svg viewBox="0 0 24 24" width="24" height="24">
            <path
              fill="currentColor"
              d="M15.009 13.805h-.636l-.22-.219a5.184 5.184 0 0 0 1.256-3.386 5.207 5.207 0 1 0-5.207 5.208 5.183 5.183 0 0 0 3.385-1.255l.221.22v.635l4.004 3.999 1.194-1.195-3.997-4.007zm-4.808 0a3.605 3.605 0 1 1 0-7.21 3.605 3.605 0 0 1 0 7.21z"
            ></path>
          </svg>

          <svg viewBox="0 0 24 24" width="24" height="24">
            <path
              fill="currentColor"
              d="M12 4l1.4 1.4L7.8 11H20v2H7.8l5.6 5.6L12 20l-8-8 8-8z"
            ></path>
          </svg>

      </button>

Search or start new chat

  <button class="clear-button">

          <svg viewBox="0 0 24 24" width="24" height="24">
            <path
              fill="currentColor"
              d="M17.25 7.8L16.2 6.75l-4.2 4.2-4.2-4.2L6.75 7.8l4.2 4.2-4.2 4.2 1.05 1.05 4.2-4.2 4.2 4.2 1.05-1.05-4.2-4.2 4.2-4.2z"
            ></path>
          </svg>

      </button>

A: onChange event triggers only for these supported elements:
<input type="checkbox">, <input type="color">, <input type="date">,
<input type="datetime">, <input type="email">, <input type="file">,
<input type="month">, <input type="number">, <input type="password">,
 <input type="radio">, <input type="range">, <input type="search">,
 <input type="tel">, <input type="text">, <input type="time">,
 <input type="url">, <input type="week">, <select> and <textarea>

source: https://www.w3schools.com/jsref/event_onchange.asp
WhatsApp is built by ReactJS for web and ReactNative for mobile apps.
React has a event binder that reacts to certain changes and feeds back to the DOM.
If you're trying to recreate it using vanilla javascript, use the input tag

A: i'm also working on extension for Whatsapp and this works for me.
const input = document.querySelector('footer ._13NKt.copyable-text.selectable-text[contenteditable="true"]');
            input.innerText = `${value}`;
            const event = new Event('input', {bubbles: true});
            input.dispatchEvent(event);

A: *

*If you don't need any rich text formatting in the "value", then
 is probably overkill which will bring more complications than usage of simple native <input> with similar semantic and native convenient properties like dispatching of events when it's value is changed by user (the input event).

*Sadly, even native input elements do no fire change nor input events when it's value is changed by JS "from the outside".  Complex workarounds for this would involve similar techniques as for the "fake input / conteneditable div": for example using mutationobserver for watching the input's value / div's innerHTML and/or listening to all keyboard, mouse and clipboard events in relevant parts of the document), but…

*…there's stupidly simple workaround for this: just fire the "changed" handler yourself when you know it is necessary.

Using these pieces of information can give us such simple POC with all event handlers attached as (and invoked from) inline attributes ("DOM0", what sometimes even makes quite sense being nice "vanilla" declarative markup):

<input placeholder="type, paste or change text here" id="i" size="40"
oninput="
  // native inline 'input event handler'
  // of native 'text input element' ('this' refers to it)
  console.log(this.value);
">
<button
onclick="
  // 'do something' with the content in a 'programmatic' way:
  i.value += '!!';
  // then invoke the native inline 'input' event handler directly:
  i.oninput();
">append '!!'</button>

Same could be used in higher DOM event handlers, but it would not be as self-explanatory as this POC.

A: Following your example:
var node = document.getElementsByClassName('_13NKt copyable-text selectable-text')[0];

node.value = 'test'

const clickEvent = new KeyboardEvent('keydown', {
    bubbles: true, cancelable: true, keyCode: 13
});

node.dispatchEvent(clickEvent);

I don't know about whatsapp being based on React but assuming it is, you could hook this after mounting the app


text:
Q: Writing a HLSL shader for rescaling floating point textures When using HalfSingle/Single format for my Texture2D, XNA complains that sampling must be set to PointClamp, and this makes my texture look jagged. I am actually using this to pass depth data to the shader, so I am trying to get a better dynamic range than simply using RGBA grayscale values.
If I use Color or Bgra, then I basically only have 255 levels. If I encode the depth values as color pixels, then I can enable antialiasing, but then it doesn't work correcly because the sampler treats each byte/nibble separately when lerping.
Question:
Is there a way to tell HLSL to sample my floating point texture using anti-aliasing filters, or do I need to write the shader myself?

A: It turns out there are two ways to solve this:

*

*Pack .NET 32-bit floats into a RGBA using my own conversion methods, or

*Use SurfaceFormat.Rg32 to pack two 16-bit floats into RGBA (this format supports texture filtering).
I went for the first method.


text:
Q: Soldered wires don't last very long on PCB I am having a very bad experience with soldering wires on my boards. The problem is I have tried wires from various manufactures and suppliers but when I solder them initially they appear good but overtime (within couple of days) the insulation near the solder point on PCB starts cracking or in some case the conductor itself starts breaking.
My soldering technique is

*

*Strip the wire end.

*Tin the wire with solder end and make sure no split ends.

*Solder the wire on the PCB and then cut the bits that might be sticking out.

Any ideas or wire makes that can solve this problem and make the solder last?

A: I do costuming-related electronics, and I have found that using hot glue to hold wires in place significantly reduces odd problems that otherwise occur due to wires moving around and damaging solder joints or breaking.
I suggest applying a dab of glue from a hot glue gun soon after soldering the wires in place. The blob of hot glue should be large enough that it can adhere to the wire's insulation, and should also attach to stable, nonmoving parts of the board, thus making the wire held in place by not just its metal parts, but also by its insulation, and eliminating extraneous wire movement that would otherwise lever against the metal join point of the wire to the board and hence weaken it by metal fatigue.

A: If you're trying to do this properly, then you probably want to use 'board-in' crimps.  The wire is crimped to a little metal fitting, which is then soldered to the board.
For some examples:  http://www.molex.com/molex/products/group?key=direct_solder__boardin_crimp_terminals&channel=products
Soldering stranded cable which is then flexed is always a problem, because the strain at the end of the rigid soldered section is extremely high, which leads to failure.

A: These are effectively extensions to othert answers:
@venny's advice should be noted. This is an extremely effective way of providing strain relief, cost is minimal (two holes*), it does not degrade with time.
Also note my comment on Some_Guy's answer - hot glue is a quick way of constraining wires and components BUT it releases its bond in under a year. Neutral cure (MUST be NC) Silicone Rubber does the same job, takes longer to harden and lasts for decades in most cases.

*

*You can use a single hole as strain relief- pass wire through and then solder to PCB - not as good as 2 holes but MUCH better than 0 holes.

Wire should be thicker than the VERY thin stranded hookup wire which is available. (Was 7 x 0.0076"). These may break if you breathe, bend, look at or think about them.


text:
Q: "callback" keyword in JavaScript Please help in understanding the below code:
// define our function with the callback argument

function some_function(arg1, arg2, callback) {
    // this generates a random number between
    // arg1 and arg2

    var my_number = Math.ceil(Math.random() * (arg1 - arg2) + arg2);

    // then we're done, so we'll call the callback and
    // pass our result
    callback(my_number);
}

// call the function
some_function(5, 15, function(num) {
    // this anonymous function will run when the
    // callback is called
    console.log("callback called! " + num);
});

In the above code,what is the callback keyword.what is the use of this word.
Even there is no function defined with name callback.

A: The gap in logic I think you're having a hard time with is anonymous, unnamed functions. Once upon a time, all functions were named. So code was written like this:
function MemberProcessingFunction() {
  // etc
}

function AdminProcessingFunction() {
  // etc
}

var loginProcessingFunction;

if (usertype == 'BasicMember') {
  loginProcessingFunction = MemberProcessingFunction;
}
else if (usertype == 'Admin') {
  loginProcessingFunction = AdminProcessingFunction;
}
loginProcessingFunction();

Someone thought "This is dumb. I'm only creating those function names to use them in one place in my code. Let's merge that together."
var loginProcessingFunction;

if (usertype == 'BasicMember') {
  loginProcessingFunction = function() {
    // etc
  };
}
else if (usertype == 'Admin') {
  loginProcessingFunction = function() {
    // etc
  };
}
loginProcessingFunction();

This especially saves a lot of time when you're passing a function to another function as an argument. Often, this is used for "callbacks" - occasions where you want to run certain code, but only after a certain indeterminately-timed function has finished its work.
For your top function, callback is the name of the third argument; it expects this to be a function, and it is provided when the method is called. It's not a language keyword - if you did a "find/replace all" of the word "callback" with "batmanvsuperman", it would still work.

A: 'callback' is a function passed as an argument to the 'some_function' method. It is then called with the 'my_number' argument.
when 'some_function' is actually being called as seen below
// call the function
some_function(5, 15, function(num) {
    // this anonymous function will run when the
    // callback is called
    console.log("callback called! " + num);
});

it receives the whole definition of the third function argument. so basically your 'callback' argument has this value below
function(num) {
    // this anonymous function will run when the
    // callback is called
    console.log("callback called! " + num);
}

To understand better how a function can be passed as an argument to another function, take a look at this answer.


text:
Q: Similating a javascript click event on a specific page I know click simulation is a very very standard question but I cannot work out what is going wrong I am applying thefollowing scripts on a microsoft dom https://www.projectoxford.ai/demo/Emotion:
var l2 =  document.getElementsByClassName("imgUrl defaultvalue")[0];

l2.value = "http://i.telegraph.co.uk/multimedia/archive/03442/DEBATE_FIRST_PIC_3442872k.jpg"

function simulate(element, eventName)
{
    var options = extend(defaultOptions, arguments[2] || {});
    var oEvent, eventType = null;

    for (var name in eventMatchers)
    {
        if (eventMatchers[name].test(eventName)) { eventType = name; break; }
    }

    if (!eventType)
        throw new SyntaxError('Only HTMLEvents and MouseEvents interfaces are supported');

    if (document.createEvent)
    {
        oEvent = document.createEvent(eventType);
        if (eventType == 'HTMLEvents')
        {
            oEvent.initEvent(eventName, options.bubbles, options.cancelable);
        }
        else
        {
            oEvent.initMouseEvent(eventName, options.bubbles, options.cancelable, document.defaultView,
            options.button, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
            options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, element);
        }
        element.dispatchEvent(oEvent);
    }
    else
    {
        options.clientX = options.pointerX;
        options.clientY = options.pointerY;
        var evt = document.createEventObject();
        oEvent = extend(evt, options);
        element.fireEvent('on' + eventName, oEvent);
    }
    return element;
}

function extend(destination, source) {
    for (var property in source)
      destination[property] = source[property];
    return destination;
}

var eventMatchers = {
    'HTMLEvents': /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
    'MouseEvents': /^(?:click|dblclick|mouse(?:down|up|over|move|out))$/
}
var defaultOptions = {
    pointerX: 0,
    pointerY: 0,
    button: 0,
    ctrlKey: false,
    altKey: false,
    shiftKey: false,
    metaKey: false,
    bubbles: true,
    cancelable: true
}
var l =  document.getElementsByClassName("demo-bar-submit")[0];

simulate(l,"click");

Every command in the code above is done one at a time in the comand line of the website https://www.projectoxford.ai/demo/Emotion. Is this blocked somehow because nothing happens ? nonetheless when I click the button a change does indeed take place.


text:
Q: How can I use a single model struct for data from multiple APIs/sources in Swift? Let's say I want to get news articles from Site A and Site B, each with a different URL and differently structured JSON payloads. Instead of having two different models to manage, I want to combine them into a single "Articles" data model that takes in data from each of the APIs. I'm wanting to know if this possible using CodingKeys or a dictionary or something.
I want to do something like:
struct Article: Codable, Hashable {
    var title: String
    var site: String
    var date: String
    var image: String
    var url: String
}

and then have CodingKeys to convert the JSON from each site into the shared model. Something like:
extension Article {
    enum CodingKeys: String, CodingKey {
        var title = "title"
        var site = "site_name"
        var date = "date_published"
        var image = "featured_image_url"
        var url = "article_url"
}

But the problem with the above code is that each JSON is different, with different names for the objects. So, then I want to do something like:
enum DataSource {
    case siteA
    case siteB
}

extension Article {
    enum CodingKeys: String, CodingKey {
        switch DataSource {
        case siteA:
            var title = "title"
            var site = "site_name"
            var date = "date_published"
            var image = "featured_image_url"
            var url = "article_url"
        case siteB:
            var title = "article_title"
            var site = "site_name_long"
            var date = "published_date"
            var image = "featured_image"
            var url = "url"
}

and then of course do all the JSONdecoder stuff below that. How can I do this?

A: You can pass parameter into decoder using userInfo. You can control the way of decoding whatever the way you want by setting extra parameter via userInfo. Here i'm passing Article.Site.a/b on site key.
Model definition:
// Model
struct Article: Codable, Hashable {

    var title: String
    var site: String
    var date: String
    var image: String
    var url: String

    enum Site {
        case a
        case b
    }
    enum SiteError : Error {
        case unknownSite
    }
    enum SiteACodingKeys: String, CodingKey {
        case title
        case site
        case date
        case image
        case url
    }
    enum SiteBCodingKeys:String, CodingKey{
        case title = "article_title"
        case site = "article_site"
        case date = "article_date"
        case image = "article_image"
        case url = "article_url"
    }

    init(from decoder: Decoder) throws {

        guard   let key = CodingUserInfoKey(rawValue: "site"),
                let value = decoder.userInfo[key],
                let site =  value as? Site else {
            throw SiteError.unknownSite
        }

        switch site {
        case .a:
            let container = decoder.container(keyedBy: SiteACodingKeys)

            title = try? container.decode(String.self, forKey: .title)
            // decode other properties

        case .b:
            let container = decoder.container(keyedBy: SiteBCodingKeys)

            title = try? container.decode(String.self, forKey: .title)
            // decode other properties
        }
    }
}

Decoding:
// Decoding
let decoder = JSONDecoder()
decoder.userInfo[CodingUserInfoKey(rawValue: "site")] = Article.Site.a // Set `Article.Site.b` while data is from site B
// Now use this decoder to decode JSON


text:
Q: How to open UIWebView from another UIWebView? I have a web view at the bottom of one of my view controllers that contains links.
What I want to do is that when the user clicks on one of the links in the web view it opens a web view that takes up the screen with the with the content of the page the user has clicked on. Or maybe when the user clicks on one of the links in the web view, the user is taken to safari to display the content of the link.
Anyone know how to do this?
Cheers.

Above is a screen shot of the web view with the links that the user can click on..

A: You can use delegate  - webView:shouldStartLoadWithRequest:navigationType: of UIWebView. Before loading each url it will call following delegate -
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

you will able to get request url from request and push new view controller.
More details : https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIWebViewDelegate_Protocol/index.html#//apple_ref/occ/intfm/UIWebViewDelegate/webView:shouldStartLoadWithRequest:navigationType:

A: Try this:
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
{
    NSURL *requestURL =[ request URL ];
    if ( ( [ [ requestURL scheme ] isEqualToString: @"http" ] || [ [ requestURL scheme ] isEqualToString: @"https" ] || [ [ requestURL scheme ] isEqualToString: @"mailto" ])
        && ( navigationType == UIWebViewNavigationTypeLinkClicked ) )
    {
        return ![ [ UIApplication sharedApplication ] openURL: requestURL] ;
    }
    return YES;
}


text:
Q: Poisson Process conditional probability I have the problem
"Suppose that the number of calls arriving to a telesales call centre follows
a Poisson process with intensity λ = 6 calls per hour. Each caller makes a
purchase with probability 0.4.

Suppose now  that 5 calls arrived in the first hour. What is the probability
that 3 of them made a purchase?"

I have set $X_t =$ number of calls by time $ t $ and  $Y_t =$ number of purchases made by time $ t $
So I have $Y_t \sim Po(0.4(6)t)$ and I found that arrival time is exponentially distributed and from that i have the expected arrival $\mu = \frac{1}{2.4}=0.4167$
I then found $$P(Y_1=3)= 0.20914 $$
Im not really sure how to use all this information to get the answer I want, I assume the answer is $$P(Y_1=3|X_1=5)$$ but not sure what to do

A: Since you already know that $5$ people called you no longer need to use the Poisson distribution. Try answer this question: "$5$ calls arrived in the first hour. Giver that each caller has a $0.4$ probability to make a purchase, what is the probability that $3$ of them made a purchase." If you are still unable to do it I am happy to provide a full solution.


text:
Q: Change Row Color in PHP data table by Date Today : <?php echo date("m/d/Y"); ?>
<ph>ISSUED BOOKS | DUE BOOKS</ph>

        id
        Officer
        Member_ID
        Book_ID
        Issued_date
        Due_date
        Remarks

      <?php do { ?>

          <?php echo $row_rsissuedbooks['id']; ?>
          <?php echo $row_rsissuedbooks['Officer']; ?>
          <?php echo $row_rsissuedbooks['Member_ID']; ?>
          <?php echo $row_rsissuedbooks['Book_ID']; ?>
          <?php echo $row_rsissuedbooks['Issued_date']; ?>
          <?php echo $row_rsissuedbooks['Due_date']; ?>
          <?php echo $row_rsissuedbooks['Remarks']; ?>

        <?php } while ($row_rsissuedbooks = mysql_fetch_assoc($rsissuedbooks)); ?>

i want to color the rows Due_date if due_date is greater than today (php 1st line in code)
im not good in english..
sorry for that, i hope you will understand..

A: Something like this will work.
  <?php do {
  $style = "";
  if ($row_rsissuedbooks['Due_date'] > date("m/d/Y")){
    $style = "style='background:#FF0000;'";
  }
  ?>

      <?php echo $row_rsissuedbooks['id']; ?>
      <?php echo $row_rsissuedbooks['Officer']; ?>
      <?php echo $row_rsissuedbooks['Member_ID']; ?>
      <?php echo $row_rsissuedbooks['Book_ID']; ?>
      <?php echo $row_rsissuedbooks['Issued_date']; ?>
      <td <?php echo $style;?>><?php echo $row_rsissuedbooks['Due_date']; ?>
      <?php echo $row_rsissuedbooks['Remarks']; ?>

    <?php } while ($row_rsissuedbooks = mysql_fetch_assoc($rsissuedbooks)); ?>

A: Try this:
<?php echo $row_rsissuedbooks['Issued_date']; ?>
<?php
    echo "time())
    {
        echo " style=\"background-color:#00FF00\"";
    }
    echo ">".$row_rsissuedbooks['Due_date']."	";
?>
<?php echo $row_rsissuedbooks['Remarks']; ?>


text:
Q: How to access RESPONSE data from an AJAX Get in JQuery This is my first attempt at using an AJAX GET to pull data and it is really causing me a nightmare. I have used POST loads of times and assumed accessing the data would be the same basic process, but no matter what I try I always end up with "Undefined".
This is the code I have been trying to make the GET work in my script;

$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "/buytoken/public/api/stage?secret=***************",
        cache: false,
        dataType: "json",
            success : function(response){
            var len = response.length;
            for(var i=0; i<len; i++){
            var sold = response[i].progress;
            }
            alert(sold);
            }
    });
});

This is then what the response should be;
{
"success": true,
"response": {
"ico": "running",
"total": "8,000,000",
"total_amount": "800,000",
"sold": "1,599,300",
"sold_amount": "159,930",
"progress": 20,
"price": "0.1",
"start": "2022-02-28 00:01:00",
"end": "2022-05-31 00:01:00",
"timezone": "Europe/London",
"min": "500",
"max": "4000000",
"soft": "400000",
"soft_amount": "40,000",
"hard": "800000",
"hard_amount": "80,000"
}
}
The script that I am trying to access is on the same webserver.
It is coming from a third-party piece of software that we are running on the site. The documentation states "Application provides some specific internal live data in JSON"
So, we should be getting JSON back.
I need to access just two pieces of data "sold_amount" and "progress" which I want to load into variables in the Success callback.
I really would be grateful if somebody could explain or better still show me how this is supposed to work because I am really banging me head against the wall on this.
Also, if I need to add any extra bits like error handling then please point that out.
Thanks to anybody who responds to this..


text:
Q: Excel IRR: Can I use range reference inside IRR with math inside {}? Good morning. In post "Excel IRR: can I use it referencing a combination of cells and fixed numbers? IRR({-10,11+A2})" is said we can math inside {} using CHOOSE function. But if I have first payment (investment) in B1, 100, and rest of income in a range, B2:B6, (10,10,10,10,70), then, when I try
=IRR(CHOOSE({1,2};-B1,E2:E6))
I receive a #¡VALUE! result with ENTER or CSE. I use an spanish version of Excel 2013, where separator is ";" instead ",". I have try
=IRR(CHOOSE({1,2};(-B1,E2:E6)))
without success. Ideally I would like make some additional calculations in first cell, for example -B1+cell1+cell2 ...
Thank in advance


text:
Q: Create Task automatically when Pull request is created in Bitbucket My project is hosted in Bitbucket and version controlled through Git. Is there a way to automatically create tasks when a PR is created? I have heard of Bot integrations with BitBucket but couldn't find much about this on the internet. Is this possible? I would appreciate some guidance on how this can be achieved.
P.S: The tasks I would want to create are the same with every PR - mainly like a checklist that ensures commits are squashed, its been unit tested and so on..


text:
Q: How to setup Eclipselink with JPA? The Eclipselink documentation says that I need the following entries in my pom.xml to get it with Maven:
<dependencies>
  <dependency>
    <groupId>org.eclipse.persistence</groupId>
    <artifactId>eclipselink</artifactId>
    <version>2.0.0</version>
    <scope>compile</scope>
       ...
  </dependency>
<dependencies>
      ...
<repositories>
  <repository>
     <id>EclipseLink Repo</id>
     <url>http://www.eclipse.org/downloads/download.php?r=1&nf=1&file=/rt/eclipselink/maven.repo</url>
  </repository>
      ...
</repositories>

But when I try to use @Entity annotation NetBeans tells me, that the class cannot be found. And indeed: there is no Entity class in the javax.persistence package from Eclipselink.
How do I have to setup Eclipselink with Maven?

A: Just add the following to your pom.xml.
Now these artifats are in the maven repositories, so no need to add any <repository>
 <!-- JPA  -->
 <dependency>
    <groupId>org.eclipse.persistence</groupId>
    <artifactId>eclipselink</artifactId>
    <version>2.5.1</version>
</dependency>
<dependency>
    <groupId>org.eclipse.persistence</groupId>
    <artifactId>javax.persistence</artifactId>
    <version>2.0.0</version>
</dependency>

Or if you are using a Java EE application server use org.eclipse.persistence.jpa:org.eclipse.persistence, as it doesn't include dependecies that are already on the server.
 <!-- JPA for Java EE application servers  -->
 <dependency>
  <groupId>org.eclipse.persistence</groupId>
  <artifactId>org.eclipse.persistence.jpa</artifactId>
  <version>2.5.1</version>
  <scope>provided</scope>
</dependency>
<dependency>
  <groupId>org.eclipse.persistence</groupId>
  <artifactId>javax.persistence</artifactId>
  <version>2.0.0</version>
  <scope>provided</scope>
</dependency>

A: When I look into my local maven repository, org.eclipse.persistence:eclipselink does indeed contain the persistence api, at least for version 2.0.0-SNAPSHOT of eclipselink.
But there is another set of dependencies in the eclipselink repository that are a bit more modularized. These are the dependencies I am using in a current project:
<!-- persistence api -->
<dependency>
    <groupId>org.eclipse.persistence</groupId>
    <artifactId>javax.persistence</artifactId>
    <version>2.0.0</version>
    <scope>provided</scope>
</dependency>
<!-- jpa implementation -->
<dependency>
    <groupId>org.eclipse.persistence</groupId>
    <artifactId>org.eclipse.persistence.jpa</artifactId>
    <version>2.0.2</version>
    <scope>provided</scope>
</dependency>

Note that scope is set to provided since I deploy to glassfish which already contains eclipselink.

A: The eclipselink artifact doesn't provide the JPA 2.0 API, you need to add javax.persistence:
<repositories>
  <repository>
    <id>eclipselink</id>
    <url>http://www.eclipse.org/downloads/download.php?r=1&nf=1&file=/rt/eclipselink/maven.repo/</url>
  </repository>
</repositories>
<dependencies>
  <dependency>
    <groupId>org.eclipse.persistence</groupId>
    <artifactId>eclipselink</artifactId>
    <version>2.0.0</version>
    <scope>provided</scope><!-- since I'm running inside a Java EE container -->
  </dependency>
  <dependency>
    <groupId>org.eclipse.persistence</groupId>
    <artifactId>javax.persistence</artifactId>
    <version>2.0.0</version>
    <scope>provided</scope><!-- since I'm running inside a Java EE container -->
  </dependency>
  ...

I recommend to use the non OSGI EclipseLink jar for the sake of simplicity.

A: You can try to add
<dependency>
   <groupId>org.eclipse.persistence</groupId>
   <artifactId>javax.persistence</artifactId>
   <version>2.0.0</version>
   <scope>compile</scope>
</dependency>


text:
Q: Brightness Saturation circular pad in Swift Preamble
I'm trying to create a rounded Brightness Saturation pad using SwiftUI both for indication (from a given color, show the cursor position) and use (by moving the cursor, obtain the resulting color).
I apologize for my bad English .
Presentation code
Firstly I draw the Circle using two Circle elements, filled with a LinearGradient element and the luminosity bland mode.
    public var body: some View {
        ZStack(alignment: .top) {
            //MARK: - Inner Color circle
            Group {
                Circle()
                    .fill(
                        LinearGradient(
                            colors: [self.minSaturatedColor, self.maxSaturatedColor],
                            startPoint: .leading,
                            endPoint: .trailing
                        )
                    )
                Circle()
                    .fill(
                        LinearGradient(
                            colors: [.white, .black],
                            startPoint: .top,
                            endPoint: .bottom
                        )
                    )
                    .blendMode(.luminosity)
            }
            .frame(width: self.diameter, height: self.diameter, alignment: .center)
            .gesture(
                DragGesture(minimumDistance: 0, coordinateSpace: .local)
                    .onChanged(self.updateCursorPosition)
                    .onEnded({ _ in
                        self.startIndication = nil
                        self.changed(self.finalColor)
                    })
            )

            //MARK: - Indicator

            Circle()
                .stroke(Color.black, lineWidth: 2)
                .foregroundColor(Color.clear)
                .frame(width: self.cursorDiameter, height: self.cursorDiameter, alignment: .center)
                .position(cursorPosition)
        }
        .frame(width: self.diameter, height: self.diameter, alignment: .center)
    }

Theory
Here's the theory above the mixtures of the color saturation with the brightness.

I'm not sure that this is the correct approach, but it seems so because it produces the following circle having (probably) all the shades:

Problem 1
The simplified code that I used to determine the Cursor position (from a given color) is:
    public var cursorPosition: CGPoint {
        let hsb = self.finalColor.hsba
        let x: CGFloat = hsb.saturation * self.diameter
        let y: CGFloat = hsb.brightness * self.diameter

        // Adjust the Apple reversed ordinate
        return CGPoint(x: x, y: self.diameter - y)
    }

Unfortunately, this it seems not correct because by giving a certain color (I.e. #bd4d22) it makes the pointer placed in a wrong position.

Problem 2
There's also another problem: the component should allow to move the cursor and so update the finalColor State property with the correct amount of brightness and saturation.
    private func updateCursorPosition(_ value: DragGesture.Value) -> Void {
        let hsb = self.baseColor.hsba

        let saturation = value.location.x / self.diameter
        let brightness = (0 - value.location.y + self.diameter) / self.diameter

        self.finalColor = Color(
            hue: hsb.hue,
            saturation: saturation,
            brightness: brightness
        )
    }

yet the result is not what expected because, event tough the cursor follows the point (meaning that the computed value is correct), the resulting color is not what rendered behind the pointer!
Example pt. 1

Here, as you can see, the full saturated color (that should theoretically be 2π of the circumference) is not correct.
Example pt. 2

Here, as you can see, there's an issue by going outside of the circle.
Question

*

*Can anyone explain where am I failing?

*Can anyone help me blocking the updateCursorPosition resulting color value, if the cursor is dragged out of the circle?

*Am I doing something else in the wrong way?

Thank you for the patience !

Ps. To accomplish this, I take clue form what done by Procreate and what asked here Circular saturation-brightness gradient for color wheel

A: Okay, this took a while as it wasn't one thing. I ended up pulling your code apart and rebuilding it a little more simply, as well as refactoring the indicator from the color view. To fix the indicator, I took inspiration from this answer. Give it a bump.
As to the color wheel itself, I simplified it into a Circle() with an overlay of the second Circle(). Getting the colors straight took a lot more time as I am not a designer, so I had to work through dealing with the colors less intuitively. I had a two realizations while dealing with this.
To handle the maximum and minimum saturations, the only variable that could be used was the hue. The brightness and saturation were fixed, either 0 or 1 for saturation and 1 for brightness, otherwise the base color gradient was off.
That caused me to have to deal with the brightness gradient. The color was already at maximum brightness, so putting a gradient from white to black rendered incorrectly, yet again. Another realization I had was that the brightness gradient should go from clear to black. That resolved the color issues. The code is below and commented.
The Color Wheel:
struct ColorWheelView: View {

    @State private var position: CGPoint
    @Binding public var selectedColor: Color

    private var saturation: CGFloat {
        position.x / diameter
    }
    private var brightness: CGFloat {
        (diameter - position.y) / diameter
    }

    private let diameter: CGFloat
    private let cursorDiameter: CGFloat

    private let baseHSB: (hue: Double, saturation: Double, brightness: Double, alpha: Double)
    private let minSaturatedColor: Color
    private let maxSaturatedColor: Color

    public init(
        //there needs to be an intitial fixed color to set the hue from
        color: Color,
        //this returns the selected color. It can start as anything as it is set to
        //color in .onAppear()
        selectedColor: Binding<Color>,
        diameter: CGFloat = 200,
        cursorDiameter: CGFloat = 20
    ) {
        let hsb = color.hsba
        // Because the view uses the different parts of color, it made sense to just have
        // an hsba here. I would consider making this its own Type just for readability.
        // The only thing that this entire variable is used for is setting the initial selected
        // color. Otherwise I could have just kept the hue.
        baseHSB = Color(hue: color.hsba.hue, saturation: color.hsba.saturation, brightness: color.hsba.brightness).hsba

        // This sets the initial indicator position to be at the correct place on the wheel as
        //The initial color sent in, including the initial saturation and brightness.
        _position = State(initialValue: CGPoint(x: hsb.saturation * diameter, y: diameter - (hsb.brightness * diameter)))
        // This is the return color.
        _selectedColor = selectedColor
        // self is only needed to avoid confusion for the compiler.
        self.diameter = diameter
        self.cursorDiameter = cursorDiameter
        // Note these are set to maximum brightness.
        minSaturatedColor = Color(hue: baseHSB.hue, saturation: 0, brightness: 1)
        maxSaturatedColor = Color(hue: baseHSB.hue, saturation: 1, brightness: 1)
    }

    var body: some View {
        VStack {
        Circle()
            .fill(
                LinearGradient(
                    colors: [self.minSaturatedColor, self.maxSaturatedColor],
                    startPoint: .leading,
                    endPoint: .trailing
                )
            )
            .overlay(
                Circle()
                    .fill(
                        LinearGradient(
                            // Instead of a gradient of white to black, this is clear to black
                            // as the saturation gradients are at maximum brightness already.
                            colors: [.clear, .black],
                            startPoint: .top,
                            endPoint: .bottom
                        )
                    )
                    .blendMode(.luminosity)
            )
            .overlay(
                IndicatorView(position: $position, diameter: diameter, cursorDiameter: cursorDiameter)
            )
            .frame(width: self.diameter, height: self.diameter)
            .onAppear {
                // Sets the bound color to the original color.
                selectedColor = Color(hue: baseHSB.hue, saturation: baseHSB.saturation, brightness: baseHSB.brightness, opacity: baseHSB.alpha)
            }
            .onChange(of: position) { _ in
                // When position changes, this changes the saturation and brightness.
                selectedColor = Color(
                    hue: baseHSB.hue,
                    saturation: saturation,
                    brightness: brightness
                )
            }
        }
    }
}

The Indicator:
struct IndicatorView: View {

    @Binding var position: CGPoint
    private let diameter: CGFloat
    private let cursorDiameter: CGFloat
    private let radius: CGFloat
    private let center: CGPoint

    init(position: Binding<CGPoint>, diameter: CGFloat, cursorDiameter: CGFloat) {
        _position = position
        self.diameter = diameter
        self.cursorDiameter = cursorDiameter
        self.radius = diameter / 2
        // the center of the circle is the center of the frame which is CGPoint(radius, radius)
        self.center = CGPoint(x: radius, y: radius)
    }
    var body: some View {
        VStack {
            Circle()
                // This circle is simply to keep the indicator aligned with the ColorWheelView
                .fill(Color.clear)
                .overlay(
                    Circle()
                        .stroke(Color.black, lineWidth: 2)
                        .foregroundColor(Color.clear)
                        .frame(width: cursorDiameter, height: self.cursorDiameter)
                        .position(position)
                        .gesture(DragGesture()
                            .onChanged { value in
                                updatePosition(value.location)
                            }
                        )
                )
                .frame(width: diameter, height: diameter)
        }
        .onAppear {
            updatePosition(position)
        }
    }

    private func updatePosition(_ point: CGPoint) {
        let currentLocation = point
        let center = CGPoint(x: radius, y: radius)
        let distance = center.distance(to:currentLocation)
        // This triggers if the drag goes outside of the circle.
        if distance > radius {
            let overDrag = radius / distance
            //These coordinates are guaranteed inside of the circle.
            let newLocationX = (currentLocation.x - center.x) * overDrag + center.x
            let newLocationY = (currentLocation.y - center.y) * overDrag + center.y
            self.position = CGPoint(x: newLocationX, y: newLocationY)
        }else{
            self.position = point
        }
    }
}

extension CGPoint {
    //This is simply the Pythagorean theorem. Distance is the hypotenuse.
    func distance(to point: CGPoint) -> CGFloat {
        return sqrt(pow((point.x - x), 2) + pow((point.y - y), 2))
    }
}

Also, as a side note, most of the variables you had were constants and should be lets and not vars. Anything internal to the struct should be private. @State variables are always private.


text:
Q: How to use Raycast methods in RealityKit? There are three ways about Detecting Intersections in RealityKit framework, but I don't know how to use it in my project.
1.
func raycast(origin: SIMD3<Float>,
          direction: SIMD3<Float>,
             length: Float,
              query: CollisionCastQueryType,
               mask: CollisionGroup,
         relativeTo: Entity?) -> [CollisionCastHit]

2.
func raycast(from: SIMD3<Float>,
               to: SIMD3<Float>,
            query: CollisionCastQueryType,
             mask: CollisionGroup,
       relativeTo: Entity?) -> [CollisionCastHit]

3.
func convexCast(convexShape: ShapeResource,
               fromPosition: SIMD3<Float>,
            fromOrientation: simd_quatf,
                 toPosition: SIMD3<Float>,
              toOrientation: simd_quatf,
                      query: CollisionCastQueryType,
                       mask: CollisionGroup,
                 relativeTo: Entity?) -> [CollisionCastHit]

A: Simple Ray-Casting

If you want to find out how to position a model made in Reality Composer into a RealityKit scene (that has a detected horizontal plane) using Ray-Casting method, use the following code:

import RealityKit
import ARKit

class ViewController: UIViewController {

    @IBOutlet var arView: ARView!
    let scene = try! Experience.loadScene()

    @IBAction func onTap(_ sender: UITapGestureRecognizer) {

        scene.steelBox!.name = "Parcel"

        let tapLocation: CGPoint = sender.location(in: arView)
        let estimatedPlane: ARRaycastQuery.Target = .estimatedPlane
        let alignment: ARRaycastQuery.TargetAlignment = .horizontal

        let result: [ARRaycastResult] = arView.raycast(from: tapLocation,
                                                   allowing: estimatedPlane,
                                                  alignment: alignment)

        guard let rayCast: ARRaycastResult = result.first
        else { return }

        let anchor = AnchorEntity(world: rayCast.worldTransform)
        anchor.addChild(scene)
        arView.scene.anchors.append(anchor)

        print(rayCast)
    }
}

Pay attention to a class ARRaycastQuery. This class comes from ARKit, not from RealityKit.
Convex-Ray-Casting

A Convex-Ray-Casting methods like raycast(from:to:query:mask:relativeTo:) is the op of swiping a convex shapes along a straight line and stopping at the very first intersection with any of the collision shape in the scene. Scene raycast() method performs a hit-tests against all entities with collision shapes in the scene. Entities without a collision shape are ignored.

You can use the following code to perform a convex-ray-cast from start position to end:
import RealityKit

let startPosition: SIMD3<Float> = [0, 0, 0]
let endPosition: SIMD3<Float> = [5, 5, 5]
let query: CollisionCastQueryType = .all
let mask: CollisionGroup = .all

let raycasts: [CollisionCastHit] = arView.scene.raycast(from: startPosition,
                                                          to: endPosition,
                                                       query: query,
                                                        mask: mask,
                                                  relativeTo: nil)

guard let rayCast: CollisionCastHit = raycasts.first
else { return }

print(rayCast.distance)      /* The distance from the ray origin to the hit */
print(rayCast.entity.name)   /* The entity's name that was hit              */

A CollisionCastHit structure is a hit result of a collision cast and it lives in RealityKit's scene.
P.S.

When you use raycast(from:to:query:mask:relativeTo:) method for measuring a distance from camera to entity it doesn't matter what an orientation of ARCamera is, it only matters what its position is in world coordinates.


text:
Q: ImDisk: Create physical memory drive (not virtual memory drive) from command-line I'm using ImDisk to create a virtual drive in Windows 7. I use it as a temporary drive for documents, and it will be created every time the computer/windows restarts. This is working okay; however, I want to create the drive in physical memory instead of virtual memory.
In the configuration tab of Windows there is the 'ImDisk Virtual Disk Driver'. With this tool it is possible to create virtual disks in physical memory (see also image below), but the command-line version doesn't have a physical memory option or I can't figure out.

Is it possible to create virtual disks in physical memory at the command line?
This is the command-line batch code that I currently using:
imdisk -a -s 512M -m Z: -p "/fs:ntfs /v:RAMDISK /A:512 /q /c /y"

How do I do this?

A: I wanted this on a server where permissions are a bit more complex, so here's the full command line for getting a physical RAM disk setup with ImDisk, creating a directory (so you can assign more complex permissions - there are limitations on full drive access), and assigning modify permissions to a group by its name.
imdisk -a -o awe -s 512M -m R: -p "/fs:ntfs /q /y"
cd R:
R:
mkdir r
icacls "R:\r" /grant Web:(OI)(CI)M

So it's saying to:

*

*-a: Make a virtual disk

*-o awe: In physical RAM

*-s 512M: 512 MB in size

*-m R:: Named R

*-p...: Tells it to format the disk with default parameters, quietly.

It switches to R, makes the dir r, and then icacls grants permissions to the group "Web" (if you wanted a user, just use their name here instead, no syntax difference), (OI)(CI) every file and folder inside should inherit this permission M Modify, which is read, list, write, create/delete/modify.

A: Add parameter: -o awe
From: http://reboot.pro/topic/2148-news/page-3 Posted 28 March 2013 - 06:50 PM


text:
Q: Quero fazer um conversor de decimal para binário sem usar itoa() ou vetores em C O meu código dá certo até um certo ponto. Quando forneço valores acima de 1023 para num, o programa dá errado, abaixo de 1023 o programa funciona perfeitamente. Alguém sabe o que pode ser?
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int bin = 0, num = 0, resp = 0, cont = 0;
    printf("digite um numero\n");
    scanf("%d", &num);
    do
    {
        bin = (bin * 10) + (num % 2);
        num = num / 2;
        cont++;
    }
    while (num > 0);
    do
    {
        cont--;
        resp = (resp * 10) + (bin % 2);
        bin = (bin - (bin % 2)) / 10;
    }
    while (cont > 0);
    printf("%d", resp);
    return 0;
}

A: Acontece que como está a guardar a representação binária num inteiro, rapidamente passa a capacidade de representação do mesmo e gera um overflow.
Observe o numero 1200 em binário:
10010110000

Veja o mesmo numero em inteiro, formatado visualmente para simplificar a leitura:
10,010,110,000

Que são 10 biliões, e claramente fora da gama de inteiros que vai até 2,147,483,647.
Assim, a única coisa que precisa de fazer é alterar o tipo para um com mais representação, como o unsigned long long:
int main()
{
    unsigned long long bin = 0, num = 0, resp = 0, cont = 0;
    printf("digite um numero\n");
    scanf("%lld", &num); //tipo lld
    ...
    printf("%lld", resp); //tipo lld
    return 0;
}

Veja o código a funcionar no Ideone
Alerto que no entanto, irá ter o mesmo problema se tentar converter números um pouco maiores, tal como 1000000, pois a representação binária cresce demasiado rápido. Para contornar esse problema só mesmo guardando a representação numa string, que poderá ter o tamanho que quiser.


text:
Q: javascript error - node was not found : replaceChild I am trying to swap two array in javascript. While the replacement comes to the last iteration, I am getting "NotFoundError: Node was not found" in the call of parent.replaceChild(item2,item1). Please help me what mistake I have committed.
    function sortTable(col){
            if($("loacte-resultsTable") == null || $("loacte-resultsTable") == undefined){
            return false;
        }

    if (lastSort == col) {
        // sorting on same column twice = reverse sort order
        absOrder ? absOrder = false : absOrder = true
    }
    else{
        absOrder = true
    }
    lastSort = col;

    try{
        var loacteResultsTable = $("loacte-resultsTable").getElementsByTagName("TBODY")[0];
        var loacteResultsTableTR = loacteResultsTable.getElementsByTagName("TR");
        allTR = loacteResultsTableTR;
    } catch (e) {
        return false;
    }

    // allTR now holds all the rows in the dataTable
    totalRows = allTR.length;
    colToSort = new Array();        //holds all the cells in the column to sort
    colArr = new Array();           //holds all the rows that correspond to the sort cell
    copyArr = new Array();          //holds an original copy of the sort data  to match to colArr
    resultArr = new Array();        //holds the output

    allNums = true
    allDates = true

    //store the original data
    //remember that the first row - [0] -  has column headings
    //so start with the second row - [1]
    //and load the contents of the cell into the array that will be sorted
    for (x=0; x < totalRows; x++){
        var data = setDataType(allTR[x].childNodes[col].innerText);
        if(typeof data!="undefined"){
            colToSort[x] = setDataType(allTR[x].childNodes[col].innerText);
        }else{
            colToSort[x] = setDataType(allTR[x].childNodes[col].textContent);
        }
        colArr[x] = allTR[x];
    }

    //make a copy of the original
    for (x=0; x<colToSort.length; x++){
        copyArr[x] = colToSort[x];
    }
    //sort the original data based on data type
    if (allNums){
        colToSort.sort(numberOrder);
    } else if (allDates){
        colToSort.sort(dateOrder);
    } else {
        colToSort.sort(textOrder);
    }

    //match copy to sorted
    for(x=0; x<colToSort.length; x++) {
        for(y=0; y<copyArr.length; y++) {
            if (colToSort[x] == copyArr[y]) {
                boolListed = false
                //search the ouput array to make sure not to use duplicate rows

                for(z=0; z<resultArr.length; z++) {
                    if (resultArr[z]==y) {
                        boolListed = true
                        break;
                    }
                }

                if (!boolListed){
                    resultArr[x] = y
                    break;
                }
            }
        }
    }

    //now display the results - it is as simple as swapping rows
    for (x=0; x<resultArr.length; x++) {
        //allTR[x].swapNode(colArr[resultArr[x]])
        swapNodes(allTR[x],colArr[resultArr[x]]);
    }
    function swapNodes(item1,item2)
    {
        var itemtmp = item1.cloneNode(1);
        var parent = item1.parentNode;
        item2 = parent.replaceChild(itemtmp,item2);
        parent.replaceChild(item2,item1);
        parent.replaceChild(item1,itemtmp);
        itemtmp = null;
    }

}

The call to the sortTable method is from synch().This is the UI part coded in JS:
function synch(){

    var loacteResults = $('loacte-results');
    var loacteResultsTable = $('loacte-resultsTable');

    tab = loacteResults.getElementsByTagName('TABLE')[0];
    loacteResults.removeChild(tab);

    var updatedResults =
                '
' +
                '
' +
                    '
' +
                        'Site ID	' +
                        'Store Name	' +
                        'Agent Code	' +
                        'Address	' +
                        'City, State	' +
                        'Phone	' +
                        'Hours	' +
                        'Deleted	' +
                        'Priority 	' +
                        'Est.Dist.(miles) 	' +
                    '
' +
                '
' ;

    if(tr == '')
        updatedResults = updatedResults + '

No Stores to display

';
    else
        updatedResults = updatedResults + '
' + tr +  '

';

    loacteResults.innerHTML = updatedResults;

}

A: In the third parent.replaceChild line item1 is no longer is on the page, since it has been replaced with item2.
Your code broken down:
function swapNodes(item1,item2)
{
    var itemtmp = item1.cloneNode(1); //create a copy of item 1
    var parent = item1.parentNode; //set a reference to the parent
    item2 = parent.replaceChild(itemtmp,item2); //replace item2 with the copy of item1 and store the old child in item2
    parent.replaceChild(item2,item1); //replace item1 with item2
    parent.replaceChild(item1,itemtmp); //this line is redundant. <-- item1 no longer is on the page.
    itemtmp = null;
}


text:
Q: IE9 rendering css3 Hi recently I have started to develop a website which uses a few basic css3 features which I am sure that are supported in IE9 because I've checked. No matter what I did IE9 seemed not to render any of the css3 properties not even when I was using ms prefix.
After I did some reasearch I found a question here on stackoverflow that dealt with a similar problem to mine and someone offered a solution to that problem.The person said to add this line in the head tag:
<meta http-equiv="X-UA-Compatible" content="IE=9" />

After I added this everything seemed to work. What I would is an explanation as to why do I have to use this to make css3 features work in IE9 and what is it's meaning?
I am still prety new to web development and I tried to learn html/css/javasript/php/mysql in about 6 months. While I am now capable of creating functional websites alot of gaps seem to be left in my head so I hope this is not a very basic question.

A: This is the document compatibility.
It's all explained in this article - http://msdn.microsoft.com/en-us/library/cc288325%28v=vs.85%29.aspx


text:
Q: How to bind a GridView after calling a WebMethod? At the moment I am doing drag & drop to GridView rows which sends the new row order to a WebMethod in order to update the database according to these new values.
So, how can I update the GridView in the web form after calling the WebMethod? Considering that I can't access to any of the webform elements from a WebMethod.
Web Method:
[WebMethod]
public static void GridViewCarriersReorders(string Reorder)
{
    Boolean result;
    string[] ListID = Reorder.Split('|');
    transactions tr = new transactions();
    result = tr.updateLcrPriorities(ListID);
    //updateGridViewCarriers(); //SOMETHING LIKE THIS IS NEEDED TO DO THE BINDING
}

Thanks a lot for your help and comprehension.
UPDATE: This is how I am calling the webmethod:
$.ajax({
    type: "POST",
    url: "lcrP.aspx/GridViewCarriersReorders",
    data: '{"Reorder":"' + strorder + '"}',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    async: true,
    cache: false,
    success: function (msg) {
        $.jGrowl("The Carriers priority was successfully updated", { theme: "succeeded" });
    }
})

A: If you put an UpdatePanel around the gridview, you can call a postback only for it:
success: function (msg) {
        $.jGrowl("The Carriers priority was successfully updated", { theme: "succeeded" });
        __doPostBack('UpdatePanel1', '');
    }

EDIT:
As you found by yourself, i missed writing that in the OnLoad event you should force databind of the grid:
void OnLoad(EventArgs e) {
    base.OnLoad(e);
    myGrid.DataBind();
}

As an alternative, if your grid is bound to a xDataSource control you can disable the viewstate of the grid, and if it will be forced to DataBind at each postback.


text:
Q: How do I reuse a select list in Knockout.js for better performance? I have a view that shows small edit forms for all employees at a given location, one below the other. One of the controls shown for each employee is a select list of 150 cities. A change event on that select list transfers the employee to another location.
<select data-bind="options: $root.locations(),
    optionsCaption: 'Please choose...',
    optionsText: function(item) { return item.locationname(); },
    optionsValue: 'uuid',
    value: reassign_to_locationuuid,
    event: {change: $root.reassignLocation}">
</select>

This works fine, but the largest location has 79 people, and when that page loads, it takes a while -- nothing crazy, only about 10 seconds, and I have a nice hypnotic loading animation in place while the user waits. But I wonder how to improve load speed and my Knockout-fu, before this becomes a bigger problem.
When I load the page with these select lists commented out, it renders in <2s. The slowdown is from [my bad design of] having KO repeat the work of building a select list of 150 items 79 times. Since they are the exact same lists, with each just bound to a different employee's reassign_to_locationuuid property, I wonder if it can be made to run faster.
This has been a tough one to Google because:

*

*searching with multiple select lists in knockout.js brings up a ton of info on select lists that allow multiple selections

*searching with reuse template in knockout.js brings up a lot of helpful info on named templates

I tried to go with a named template, but learned that those seem to be for situations where you want to pass different data into the same layout -- I'm passing the same data each time.
When I searched for knockout.js performance I found Ryan Niemeyer's  http://www.knockmeout.net/2012/06/knockoutjs-performance-gotcha-3-all-bindings.html
To try to determine whether the problem described there (all bindings firing at once) was my issue too, I downloaded Michael Best's knockout-repeat from https://github.com/mbest/knockout-repeat and changed my select lists to use that approach:
<select data-bind="value: reassign_to_locationuuid,
                   event: {change: $root.reassignLocation}">
    <option value="">Please choose...</option>
    <option data-bind="repeat: $root.locations()"
            data-repeat-bind="attr: { value: $item().uuid() },
                              text: $item().locationname()">
    </option>
</select>

...but the timings were near-identical, so that doesn't seem to be it.
Thank you Michael & Ryan for answering Knockout with repeat binding: Initially selected value being overwritten -- as I found that solution yesterday and it helped me get the knockout-repeat test above to work (it's just not any faster).
Given that the reassign_to_locationuuid property starts out as null for every employee when the page loads, and that the first change to any one of these lists will navigate away from this page when the reassignLocation event fires, I feel like I'm doing something wrong.

*

*In this situation, can I get KO to do most of its work only once instead of 79 times?

*Am I using KO for this part when I shouldn't be? Maybe I don't need all the rich KO binding goodness here in these lists?

*Could some of this list-building happen asynchronously somehow?

A: Yes, it's possible to reuse the same location list for every person. I've simplified your task by stripping some properties off and written the example implementation of your problem.
http://jsfiddle.net/PqqHK/
300 locations and 100 persons are being loaded only once (onload). Location list for every person does not need to be rendered for every person separately, since person data keeps and tracks location id and proper location item in select is selected on person change.

        Id:

        Name:

        Location:
        <select data-bind="options: $root.locations,
            optionsValue: 'id',
            optionsText: 'name',
            value: location"></select>
        Select another value to relocate!

Person constructor:
function Person(id, name, locId) {
    this.id = id;
    this.name = name;
    this.location = ko.observable(locId);
}

Model:
ko.applyBindings(vm = {
    persons: persons,
    locations: locations,
    selectedPerson: ko.observable()
});