text:
Q: How to mock streams in NodeJS I'm attempting to unit test one of my node-js modules which deals heavily in streams. I'm trying to mock a stream (that I will write to), as within my module I have ".on('data/end)" listeners that I would like to trigger. Essentially I want to be able to do something like this:
var mockedStream = new require('stream').readable();

mockedStream.on('data', function withData('data') {
  console.dir(data);
});

mockedStream.on('end', function() {
  console.dir('goodbye');
});

mockedStream.push('hello world');
mockedStream.close();

This executes, but the 'on' event never gets fired after I do the push (and .close() is invalid).
All the guidance I can find on streams uses the 'fs' or 'net' library as a basis for creating a new stream (https://github.com/substack/stream-handbook), or they mock it out with sinon but the mocking gets very lengthy very quicky.
Is there a nice way to provide a dummy stream like this?

A: Building on @flacnut 's answer, I did this (in NodeJS 12+) using Readable.from() to construct a stream preloaded with data (a list of filenames):
    const mockStream = require('stream').Readable.from([
       'file1.txt',
       'file2.txt',
       'file3.txt',
    ])

In my case, I wanted to mock the stream of filenames returned by fast-glob.stream:
    const glob = require('fast-glob')
    // inject the mock stream into glob module
    glob.stream = jest.fn().mockReturnValue(mockStream)

In the function being tested:
  const stream = glob.stream(globFilespec)
  for await (const filename of stream) {
    // filename = file1.txt, then file2.txt, then file3.txt
  }

Works like a charm!

A: There's a simpler way: stream.PassThrough
I've just found Node's very easy to miss stream.PassThrough class, which I believe is what you're looking for.
From Node docs:

The stream.PassThrough class is a trivial implementation of a Transform stream that simply passes the input bytes across to the output. Its purpose is primarily for examples and testing...

The code from the question, modified:
const { PassThrough } = require('stream');
const mockedStream = new PassThrough(); // <----

mockedStream.on('data', (d) => {
    console.dir(d);
});

mockedStream.on('end', function() {
    console.dir('goodbye');
});

mockedStream.emit('data', 'hello world');
mockedStream.end();   //   <-- end. not close.
mockedStream.destroy();

mockedStream.push() works too but as a Buffer so you'll might want to do: console.dir(d.toString());

A: Instead of using Push, I should have been using ".emit(<event>, <data>);"
My mock code now works and looks like:
var mockedStream = new require('stream').Readable();
mockedStream._read = function(size) { /* do nothing */ };

myModule.functionIWantToTest(mockedStream); // has .on() listeners in it

mockedStream.emit('data', 'Hello data!');
mockedStream.emit('end');

A: The accept answer is only partially correct.  If all you need is events to fire, using .emit('data', datum) is okay, but if you need to pipe this mock stream anywhere else it won't work.
Mocking a Readable stream is surprisingly easy, requiring only the Readable lib.
  let eventCount = 0;
  const mockEventStream = new Readable({
    objectMode: true,
    read: function (size) {
      if (eventCount < 10) {
        eventCount = eventCount + 1;
        return this.push({message: `event${eventCount}`})
      } else {
        return this.push(null);
      }
    }
  });

Now you can pipe this stream wherever and 'data' and 'end' will fire.
Another example from the node docs:
https://nodejs.org/api/stream.html#stream_an_example_counting_stream

A: Here's a simple implementation which uses jest.fn() where the goal is to validate what has been written to the stream created by fs.createWriteStream().  The nice thing about jest.fn() is that although the calls to fs.createWriteStream() and stream.write() are inline in this test function, these functions don't need to be called directly by the test.
    const fs = require('fs');
    const mockStream = {}

    test('mock fs.createWriteStream with mock implementation', async () => {
      const createMockWriteStream = (filename, args) => {
        return mockStream;
      }

      mockStream3.write = jest.fn();
      fs.createWriteStream = jest.fn(createMockWriteStream);

      const stream = fs.createWriteStream('foo.csv', {'flags': 'a'});
      await stream.write('foobar');
      expect(fs.createWriteStream).toHaveBeenCalledWith('foo.csv', {'flags': 'a'});
      expect(mockStream.write).toHaveBeenCalledWith('foobar');
  })


text:
Q: Tannakian categories and differential Galois theory I was taking a look at a result in Tamás Szamuely's Galois groups and fundamental groups. The following argument can be found right after the proof of lemma 6.6.7.
Let $(K,\partial)$ be a differential field, let $(V,\nabla)$ be a differential module over $K$ and let $L$ be a Picard-Vessiot extension for the differential module $(V,\nabla)$. Szamuely claims that if $\sigma:L\rightarrow L$ is a $K$-automorphism of $L$ commuting with the derivation $\partial$, then the induced automorphism $\tilde{\sigma}:V\otimes_K L\rightarrow V\otimes_K L$ preserves the space of horizontal vectors $(V\otimes_K L)^{\nabla_L}$, and also that this is true for any $(W,\nabla)\in Ob(\langle V,\nabla\rangle_\otimes)$, where $\langle(V,\nabla)\rangle_\otimes$ is the full subcategory of the category of differential modules over $K$, $\mathbf{DiffMod}_K$ tensor-generated by $(V,\nabla)$.
The first problem I am having is that I do not see why this implies that the fibre functor $\omega_L:(W,\nabla)\mapsto (W\otimes_K L)^{\nabla_L}$ takes values not only in $\mathbf{Vecf}_k$, but in fact in the category of finite dimensional representations of $\mathrm{Gal}_\partial(L|K)(k)$. Why is it?
On the other hand, I do not see why is it that the functor that sends each $k$-algebra $R$ to $(W\otimes_K L\otimes_L R)^{\nabla_{L\otimes_K R}}$ allows us to deduce that $\omega_L$ induces a functor from $\langle V,\nabla\rangle_\otimes$ to the category of representations of the affine group scheme $\mathrm{Gal}_\partial(L|K)$, $\mathbf{Rep}(\mathrm{Gal}_\partial(L|K))$. Any idea why does this happen?
For the first question, I believe that since $\mathrm{Gal}_\partial(L|K)(k)$ is the set of $K$-automorphisms of $L$ that commute with $\partial$, we can send each $(W,\nabla)$ to an element of $\mathrm{GL}_W(k)\simeq\mathrm{Aut}(W)$, but I am not completely sure of this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: WPF adjacent shape aliasing artifacts I have a rendering issue when trying to render two adjacent shapes in WPF. Using two polygons that have the same coordinates for the edges I hoped to see it filled nicely blue in this case. However there is a thin line from the background visible between the two polygons.
When I set the SnapToDevicePixels property to true the problem seems to be solved for the polygons that are vertically adjacent but not for the diagonal adjacent polygons.
Is it possible to solve this problem without combining the two polygons into one?


text:
Q: Wrong Calculation?
Possible Duplicate:
Is double Multiplication Broken in .NET?
PHP unexpected result of float to int type cast

echo (int) ( (0.1+0.7) * 10);

Gives me answer 7 but not 8.
echo (int) ( (0.1+0.8) * 10);

Gives answer 9 which is right
whats wrong? can anybody explain
thanx,
-Navi

A: It's normal – There's a thing called precision while working with floating point numbers. It's present in most of the modern languages. See here: http://www.mredkj.com/javascript/nfbasic2.html for more information.
((0.1+0.7) * 10) is probably something like 7.9999999 and (int) 7.9999999 = 7
On the other hand ((0.1+0.8) * 10) is probably 9.00000001 and (int)9.00000001 = 9

Floating point numbers have limited precision. Although it depends on the system, PHP typically uses the IEEE 754 double precision format, which will give a maximum relative error due to rounding in the order of 1.11e-16. Non elementary arithmetic operations may give larger errors, and, of course, error propagation must be considered when several operations are compounded.
Additionally, rational numbers that are exactly representable as
  floating point numbers in base 10, like 0.1 or 0.7, do not have an
  exact representation as floating point numbers in base 2, which is
  used internally, no matter the size of the mantissa. Hence, they
  cannot be converted into their internal binary counterparts without a
  small loss of precision. This can lead to confusing results: for
  example, floor((0.1+0.7)*10) will usually return 7 instead of the
  expected 8, since the internal representation will be something like
  7.9999999999999991118....
So never trust floating number results to the last digit, and do not
  compare floating point numbers directly for equality. If higher
  precision is necessary, the arbitrary precision math functions and gmp
  functions are available.

Source: http://php.net/manual/en/language.types.float.php

A: try
echo (float) ( (0.1+0.7) * 10);

A: Use Float
echo (float) ( (0.1+0.7) * 10);

it will give you perfect ans

A: try
echo (int) round( ( (0.1+0.7) * 10));

This should compensate the floating point computation error.


text:
Q: Find the value of $\sin x+\sin 3x+\sin 5x....\sin 29x$ This was a part of a larger question. I have the solution with me, but I have a problem with the way they wrote it.
The expression was written as
$$\frac{\sin (\frac{x+29x}{2})\sin(\frac{2x.15}{2})}{\sin\frac{2x}{2}}$$
Is this a formula that I am not aware of, or was it somehow derived from the specific information

A: Note
\begin{align}
&2\sin x\sin x=1 -\cos2x\\
 &2\sin x\sin 3x= \cos 2x - \cos4x\\
 &2\sin x\sin 5x= \cos 4x - \cos6x\\
&\cdots\\
& 2\sin x \sin 29x= \cos 28x -\cos30x
\end{align}
Sum up both sides
$$2\sin x\ ( \sin x+\sin 3x+\sin 5x+....+\sin 29x) = 1-\cos30x$$
to arrive at
$$\sin x+\sin 3x+\sin 5x +\cdots+\sin 29x=\frac{1-\cos30x}{2\sin x}=\frac{\sin^2 15x}{\sin x}$$

A: $$\sum_{k=1}^{29}\sin\left(kx\right)=\Im\left[\sum_{k=1}^{29}\left(e^{ikx}\right)\right]$$$$=\Im\left[e^{ix}\frac{e^{i\left(29\right)k}-1}{e^{ix}-1}\right]=\Im\left[e^{ix}\cdot\frac{\left(e^{i\left(\frac{29}{2}\right)x}\right)e^{i\left(\frac{29}{2}\right)x}-e^{-i\left(\frac{29}{2}\right)x}}{e^{i\left(\frac{1}{2}\right)x}\left(e^{i\left(\frac{1}{2}\right)x}-e^{-i\left(\frac{1}{2}\right)x}\right)}\right]$$$$=\Im\left[e^{i\left(15\right)x}\cdot\frac{2i\sin\left(\frac{29}{2}x\right)}{2i\sin\left(\frac{1}{2}x\right)}\right]$$$$=\Im\left[(\cos\left(\left(15\right)x\right)+i\sin\left(\left(15\right)x\right))\frac{2i\sin\left(\frac{29}{2}x\right)}{2i\sin\left(\frac{1}{2}x\right)}\right]$$$$=\sin\left(\left(15\right)x\right)\frac{\sin\left(\frac{29}{2}x\right)}{\sin\left(\frac{1}{2}x\right)}$$

A: Note that
$$\sum_{r=1}^n\sin(a+(r-1)b)=\dfrac{\sin\left(\dfrac{2a+(n-1)b}{2}\right)\sin\left(\dfrac{nb}{2}\right)}{\sin\left(\dfrac{b}{2}\right)}$$
To prove, multiply and divide by $2\sin\left(\dfrac{b}{2}\right)$ in LHS, apply the identity $$2\sin x\sin y=\cos(x-y)-\cos(x+y)$$
and do the telescopic sum.


text:
Q: Placeholder scaling issue with URLImage in landscape mode I scaled the placeholder to the screen size as below. But if it is first viewed in portrait mode, it just takes the screen and doesn't cover whole screen in landscape mode. If it is 1st viewed in landscape mode, then it appears bigger than the screen size in portrait mode.
How do I fix this problem. I checked in PropertyCross demo and the same issue exists there too.
private EncodedImage largePlaceholder;

protected void initVars(Resources res) {
    Image tmp = Image.createImage(Display.getInstance().getDisplayWidth(), Display.getInstance().getDisplayWidth() / 6 * 3, 0);
    largePlaceholder = EncodedImage.createFromImage(tmp, false);
}

findMainImg(f).setIcon(URLImage.createToStorage(largePlaceholder, getMainImg + "_0_ y", getMainImg, URLImage.RESIZE_SCALE_TO_FILL));

Updated:
int sizethumb = 0;
int sizethumb1 = 0;
if (responsesImg.size() > 0) {

    sizethumb = largePlaceholder.getWidth();
    sizethumb1 = largePlaceholder.getHeight();
    findMainImg().setPreferredSize(new Dimension(sizethumb, sizethumb1));

    findMainImg(f).getAllStyles().setBgImage(URLImage.createToStorage(largePlaceholder, newsImgFilename + "_0_ y", responsesImg.get(0).get("image_url"), URLImage.RESIZE_SCALE));

    mainImageImgViewer = findMainImg(f).getAllStyles().getBgImage();
    System.out.println("beck0 " + mainImageImgViewer); //it gives null

A: I suggest setting it as the bg image of the style and setting the background behavior to SCALE_TO_FILL or SCALE_TO_FIT.

A: You are using the screen size to generate your placeholder image and the width of the screen in Landscape is bigger than Portrait.
If you want to make the image responsive, you will have to add orientation  change listener which will download another image with a different size for landscape if you're coming from portrait and vice-versa.
private EncodedImage largePlaceholderPortrait;
private EncodedImage largePlaceholderLandscape;
private boolean isPortrait = Display.getInstance().isPortrait();

protected void initVars(Resources res) {
    Image tmp = Image.createImage(Display.getInstance().getDisplayWidth(), Display.getInstance().getDisplayWidth() / 6 * 3, 0);
    Image tmp2 = Image.createImage(Display.getInstance().getDisplayHeight(), Display.getInstance().getDisplayHeight() / 6 * 3, 0);
    largePlaceholderPortrait = EncodedImage.createFromImage(isPortrait ? tmp : tmp2, false);
    largePlaceholderLandscape = EncodedImage.createFromImage(isPortrait ? tmp2 : tmp, false);
}

findMainImg(f).setIcon(URLImage.createToStorage(largePlaceholderPortrait,  isPortrait ? getMainImg + "_0_y_portrait" : getMainImg + "_0_y_landscape", getMainImg, URLImage.RESIZE_SCALE_TO_FILL));

f.addOrientationListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent evt) {
        findMainImg(f).setIcon(URLImage.createToStorage(largePlaceholderPortrait,  isPortrait ? getMainImg + "_0_y_portrait" : getMainImg + "_0_y_landscape", getMainImg, URLImage.RESIZE_SCALE_TO_FILL));
    }
});

//Java 8
f.addOrientationListener((evt) -> {
    findMainImg(f).setIcon(URLImage.createToStorage(largePlaceholderPortrait,  isPortrait ? getMainImg + "_0_y_portrait" : getMainImg + "_0_y_landscape", getMainImg, URLImage.RESIZE_SCALE_TO_FILL));
});


text:
Q: Move input inside label with jQuery How can I move the input inside the  tag, so that it would be <input> using jQuery. I need to target all the answers within the select-option set.

 <input id="[0]_Actual_Answer_1" name="[0]_Actual_Answer_1" type="radio" value="IZWE">
 HELLO WORLD

 <input id="[0]_Actual_Answer_2" name="[0]_Actual_Answer_2" type="radio" value="IZWE">
 HELLO WORLD 2

 <input id="[0]_Actual_Answer_3" name="[0]_Actual_Answer_3" type="radio" value="IZWE">
 HELLO WORLD 3

 <input id="[0]_Actual_Answer_4" name="[0]_Actual_Answer_4" type="radio" value="IZWE">
 HELLO WORLD 4

A: Your quotes
 are incorrect! Use "
Than for the jQuery part:

$("label[for*='[0]_Actual_Answer']").prepend(function(){
  return $(this).prev("input");
});
label{background:red;}

    <input id="[0]_Actual_Answer_1" name="[0]_Actual_Answer_1" type="radio" value="IZWE">
    HELLO WORLD

    <input id="[0]_Actual_Answer_2" name="[0]_Actual_Answer_2" type="radio" value="IZWE">
    HELLO WORLD 2

    <input id="[0]_Actual_Answer_3" name="[0]_Actual_Answer_3" type="radio" value="IZWE">
    HELLO WORLD 3

    <input id="[0]_Actual_Answer_4" name="[0]_Actual_Answer_4" type="radio" value="IZWE">
    HELLO WORLD 4

A: If I'm understanding correctly, what you may be after is something like this...
$(document).ready(function() {
  $('.select-option input').each(function() { //Get every input in the "select-option" div
     var t = $(this);
     var l = t.siblings('label'); //Find the closest label
     t.detach().appendTo(l);
  });
});

JSFiddle

A: Using prepend(function)
$('.select-option label[for*=Actual_Answer]').prepend(function(){
    return $(this).prev("input")
});


text:
Q: HTTP 400 When Trying to Send HTTP Post GraphQL Query using HttpClient in Java Have a post query for an external GraphQL server which works in Postman Pro setup as a Pre-request Script.
Am trying to hit an external GraphQL server using HttpClient.
Maven dependencies pom.xml:
<!-- Apache Commons -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.6</version>
</dependency>

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.2.5</version>
</dependency>

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.6</version>
</dependency>

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.2.4</version>
</dependency>

<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.1.1</version>
</dependency>

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient-cache</artifactId>
    <version>4.2.5</version>
</dependency>

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.2.5</version>
</dependency>

<!-- Google Code -->
<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>

Hardcoded the pre-request script as follows:
GetDataAsRequest.java
public class GetDataAsRequest {
    private static final String GET_DATA_REQUEST_TEMPLATE =
    "query {"
        + "    viewer {     "
        + "        data(id: \"10045701-2017-41a4-33f4-bf8481cf01dc\") {" +
        "            id"
        + "            createdDate"
        + "            lastModifiedDate"
        + "            abbreviation"
        + "            cityStateRegion"
        + "        }"
        + "    }"
        + "}";
    }

    public static String generateQuery() {
        return String.format(GET_DATA_REQUEST_TEMPLATE);
    }
}

MyController:
public class MyController {

    private static final String EXTERNAL_API_URL = "https://sample-api.com"

    public static void main (String args []) {

        // Generate Access Token
        String accessToken = OAuth2Client.generateAccessToken();
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(EXTERNAL_API_URL);
        StringEntity postBody = new StringEntity(GetDataAsRequest.generateQuery());
        postBody.setContentType("application/json");
        postRequest.addHeader("Authorization", "Bearer " + accessToken);
        postRequest.setEntity(postBody);
        HttpResponse response = httpClient.execute(postRequest);

        if (response.getStatusLine().getStatusCode() != 201) {
            throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }
        httpClient.getConnectionManager().shutdown();
        }
        catch (MalformedURLException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

Although the same OAuthToken and HTTP post query works when I copy it from stdin (console) into a Postman call, I keep getting an HTTP 400 when trying to emulate the same call using HttpClient inside a Java program:
03:25:30.690 [main] DEBUG org.apache.http.impl.conn.BasicClientConnectionManager - Get connection for route {s}->https://https://sample-api.com
03:25:30.751 [main] DEBUG org.apache.http.impl.conn.DefaultClientConnectionOperator - Connecting to https://sample-api.com:443
03:25:30.943 [main] DEBUG org.apache.http.client.protocol.RequestAddCookies - CookieSpec selected: best-match
03:25:30.950 [main] DEBUG org.apache.http.client.protocol.RequestAuthCache - Auth cache not set in the context
03:25:30.950 [main] DEBUG org.apache.http.client.protocol.RequestTargetAuthentication - Target auth state: UNCHALLENGED
03:25:30.951 [main] DEBUG org.apache.http.client.protocol.RequestProxyAuthentication - Proxy auth state: UNCHALLENGED
03:25:30.951 [main] DEBUG org.apache.http.impl.client.DefaultHttpClient - Attempt 1 to execute request
03:25:30.951 [main] DEBUG org.apache.http.impl.conn.DefaultClientConnection - Sending request: POST /v1/oauth/token HTTP/1.1
03:25:30.951 [main] DEBUG org.apache.http.wire - >> "POST /v1/oauth/token HTTP/1.1[\r][\n]"
03:25:30.952 [main] DEBUG org.apache.http.wire - >> "Content-Length: 119[\r][\n]"
03:25:30.952 [main] DEBUG org.apache.http.wire - >> "Content-Type: application/x-www-form-urlencoded; charset=UTF-8[\r][\n]"
03:25:30.952 [main] DEBUG org.apache.http.wire - >> "Host: https://sample-api.com[\r][\n]"
03:25:30.952 [main] DEBUG org.apache.http.wire - >> "Connection: Keep-Alive[\r][\n]"
03:25:30.952 [main] DEBUG org.apache.http.wire - >> "User-Agent: Apache-HttpClient/4.2.5 (java 1.5)[\r][\n]"
03:25:30.952 [main] DEBUG org.apache.http.wire - >> "[\r][\n]"
03:25:30.952 [main] DEBUG org.apache.http.headers - >> POST /v1/oauth/token HTTP/1.1
03:25:30.952 [main] DEBUG org.apache.http.headers - >> Content-Length: 119
03:25:30.952 [main] DEBUG org.apache.http.headers - >> Content-Type: application/x-www-form-urlencoded; charset=UTF-8
03:25:30.952 [main] DEBUG org.apache.http.headers - >> Host: https://sample-api.com
03:25:30.952 [main] DEBUG org.apache.http.headers - >> Connection: Keep-Alive
03:25:30.953 [main] DEBUG org.apache.http.headers - >> User-Agent: Apache-HttpClient/4.2.5 (java 1.5)
03:25:30.953 [main] DEBUG org.apache.http.wire - >> "grant_type=client_credentials&client_id=fghuXeULFBdW4B1dmRY0MhROMRQnlumk&client_secret=MM2banXEq2R1GhRvIQ2d2AKRx0SORvb4"
03:25:31.132 [main] DEBUG org.apache.http.wire - << "HTTP/1.1 200 OK[\r][\n]"
03:25:31.134 [main] DEBUG org.apache.http.wire - << "X-Application-Context: application:prod[\r][\n]"
03:25:31.134 [main] DEBUG org.apache.http.wire - << "Content-Type: application/json[\r][\n]"
03:25:31.134 [main] DEBUG org.apache.http.wire - << "Cache-Control: no-store[\r][\n]"
03:25:31.134 [main] DEBUG org.apache.http.wire - << "Pragma: no-cache[\r][\n]"
03:25:31.134 [main] DEBUG org.apache.http.wire - << "Accept-Ranges: bytes[\r][\n]"
03:25:31.135 [main] DEBUG org.apache.http.wire - << "X-Cache-Hits: 0[\r][\n]"
03:25:31.135 [main] DEBUG org.apache.http.wire - << "X-Timer: S1525774921.421988,VS0,VE41[\r][\n]"
03:25:31.135 [main] DEBUG org.apache.http.wire - << "Date: Tue, 08 May 2018 10:22:01 GMT[\r][\n]"
03:25:31.135 [main] DEBUG org.apache.http.wire - << "Content-Length: 325[\r][\n]"
03:25:31.135 [main] DEBUG org.apache.http.wire - << "Connection: keep-alive[\r][\n]"
03:25:31.135 [main] DEBUG org.apache.http.wire - << "X-Sample-APP: sso[\r][\n]"
03:25:31.135 [main] DEBUG org.apache.http.wire - << "Access-Control-Allow-Headers: Authorization,Content-Type[\r][\n]"
03:25:31.135 [main] DEBUG org.apache.http.wire - << "Access-Control-Allow-Methods: PUT,POST,OPTIONS,GET,PATCH,DELETE[\r][\n]"
03:25:31.135 [main] DEBUG org.apache.http.wire - << "Access-Control-Allow-Origin: *[\r][\n]"
03:25:31.135 [main] DEBUG org.apache.http.wire - << "[\r][\n]"
03:25:31.136 [main] DEBUG org.apache.http.impl.conn.DefaultClientConnection - Receiving response: HTTP/1.1 200 OK
03:25:31.136 [main] DEBUG org.apache.http.headers - << HTTP/1.1 200 OK
03:25:31.136 [main] DEBUG org.apache.http.headers - << X-Application-Context: application:prod
03:25:31.136 [main] DEBUG org.apache.http.headers - << Content-Type: application/json
03:25:31.136 [main] DEBUG org.apache.http.headers - << Cache-Control: no-store
03:25:31.136 [main] DEBUG org.apache.http.headers - << Pragma: no-cache
03:25:31.138 [main] DEBUG org.apache.http.headers - << Accept-Ranges: bytes
03:25:31.138 [main] DEBUG org.apache.http.headers - << X-Served-By: cache-sample-las9320
03:25:31.138 [main] DEBUG org.apache.http.headers - << X-Cache-Hits: 0
03:25:31.138 [main] DEBUG org.apache.http.headers - << X-Timer: S1525774921.421988,VS0,VE41
03:25:31.138 [main] DEBUG org.apache.http.headers - << Date: Tue, 08 May 2018 10:22:01 GMT
03:25:31.138 [main] DEBUG org.apache.http.headers - << Content-Length: 325
03:25:31.138 [main] DEBUG org.apache.http.headers - << Connection: keep-alive
03:25:31.138 [main] DEBUG org.apache.http.headers - << X-Sample-APP: sso
03:25:31.138 [main] DEBUG org.apache.http.headers - << Access-Control-Allow-Headers: Authorization,Content-Type
03:25:31.138 [main] DEBUG org.apache.http.headers - << Access-Control-Allow-Methods: PUT,POST,OPTIONS,GET,PATCH,DELETE
03:25:31.138 [main] DEBUG org.apache.http.headers - << Access-Control-Allow-Origin: *
03:25:31.141 [main] DEBUG org.apache.http.impl.client.DefaultHttpClient - Connection can be kept alive indefinitely
03:25:31.147 [main] DEBUG org.apache.http.wire - << "{"access_token":"fkMmGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6bnVsbCwiZGV2aWNlSWQiOm51bGwsImNsaWVudElkIjoiaUxIdVhlVUxGQmRXNEIxZG1SWTBNaFJPTVJRbmxmZUsiLCJhZElkIjpudWxsLCJleHAiOjE1MjU3Nzg1MjEsImlhdCI6MTUyNTc3NDkyMX0.U3gacgf7a8hlwCuCn6yGXc0z6E5Zrwgii3B_77xFlyo","token_type":"Bearer","expires_in":3600,"refresh_token":null,"scope":null}"
03:25:31.147 [main] DEBUG org.apache.http.impl.conn.BasicClientConnectionManager - Releasing connection org.apache.http.impl.conn.ManagedClientConnectionImpl@2ddc8ecb
03:25:31.147 [main] DEBUG org.apache.http.impl.conn.BasicClientConnectionManager - Connection can be kept alive indefinitely
Exception in thread "main" java.lang.RuntimeException: Failed : HTTP error code : 400

Is this returning an HTTP 400 because my request body is wrong in some way?
Is there an easier way to obtain JSON responses via GraphQL's Java libs:
<!-- GraphQL -->
<dependency>
    <groupId>com.graphql-java</groupId>
    <artifactId>graphql-java</artifactId>
    <version>8.0</version>
</dependency>

<dependency>
    <groupId>com.graphql-java</groupId>
    <artifactId>graphql-java-tools</artifactId>
    <version>5.0.0</version>
</dependency>

A lot of examples on the Internet show how to setup and external GraphQL server, what I need is to learn how to use the GraphQL Java libs serving as a client library to parse and obtain the right GraphQL response from an external server...
This is returning correctly from Postman Pro and curl but not using HttpClient.
What am I possibly doing wrong?

A: Do you control the server? If so, why not put a break point there and inspect what fails? If you don't control the server, I'd say double-check the differences between what you send here and with Postman.
One thing looks very suspicious immediately. You're sending a POST that claims to have a JSON body, but the string you're sending is a raw GraphQL query and not JSON at all.
I could tell you to turn the request body into a JSON object as defined by the GraphQL over HTTP Spec, but without knowing if your server actually implements this spec, it is just a guess.
What the spec defines as a proper body of a POST request is a JSON object with 3 fields: query, operationName and variables. The query field should contain the query string (so stringify the query first), operationName contains the name of the operation to execute in case there's multiple (not relevant to your case), and variables contains a JSON object with variables as key-value pairs (not relevant right now).
Meaning in your case, the body should look like:
{
    query: "{
        viewer {
            data(id: \"10045701-2017-41a4-33f4-bf8481cf01dc\") {
                id
                createdDate
                lastModifiedDate
                abbreviation
                cityStateRegion
            }
        }
    }"
}

To put this string into Java code, all this needs an extra level of escaping but I hope your IDE will take care of that. Also notice the line breaks are important. If you lose them for any reason, you must put commas between the selected fields for the query to remain valid.


text:
Q: Difference Between Application Exception and System Exception I want to know the difference Between System.ApplicationException and System.Exception.
Can anyone explain

A: Originally they were intended to separate BCL defined and user defined Exceptions.  ApplicationException was meant to be the base class for all user defined exceptions.  The idea was it would give you a clean way to differintiate between framework exceptions and custom exceptions.
Unfortunately this policy was not enforced from the start and as a result there are many contradictions to this rule in the BCL.  The current recomendation is not to inherit from these exceptions.
Here's a nice blog entry on the subject:

*

*http://blogs.msdn.com/kcwalina/archive/2006/06/23/644822.aspx

A: All exception derives from Exception Base class. Exceptions can be generated programmatically
or can be generated by system. Application Exception serves as the base class for all application
specific exception classes. It derives from Exception but does not provide any extended functionality.
You should derive your custom application exceptions from Application Exception.
Application exception are used when we want to define user defined exception. While system
exception are all which are defined by .NET


text:
Q: Projective space and homogeneous coordinates I'm learning projective geometry and need help with the following problem :

Consider three distinct "points" of the projective space $\mathbb R P^1$, that is three distinct lines $l_1, l_2, l_3$ of $R^2 -\{0\}$ (the plane minus $0$). $(1)$ Show that we can choose homogeneous coordinates $[X_1 : X_2], [Y_1:Y_2]$ and $[Z_1:Z_2]$ for $l_i, i = 1, 2, 3$ such that
$$Z_1 = X_1 + Y_1, \quad Z_2 = X_2 + Y_2.$$
$(2)$ Find such coordinates for the lines $l_1 : -x+2y=0, \, l_2 = 2x+y = 0, \, l_3 : 5x-3y = 0.$

I'm sorry for the lack of effort on my part but I was not able to do much with this problem. I did go back several times through my notes but I don't know where to start here. Any help would be appreciated.

A: A given line $l_1$ in $\mathbb{RP}^1$ can be specified by any homogeneous coordinate $[\lambda_1 X_1 : \lambda_1 X_2]$, with $\lambda_1$ nonzero. So the desired condition amounts to finding $\lambda_1,\lambda_2$, and $\lambda_3$ so that
$$ X_1 \lambda_1 + Y_1 \lambda_2 = Z_1 \lambda_3 \\
   X_2 \lambda_1 + Y_2 \lambda_2 = Z_2 \lambda_3 $$
In other words, your problem amounts to solving a system of linear equations.

I'll take things a bit farther. If we let
$$ A= \begin{bmatrix} X_1  & Y_1\\ X_2 & Y_2 \end{bmatrix}, \quad  x=\begin{bmatrix} \lambda_1 \\ \lambda_2 \end{bmatrix}, \quad  b=\begin{bmatrix} Z_1 \\ Z_2 \end{bmatrix} $$
then the linear equation $Ax=b$ has a unique solution (why?) and yields a solution to your problem (why?).
Let me know if you'd like any further comments.

A: OK, if you wish one more answer....
The homogeneous coordinates of a point $\mathscr l$ of the projective space $\Bbb RP_1$ are given by a pair $[T_1:T_2]$ of real numbers, such that not both $T_1$ and $T_2$ are zero. Moreover, if we multiply both $T_1$ and $T_2$ by any non-zero real number $\lambda$ then we obtain the homogeneous coordinates $[\lambda T_1: \lambda T_2]$ of the same point $\mathscr l$. This is all that you need to solve your problem, :-) so let's start.
(1) Assume that we have three distinct points $\mathscr l_1$, $\mathscr l_2$, and $\mathscr l_3$ of $\Bbb RP_1$. Let the point $\mathscr l_1$ is given to us by its homogeneous coordinates $[x_1:x_2]$, the point $\mathscr l_2$ by $[y_1:y_2]$, and the point $\mathscr l_2$ by $[z_1:z_2]$. So we have to show that there exist non-zero real numbers $\lambda_1$,  $\lambda_2$, and $\lambda_3$ such that
$$X_1=\lambda_1 x_1\mbox{, } X_2=\lambda_1 x_2,$$
$$Y_1=\lambda_2 y_1\mbox{, } Y_2=\lambda_2 y_2,$$
$$Z_1=\lambda_3 z_1\mbox{, } Z_2=\lambda_3 z_2,$$
$$Z_1=X_1+Y_1\mbox{, and } Z_2=X_2+Y_2.$$
Thus we have to show that this system of equations has a solution. This means that there exist non-zero real numbers $\lambda_1$,  $\lambda_2$, and $\lambda_3$ such that
$$\lambda_1 x_1+\lambda_2 y_1-\lambda_3 z_1=0$$
$$\mbox{and}$$
$$\lambda_1 x_2+\lambda_2 y_2-\lambda_3 z_2=0.$$
We can tackle this problem as a question of solvability of a homogeneous system of linear equations, but there is a short-cut. This system means that the vector $(\lambda_1, \lambda_2,-\lambda_3)$ is orthogonal to both vectors $(x_1,y_1,z_1)$ and $(x_2,y_2,z_2)$. Such a property has their vector product
$$(x_1,y_1,z_1)\times (x_2,y_2,z_2)=\left|\begin{matrix}\bf{i} & \bf{j} & \bf{k}\\ x_1 & y_1 &z_1 \\ x_2 & y_2 &z_2 \end{matrix}\right|=(\lambda_1, \lambda_2, -\lambda_3).$$
It remains to check that $\lambda_i$'s are non-zero. This holds because the points $\mathscr l_i$ are distinct. For instance, $\lambda_1=
\left|\begin{matrix} y_1 &z_1 \\  y_2 &z_2 \end{matrix}\right|=y_1z_2-y_2z_1$. If $\lambda_1$ is zero then $[y_1:y_2]z_2=[z_1:z_2]y_2$, which is impossible because points $\mathscr l_2$ and $\mathscr l_3$ are distinct.
(2)  In this case we have $(x_1,y_1,z_1)=(2,-1,3)$ and $(x_2,y_2,z_2)=(1,2,5)$. Thus
$$(\lambda_1, \lambda_2, -\lambda_3)=(x_1,y_1,z_1)\times (x_2,y_2,z_2)=$$ $$ (2,-1,3)\times (1,2,5) =\left|\begin{matrix}\bf{i} & \bf{j} & \bf{k}\\ 2 & -1 & 3 \\ 1 & 2 & 5 \end{matrix}\right|=(-11,-7,6).$$


text:
Q: How to replace OpenCV handling of binary image data in Flask with Pillow I'm currently using OpenCV to handle an image passed through to a Flask API implementation as binary data and I would like to replace it with Pillow.
The data is passed through like this:
# load image
img = open('test1.jpg', 'rb').read()
# send image and get response
response = requests.post(test_url, data=img, headers=headers)

And handled in Flask with Open CV like this:
# route http posts to this method
@app.route('/api/test', methods=['POST'])
def test():
    r = request
    # convert string of image data to uint8
    nparr = np.fromstring(r.data, np.uint8)
    # decode image
    img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

A: The solution was as follows:
# route http posts to this method
@app.route('/api/test', methods=['POST'])
def test():
    r = request
    # convert string of image data to uint8
    nparr = np.fromstring(r.data, np.uint8)
    # decode image
    img = Image.open(io.BytesIO(nparr))


text:
Q: Show that f is a homeomorphism? I'm trying to show that $\vec{f}: D \to R, \vec{f}(r, \varphi)=
\begin{pmatrix}r\cos(\varphi)\\ r\sin(\varphi)\end{pmatrix}
 $ is a homeomorphism, with $D = \{(r, \varphi) \in \mathbb{R^2}|r\in[1,2], \varphi \in [o, \frac{\pi}{2}]\}$ and on the other hand with $R = \{(x,y) \in \mathbb{R^2}|y\geq 0,x\geq 0, 1 \leq x^2+y^2 \leq 4\}$. Now, I'm not quite sure how I should go about this. Do I just find any function that assigns values to $x$ and $y$ in terms of $r$ and $\varphi$ and then show that continuity, bijection and continuity of the inverse are given? Any help is greatly appreciated since I'm fairly new to this.
Best regards.

A: Clearly $f$ is continuous.
Take $(x,y) \in R$ and assume that $f(r,\varphi)= (x,y)$ for some $(r, \varphi) \in D$. We get
$$(r\cos\varphi, r\sin\varphi) = f(r, \varphi) = (x,y)$$
so it follows $r = \sqrt{x^2+y^2}$ and $\cos\varphi = \frac{x}{r}$ so $$\varphi= \arccos\frac{x}{\sqrt{x^2+y^2}}$$
After checking that indeed $(r, \varphi) \in D$ and $f(r,\varphi) = (x,y)$, we conclude that $f \circ g = \operatorname{id}_R$ where $g : R \to D$ is given by $$g(x,y) = \left(\sqrt{x^2+y^2}, \arccos\frac{x}{\sqrt{x^2+y^2}}\right)$$
which is a continuous function $R \to D$. Now also check that $g \circ f = \operatorname{id}_D$ to conclude that $f$ is bijective with inverse $f^{-1} =g$.
Hence $f$ is a homeomorphism.

A: This really depends on which results about homeomorphisms you assume to be true, but keeping it quite simple, in the roum of what you know, I would attack the problem this way:

*

*Prove $\vec{f}$ is continuous (simple as $f$ is a product of elementary functions)

*Find an inverse for $\hat{f}$ (it won't even look ugly!)

*Prove that inverse is also continuous (also straight-forward)


text:
Q: How to fadeOut a div after a document has loaded? I'm trying to do something I thought was simple, but I'm not having any luck actually getting it to work.  All I want to do is fade out a div after X number of seconds have passed since the document finished loading.
In my Site.Master file I have the following:
<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>

    <%
    if (Html.ViewContext.TempData.ContainsKey("StatusMessage")) {
        %>

<%=Html.ViewContext.TempData["StatusMessage"]%>

        <%
    }
    %>
    <asp:ContentPlaceHolder ID="MainContent" runat="server" />

The problem is that nothing fades.  What have I overlooked?

A: I think you're missing a little of your code
$(document).ready(function() {
    $("#notify-container").fadeOut(2000);
}

Should be...
$(document).ready(function() {
    $("#notify-container").fadeOut(2000);
}); // <---

A: I think you are missing the closed parenthesis, and semi-colon.
);

at the end of your script tag for the document ready function.

A: For future reference, the best way to delay things from happening is to .fadeTo(delaytime, 1); the object you want to animate, delaytime would be how long you want to delay it from happening by. It just "fades" the already totally visible object to the value it already has, wasting the exact amount of time you tell it to.


text:
Q: syntax error when installing auth_mellon module on Apache I need to compile the module auth_mellon and I am using autoconf
but when I run this command
./configure --with-apxs2=/usr/bin/apxs

I am getting this
./configure: line 3138: syntax error near unexpected token `LASSO,'

and
./configure: line 3138: `PKG_CHECK_MODULES(LASSO, lasso)'

How can I fix it?

A: Try:
# apt-get install liblasso3 liblasso3-dev
# apt-get install libcurl4-openssl-dev
# aclocal
# ./autogen.sh
# ./configure
# make
# make install

It works on Ubuntu 16.04


text:
Q: Factorization of GCD I'm working on a question about factorization of a GCD.
Let x = p$^{n1}_1$ ... p$^{nk}_k$
Is it correct to answer this with: p$^{n1}_1$ + $^{m1}_1$ ... p$^{nk}_k$ + $^{mk}_k$ ?

A: No, try $x=12=2^2\cdot 3^1 \cdot 5^0, y=1350=2^1\cdot 3^3 \cdot 5^2$.  The GCD is not $2^3\cdot 3^4 \cdot 5^2=16200$  For a common divisor, you need the minimum of the exponents.


text:
Q: Efficiently skipping Stripe API calls and/or logging for test IDs I would like to be able to have test stripe accounts live along production accounts in the same database, but treat them differently depending on whether I am using test API keys.
Currently the stripe Go library logs errors when a test Stripe ID is queried while using production API keys. The Stripe library itself logs this when trying to fetch such a stripe customer:
Error encountered from Stripe: {"code":"resource_missing","status":404,"message":
"No such customer: cus_foo; a similar object exists in test mode, but a live mode
key was used to make this request.","param":"id","request_id":"req_foo","type":
"invalid_request_error"}

I would like to avoid having this happen by either doing a separate API call that asks "is this a test user?" or by suppressing only the above error output so I can ignore and not print my own error in the case of test users.
I do the obvious
params := &stripe.CustomerParams{}
stripeCustomer, err := customer.Get(stripeID, params)
if err != nil {
    return nil, err
}

From a function, but the call to Get() has already logged an error before I have a chance to react to it..
I could just have a test_account attribute attached to the user, but I'd rather just make a few needless API calls and silently ignore them somehow.


text:
Q: Construct a type I have many type declarations:
module SumProduct where

  data GuessWhat = Chickenbutt deriving (Eq, Show)

  data Id a = MkId a deriving (Eq, Show)

  data Product a b = Product a b deriving (Eq, Show)

  data Sum a b = First a
                | Second b
                deriving (Eq, Show)

  data RecordProduct a b = RecordProduct { pfirst :: a , psecond :: b }
                          deriving (Eq, Show)

  newtype NumCow = NumCow Int deriving (Eq, Show)

  newtype NumPig = NumPig Int deriving (Eq, Show)

  data Farmhouse = Farmhouse NumCow NumPig deriving (Eq, Show)
  type Farmhouse' = Product NumCow NumPig

  newtype NumSheep = NumSheep Int deriving (Eq, Show)

  data BigFarmhouse = BigFarmhouse NumCow NumPig NumSheep deriving (Eq, Show)
  type BigFarmhouse' = Product NumCow (Product NumPig NumSheep)

  type Name = String
  type Age = Int
  type LovesMud = Bool

  type PoundsOfWool = Int
  data CowInfo = CowInfo Name Age
                 deriving (Eq, Show)

  data PigInfo = PigInfo Name Age LovesMud deriving (Eq, Show)

  data SheepInfo = SheepInfo Name Age PoundsOfWool deriving (Eq, Show)

  data Animal = Cow CowInfo
               | Pig PigInfo
               | Sheep SheepInfo
               deriving (Eq, Show)

  type Animal' = Sum CowInfo (Sum PigInfo SheepInfo)(Sum PigInfo SheepInfo)

And play around in the prelude with:
Prelude> let bess = First (CowInfo "Bess" 4) :: Animal'
Prelude> let elmer' = Second (SheepInfo "Elmer" 5 5)

How it comes, that the first becomes the type bess :: Animal' and the second elmer' :: Sum a SheepInfo?

A: By default, Haskell infers the most general type that applies to the expression.
Here, you directly tell GHC what type bess is, so it just checks if the type you provided is valid, but allows it to be more specific than the most general type.
Since you explicitly tell GHC that bess has type Animal' by the :: operator (it's a language construct, not an actual operator defined in the standard library), GHC already knows that bess :: Animal'. However, because you didn't provide any type for elmer', GHC will find the most general type for you.
In this case, the most general type is Sum a SheepInfo because all GHC knows is that the Second constructor takes a SheepInfo, but has no idea of what First should take. Thus, it infers it to a type variable a.


text:
Q: SQLite databse closing issue while dealing with fragments In tablet application, left handside fragment has listview with cursor adapter   and Right hand side is replacing with fragments. In a process, I am closing database object in Righthand side fragment.  Left hand fragment side also closed.
If i am not closed the database object. Its automactically closing after some time.
So, can you please tell how to deal with database objects while dealing fragments.


text:
Q: How to make SVG images be displayed in a mobile device? I am building a QT application which I customize through QT stylesheets. The images I use for the controls are SVG images which are rendered properly when ran in Linux. But when I load the QT application into a mobile device, the SVG images don't seem to appear.
Does anyone know what's going on? What should I do to make the SVG images work?

A: First check the log file in your emulator and find out what is the error occurred:
svg while implementing on mobile device may fail because of the following scenarios.
1.Memory footpring issue because of different OS;mobile OS is relatively small in size.
2.Device type on which it runs.
3.Framework that is used for implementing SVG applications.The framework availability
4.Sometime image encoding can also be an issue.
So need to get a framework that support all these characters on mobile device.
Currently there are few open source and commercail frameworks available.You will get more from this link
http://developers.sun.com/mobility/midp/articles/s2dvg/index.html


text:
Q: Who should own the logic for service resolution in Service Fabric Stateful Services? I am using Service Fabric stateful services to store state about users in the system.  My partitioning strategy is to use the normalized international string format phone number to address a named service instance, and the hash of the phone number to resolve a partition of that service. EX: fabric:/myapp/users/1/718 (where the international phone number is +1718xxxxxxx) This allows me to geo-locate services based on their country (and further in the US/Canada markets by area code).
My question is sort of theoretical, but also practical in nature.  Who owns the logic for service resolution?  A simple approach is to just require anyone taking a dependency on this service to know how its partitioned, but that feels like a leaky abstraction to me.  Furthermore, I would like to assign an Id to the user which is divorced from the concept of a phone number.

*

*My original approach was to make the Id a byte[] which included the service name, partition id, and local id of the user.  I dropped this idea since the size of the ID was very large, and would add up over time.  (this is problematic because all keys in a Reliable Dictionary need to fit into memory and I'd rather not kill a ton of memory on ids) Also, it still carries with it the baggage of everyone using the id knowing how to interpret the id and use it accordingly.

*My next idea was to provide a client library to anyone consuming the service.  This also has the drawback of a binary dependency of a consuming service.  If i want to change the strategy in the future, I have to jump through a bunch of hoops to handle failures to correctly resolve the entity.

*The last alternative i can think of is to have a stateless proxy in front of stateful service which handles the resolution for all services.  This is the most appealing from a design perspective but also involves managing, building another service just for resolution.  Not opposed to it, but it is an additional consideration.  If i go this route, should I tread this service as a separate service fabric application, or is it advisable to keep everything as one application.

I also, am open to entertaining the idea that partitioning users this way is a bad idea. However, using the phone is advisable for a number of reasons.

A: I'd recommend keeping any knowledge about partitioning away from your service consumers, if possible. This way you can change the service internals without changing anything at the consumer-side.
That leads to option 3, combined with the built-in reverse proxy service.
In that extra service, you can look up the authenticated user and use its location to determine the service partition.
If you make it a new application, it can become the entrypoint (/proxy) for multiple bounded contexts


text:
Q: Singleton design pattern, static access non static? I think to a common Singleton Design Pattern:
public class Singleton{

   private static Singleton instance;

   private Singleton(){}

   public static Singleton getInstance(){

    if(instance==null)
       instance=new Singleton();

   return instance;

   }
}

as far as I know, costructors are NON static methods because they can use the context reference "this" (which is forbidden in static contexts). On the other hand, static members can access only static members.
So how is it possible that static member getInstance() is accessing the non static member constructor?

A: When you see an object creation like new Singleton() you must distinguish the new operator from the constructor code or to be more precise the initializer code.
The new operator is "like" a static method call. It doesn't need an instance of an object, because it creates one.
The constructor code is more "like" an instance method, except that it has no return type. But it can access the this reference.
At least you will see the difference when you dive into the generated bytecode. The new operator will lead to this bytecode instruction.
NEW yourpackage/Singleton

This instruction only creates the object in memory. See jvms-6.5.new
After the object is created it is initialized by executing the initializer code. In the bytecode it looks like:
INVOKESPECIAL yourpackage/Singleton.<init> ()V

The initializer code is more than only the constructor code. It invokes the super class's initializer and initializes instance fields.
Also see the java virtual machine specification 2.9

At the level of the Java Virtual Machine, every constructor written in the Java programming language (JLS §8.8) appears as an instance initialization method that has the special name . This name is supplied by a compiler. Because the name  is not a valid identifier, it cannot be used directly in a program written in the Java programming language. Instance initialization methods may be invoked only within the Java Virtual Machine by the invokespecial instruction (§invokespecial), and they may be invoked only on uninitialized class instances. An instance initialization method takes on the access permissions (JLS §6.6) of the constructor from which it was derived

A: Constructors are not methods. Static methods are associated with a class, and non-static methods are associated with instances of that class. You cannot call non-static method from a static method because there is no instance associated with the static method. You can call constructors from static methods because constructors are associated with classes, not instances.
Constructors can use "this" reference only after the object is instantiated, i.e. after the constructor is called.


text:
Q: Method does not exist or incorrect signature I am trying to implement a simple change for an apex class in production. I have the proper class and proper test class. The test class runs successfully in sandbox without errors, but apparently the error is coming from the TestHelper default test class in Salesforce. When trying to deploy in production it throws the error "Method does not exist or incorrect signature: void createUser(Id, String, String, Date, Integer) from the type TestHelper"
I've tried the usual of changing the method it references to public static void, but to no avail, it throws errors in code
This is my test class:
@isTest
private class OppLineItemInvntryBO_AType_OppStge_Test {

    @testSetup public static void setup() {
        Profile p = [SELECT Id FROM Profile
            WHERE Name = 'profile1' LIMIT 1];

            Date myDate = Date.newinstance(2019,07,01);

        User testUser = TestHelper.createUser(p.Id,
               'company1','legalentity1',myDate,327001);

And this is my TestHelper class:
public with sharing class TestHelper {
  public static User createUser(Id profileId, String company) {
    Integer rnd = getRandomNumber(10000);

    User user = new User(
      Username = 'john.doe@acme.com' + String.valueOf(rnd),
      Email = 'john.doe' + String.valueOf(rnd) + '@acme.com',
      LastName = 'Doe',
      FirstName = 'John',
      Alias = 'JD' + String.valueOf(rnd),
      ProfileId = profileId,
      LocaleSidKey = 'en_US',
            LanguageLocaleKey = 'en_US',
            TimeZoneSidKey = 'America/Los_Angeles',
            EmailEncodingKey='UTF-8',
            CompanyName = company);
    insert user;
    return user;
  }

  public static Integer getRandomNumber(Integer size){
    Double d = math.random() * size;
    return d.intValue();
  }
}

The full error is this:
API Name - OppLineItemInvntryBO_AType_OppStge_Test
Type - Apex Class
Line - 14
Column - 36
Error Message - Method does not exist or incorrect signature: void createUser(Id, String, String, Date, Integer) from the type TestHelper

A: You are invoking the createUser method with 5 parameters in OppLineItemInvntryBO_AType_OppStge_Test class where as in the TestHelper class , the createUser method accepts only 2 parameters. Thats why you are getting this error. Try to invoke the method with correct parameters.


text:
Q: Framework or Class for a TableView for a train scedule / time table I wonder if there is a framework or class for creating a train scedule similar to the below screenshot. Of course I know, I can create the table cells myself, but probably there is already a framework available.
Many thanks in advance.

A: To answer my own question: I finally did it by creating a custom table cell and drawing rectangles and lines for visualizing the route.


text:
Q: Martingale that converges almost surely to $-\infty$. The question is as follows:

Exercise 5.2.4. Give an example of a martingale $X_n$ with $X_n \to -\infty$ a.s. Hint: Let
  $X_n = \xi_1 + · · · + \xi_n$, where the $\xi_i$ are independent (but not identically distributed) with $E\xi_i = 0$.

My guess is that we should not make $\xi_n$ having a distribution such that it has zero expectation but are more and more likely to be negative. For example, we can have
$\mathbb{P}(\xi_n = 1) = 1/n$ and $\mathbb{P}(\xi_n = \frac {-1} {n-1}) = \frac {n-1} n$. But I am not sure how to prove $\sum \xi_n \to -\infty$.

A: Hint: you can let each $\xi_n$ be either $-1$ or positive (and like you said, each with zero expectation and more and more likely to be negative) and if you choose the
distributions right then you can use the Borel–Cantelli lemma to make sure that the probability that infinitely many $\xi_n$'s are positive is zero.


text:
Q: ASP.Net chart control not working properly in IE 9.0 I've used ASP:Chart control in my web application and it was working fine until i upgraded my browser from IE 8.0 to 9.0.
Now almost every time i come to the pages with some chart controls in them, the picture won't be rendered, but if i refersh the page it always renders the images properly.
So i did some research and made some changes to my "ChartImageHandler" key in web config. now it is something like this :

[chart Images folder] points to a folder inside my web app with full permission for my app pool user (In fact just for testing i gave full permission to everybody, definitely not a permission problem).
The problem is i do not have any problems with Firefox, Safarai, chrome or even older versions of IE, the problem happens only in IE 9.0 (BTW if i switch to compatibility mode in IE 9.0 it works fine).
When trying to watch this page using IE 9.0 i can see that chart images will be created in that folder, but they won't be removed, but using any other browser, those files are created and then removed without any problem.
I tried "storage=session" or "storage=memory" , no luck, although i'm sure i can not use "memory" because it's supposed to be deployed on a multi web server platform (Load balancers and stuff).
unfortunately most users are using IE 9.0 and i can not force them to use another browser or switch to compatibility mode.
I would appreciate your help guys.

A: try to add ImageStorageMode="UseImageLocation" to your chart. so the chart wil look like
<asp:Chart ID="Chart1" runat="server" DataSourceID="drawChartObjectDataSource" Height="200px"
    Width="800px" EnableViewState="True" ImageStorageMode="UseImageLocation">

and then go to your web.config and add AppSetting
<configuration>

  <appSettings>
    <add key="ChartImageHandler" value="storage=file;timeout=400;dir=c:\TempImageFiles\;" />
  </appSettings>

note the location of the stored images C:\TempImageFiles\ MUST BE EXSIT
Thanks I hope its solve the problem

A: I had exactly the same problem and I solved it.
My webpage where the asp:chart control was located has a masterpage reference
MasterPageFile="~/MasterPage.master"
In the masterpage i have some .js and .css references.

I solved this changing the order of the references (you have to reference first the javascript code)

I don't know why this is happening, IE 9.0 stuff.

A: Use fusion chart or zed chart
http://www.fusioncharts.com/
http://www.codeproject.com/KB/graphics/zedgraph.aspx

A: I have solved the issue by adding deleteAfterServicing=false parameter to the image handler in web.config. e.g.
<appSettings>
    <add key="ChartImageHandler" value="storage=file;timeout=400;dir=c:\TempImageFiles\;deleteAfterServicing=false;" />`
</appSettings>`

Please note that using this method the images will not be removed after servicing as the name of the parameter suggests. This means that you will have to manage that yourself.


text:
Q: Why is percona xtrabackup so slow and big When I call innobackupex with no arguments, it produces a backup of all databases. It takes three minutes, and produces an 8gb output. When I run mysqldump --all-databases, it takes 1 minutes, and produces a 1.5gb output. Since both of these outputs can be used to recreate the same database, why is xtrabackup so much slower and larger?

A: Is your ibdata1 file 8gb?  xtrabackup does a hot copy of the entire file.  The hot copy process doesn't need to lock tables (which allows your database to be available during the backup process).  The disadvantage is that unused space in your file is also backed up.


text:
Q: Basis of the Dual Space of Polynomial Spaces I have the following problem:
Let $V=\mathcal{P}_n(\mathbb{R})$ be the vector space of polynomials of degree $\leq n$. Define $\alpha_k : V\to\mathbb{R}$ by
$$
\alpha_k(p)=\int_{-1}^{1}t^kp(t)dt,\qquad p\in V.
$$
Show that $\{\alpha_0,\dots,\alpha_n\}$ is a basis for the dual space $V^*$ of $V$.
Here is my proof attempt:

We just need to show linear independence as $\operatorname{dim}(V^*)=\operatorname{dim}(V)=n+1$, and linearly independent sets of the right length form a basis.
We proceed by induction on $n$. The base case is trivial since when $n=0$ we have a set of only one vector and is thus linearly independent.
For the inductive step, suppose the result holds for $i=0,\dots,n-1$, i.e., the set $\{\alpha_0,\dots,\alpha_{n-1}\}$ is linearly independent. Thus whenever $c_0,c_1,\dots,c_{n-1}$ satisfy
$$
\sum_{k=0}^{n-1}c_k\alpha_k=0,\qquad\forall p\in\mathcal{P}_{n-1}(\mathbb{R})
$$
we have $c_0=c_1=\cdots=c_{n-1}$. Let $c_0,\dots,c_n$ satisfy
$$
\sum_{k=0}^{n}c_k\alpha_k=0,\qquad\forall p\in\mathcal{P}_n(\mathbb{R}).
$$
Suppose $n$ is even. The case where $n$ is odd is similar, and is omitted.
Let $p(t)=t$. Then we have
\begin{equation*}
\begin{split}
    0=\sum_{k=0}^nc_k\alpha_k(t) &= \sum_{k=0}^{n-
    1}c_k\int_{-1}^{1}t^{k+1}dt+c_n\int_{-1}^{1}t^{n+1}dt \\
    &= \sum_{k=0}^{n-1}c_k\int_{-1}^{1}t^{k+1}dt \\
    &\implies c_0=c_2=\cdots=c_{n-2}=0.\\
\end{split}
\end{equation*}
Now let $p(t)=1$. Then
\begin{equation*}
\begin{split}
    0 &= c_1\int_{-1}^{1}tdt+c_3\int_{-1}^{1}t^3dt+\cdots +c_{n-
    1}\int_{-1}^{1}t^{n-1}dt+c_n\int_{-1}^{1}t^ndt \\
    &= c_n\int_{-1}^{1}t^ndt \\
    &\implies c_n=0.
\end{split}
\end{equation*}
Finally, with $p(t)=t^3$, we have
\begin{equation*}
\begin{split}
c_1\int_{-1}^{1}t^4dt+c_3\int_{-1}^{1}t^6dt+\cdots +c_{n-1}\int_{-1}^{1}t^{n+2}dt &= 0 \\
\implies c_1=c_3=\cdots=c_{n-1} &= 0. \\
\end{split}
\end{equation*}
Hence the set $\{\alpha_0,\dots,\alpha_n\}$ is linearly independent. $\Box$

Does this work? Is there anywhere I left out too much detail or anything that needs to be modified? Any help is appreciated.

A: Another proof of linear independence is this:
Let $\lambda_0,...,\lambda_n$ be s.t. $\sum_{i=0}^n \lambda_i\alpha_i=0$. Hence, for all $p \in V$,
$$
\int_{-1}^1q(t)p(t)dt=0
$$
where $q(t)=\sum_{i=0}^n\lambda_it^i$. As $q\in V$, we deduce
$$
\int_{-1}^1q^2(t)dt=0
$$
hence $q(t)=0$ for all $t\in [-1,1]$. By the fundamental theorem of algebra, if $q$ were not the zero polinomial, it has only $n+1$ complex roots. But, since all $t \in [-1,1]$ are roots of $q$, $q$ is the zero polinomial. Hence, $\lambda_i=0$ for all $i\in \{0,...,n\}$

A: The proof is incorrect. You can calculate (easily) that
$$ \alpha_k(t^l) = \begin{cases} \frac{2}{n + l + 1} & \text{if $n + l$ is even} \\ 0 & \text{if $n + l$ is odd} \end{cases}$$
Your argument then goes: take an arbitrary linear combination $c_0 \alpha_0 + \cdots + c_n \alpha_n = 0$ and feed $t$ into it:
$$ (c_0 \alpha_0 + \cdots + c_n \alpha_n)(t) = c_0 \alpha_0(t) + \cdots + c_n \alpha_n(t) = \frac{c_1}{2} + \frac{c_3}{4} + \cdots = 0$$
but you cannot conclude from this that $c_1 = 0$, $c_3 = 0$, etc.

A: Big Hint:  The Legendre Polynomials $\{P_0(t), P_1(t), \ldots, P_n(t)\}$ form a basis for $\mathbb P_n(\mathbb R)$, the vector space of polynomials of degree less than or equal to $n$.  Form the matrix $A_{ij}=\alpha_i(P_j(t))$.  Use the orthogonality of the Legendre Polynomials to show that $A$ is non-singular.  Now if $\sum_k^{n+1} c_k \alpha_k=0$, then for $i=0,1, \ldots, n+1$,
$$
0 = \sum_{k=0}^{n+1} c_k \alpha_k(P_i(t))= \sum_{k=0}^{n+1} c_k A_{ki}.
$$
Can you now show that $c=(c_0, c_1, \ldots, c_n)$ must be the zero vector?
If you can prove that $\sum_k^{n+1} c_k \alpha_k=0$ implies that $c$ is the zero vector, you have proven that the $\{\alpha_k\}$ must be independent.


text:
Q: Async compression c# i have this code
  string dirName = "C:\\temp";

        if (Directory.Exists(dirName))
        {

            Console.WriteLine();
            Console.WriteLine("Файлы:");
            string[] files = Directory.GetFiles(dirName);

            foreach (string s in files)
            {
                Console.WriteLine(s);
                string sourceFile = $"{s}";
                string compressedFile = $"{s}z";

                Compress(sourceFile, compressedFile);
            }

        }

it shows me all files in directory and compress it.
method compress:
 public static void Compress(string sourceFile, string compressedFile)
    {

        using (FileStream sourceStream = new FileStream(sourceFile, FileMode.OpenOrCreate))
        {

            using (FileStream targetStream = File.Create(compressedFile))
            {
                using (GZipStream compressionStream = new GZipStream(targetStream, CompressionMode.Compress))
                {
                    sourceStream.CopyTo(compressionStream);
                    Console.WriteLine("Compressing file {0} is end. : {1}  compressede size is: {2}.",
                        sourceFile, sourceStream.Length.ToString(), targetStream.Length.ToString());
                }
            }
        }
    }

How can i do async compression of this files? should i use array of tasks? thank you

A: *

*Make Compress async method
public static async Task Compress()
{
    await Task.Run(() =>
    {
       //your compress logic
    }
}

*Call it as awaitable: await Compress(...);
You can also use Parallel.ForEach instead of your foreach loop.
But be aware that this code won't really execute in parallel. This is because that you are using IO functions.


text:
Q: Long polling in minute or single scheduler for a task - Approach for a notification system I have a requirement in which, I will plan multiple tasks for certain interval. And for each task a notification has to be pushed at certain interval of time.
I have two approaches, Either to write a single scheduler which will poll at each one minute and push the notification accordingly. Or I can schedule initialize a scheduler for each task. With the former method the solution is pretty much simple, with the later I can get more control on the scheduler, for instance I can put initial delay for each task specifically(Which is a requirement), then stop an individual task, resume etc. So far I am proceeding with the latter method. But I would like to know If it could be better to use so many scheduler in a single application. Or is it better to go with a single scheduler with 1 minute polling?. On an average I will have about 200+ tasks live at a time. Or for this can I depend on any other library?
So far my code
Sheduler which is an ExecutorService
       //Constructor
            public TaskScheduler(String taskName) {
                this.taskName = taskName;
                this.taskResult = new TaskResult();
                this.taskResult.setStartTime(getNewDate());
                scheduledExecutorService = Executors.newScheduledThreadPool(1);
//DB Operation
            }

    // To stop an individual task
                public TaskResult stop() throws InterruptedException {
                    try {
                        System.out.println("Stopping : " + this.taskName);
                        this.taskResult.setTaskName(this.taskName);
                        this.taskResult.setEndTime(new Date());
                        scheduledFuture.cancel(false);
                        scheduledExecutorService.shutdown();
//DB Operation
                        System.out.println("Stopping : finished - " + this.taskName + " @ "+ new Date());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return this.taskResult;
                }

        //Portion to add task
            public TaskScheduler schedule(Runnable task, long initialDelay, long frequency) throws Exception{
                this.taskResult.setFrequencyInSeconds(frequency);
                scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(task, initialDelay, frequency, TimeUnit.SECONDS);
                return this;
            }

Task thread with business logic
        public class TaskModel implements Runnable {
            private String taskName;

            public TaskModel() {

            }

            public TaskModel(String taskName) {
                this.taskName = taskName;
            }

            @Override
            public void run() {
//     DB operations
    .
    .

A: It is better to use a single scheduler, but you don't need to write your own scheduler for this. You could use single instance Executors.newScheduledThreadPool(1) with some number of threads to schedule all your tasks.
Think about the following code:
class TaskScheduler {
    private ScheduledExecutorService scheduledExecutorService;

    public TaskScheduler(int threads) {
        this.scheduledExecutorService = Executors.newScheduledThreadPool(threads);
    }

    //Portion to add task
    public TaskExecutionContext schedule(String taskName, Runnable task, long initialDelay, long frequency) {
        TaskExecutionContext context = new TaskExecutionContext(taskName);
        context.getTaskResult().setFrequencyInSeconds(frequency);
        ScheduledFuture scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(task, initialDelay, frequency, TimeUnit.SECONDS);
        context.setScheduledFuture(scheduledFuture);
        return context;
    }
}

class TaskExecutionContext {
    private String taskName;
    private TaskResult taskResult;

    private ScheduledFuture scheduledFuture;

    public TaskExecutionContext(String taskName) {
        this.taskName = taskName;
        this.taskResult = new TaskResult();
        this.taskResult.setTaskName(taskName);
        this.taskResult.setStartTime(new Date());
        //DB Operation on creation
    }

    public TaskResult stop() {
        try {
            System.out.println("Stopping : " + this.taskName);
            this.taskResult.setTaskName(this.taskName);
            this.taskResult.setEndTime(new Date());
            scheduledFuture.cancel(false);
//DB Operation on stopping
            System.out.println("Stopping : finished - " + this.taskName + " @ " + new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this.taskResult;
    }

    public TaskResult getTaskResult() {
        return this.taskResult;
    }

    public void setScheduledFuture(ScheduledFuture scheduledFuture) {
        this.scheduledFuture = scheduledFuture;
    }
}

If you need some extra operations on scheduling, creation and stopping tasks - probably, it's better to have separate TaskExecutionContext, which will perform all your needs.
Create a context when you need to schedule a task and pass it to scheduler.


text:
Q: AngularJS: Fields added dynamically are not registered on FormController I have the following static form in AngularJS:
<form name="myForm" class="form-horizontal">

  First Name:
  <input type="text" name="first_name" ng-model="entity.first_name">

  Last Name:
  <input type="text" name="last_name" ng-model="entity.last_name">

</form>

Angular creates a FormController for me and publishes it into the scope (under the form name). Which means I have access to properties like the following:
$scope.myForm.first_name.$error
$scope.myForm.last_name.$invalid
...

This is super useful!
But in my case I'm building a form dynamically, using directives:
<form name="myForm" class="form-horizontal">

  <field which="first_name"></field>
  <field which="last_name"></field>

</form>

The <field> directives don't resolve to actual <input> elements until after a while (after I've fetched some data from the server, linked the directives, etc.).
The problem here is that no field properties are defined on the form controller, as if dynamic fields didn't register with the FormController:
// The following properties are UNDEFINED (but $scope.myForm exists)
$scope.myForm.first_name
$scope.myForm.last_name

Any idea why? Any solution/workaround?
You can see the entire code in this jsFiddle:
http://jsfiddle.net/vincedo/3wcYV/

A: I ran into a similar problem myself and what i did to work around it was to place the name of the field before calling $compile on the template. A simple string.replace did the trick. Then again that was only possible because i was getting the field templates in through http and had access to the template text.
update: here is a fiddle with a little hack to make your example work
app.directive('field', function($compile) {
    var linker= function(scope, element){

    var template = '<input type="text" name="{{fname}}" ng-model="model">'
    .replace('{{fname}}', scope.fname);
        element.html(template)
        $compile(element.contents())(scope)
    }
  return {
    restrict: 'E',
    scope: {
      fname: '=',
      model: '='
    },

    replace: true,
      link: linker
  };
});

http://jsfiddle.net/2Ljgfsg9/4/

A: Update 7/31/2015 This has been fixed since 1.3, see here: https://github.com/angular/angular.js/issues/1404#issuecomment-125805732
Original Answer
This is unfortunately a short coming of AngularJS at the moment.  Angular's form validation doesn't work with dynamically named fields.  You can add the following at the bottom of your HTML to see exactly what's going on:

{{myForm|json}}

As you can see, Angular isn't getting the dynamic input name right.  There's currently a work around involving nested forms that can get kind of nasty, but it does work and (with a little extra work) will submit the parent form without trouble.
If you want, you can go drum up more support for the issue: GitHub Issue - dynamic element validation.  Either way, here's the code:
http://jsfiddle.net/langdonx/6H8Xx/2/
HTML:

        <form id="my_form" name="my_form" action="/echo/jsonp/" method="get">

                <ng-form name="form">
                    {{ field.label }}:
                    <input type="text" id="{{ field.name }}" name="{{field.name}}" data-ng-model="field.data" required>

Can't be empty.

                </ng-form>

            <input type="submit" />
        </form>

JavaScript:
MyController.$inject = ["$scope"];

function MyController($scope) {
    $scope.form = {};
    $scope.form.data = {};
    $scope.form.data.fields = []

    var f1 = {
        "name": "input_1",
        "label": "My Label 1",
        "data": ""
    };
    var f2 = {
        "name": "input_2",
        "label": "My Label 2",
        "data": ""
    };

    $scope.form.data.fields.push(f1);
    $scope.form.data.fields.push(f2);
}


text:
Q: AWS Lambda Function Does Not Show Access to DynamoDb I am doing this AWS tutorial to create an AWS policy and role for a Lambda function to have access to a DynamoDb. After I add the roles to the Lambda function I should get a diagram like this one from the tutorial:

This is what I get:

A: Based on the comments.
The lambda function works as expected. Sometimes console will not display all the resources it has access to. This does not mean that it can't access the required resources though.
Thus its better to check and see if it actually work despity of what console shows.


text:
Q: Illegal string offset when display data from array PHP After upgrade server from PHP 5.3 version to 5.6 my application get error like this:
Illegal string offset 'id'
This is the part of code where the error exist:
foreach($db_table_fields as $key => $value)
{
if($key == 'id')
{
$out .= '<input type="'.$value.'" name="'.$key.'[]" value="'.$row[$key].'"  />	';
}

I think I know that my variable required an array, but this is string - I still can't fix it. Maybe someone once had such a problem or have idea how fix it?
Thank You in advance for Your help.


text:
Q: The value Address of Entry Point different in PE Explorer and UltraEdit I wrote a basic helloworld.exe with C with the simple line printf("helloworld!\n");
Then I used UltraEdit to view the bytes of the EXE file and used also PE Explorer to see the header values. When it comes to Address of Entry Point, PE Explorer displays 0x004012c0.
Magic                            010Bh   PE32
Linker Version                   1902h   2.25
Size of Code                 00008000h
Size of Initialized Data     0000B000h
Size of Uninitialized Data   00000C00h
Address of Entry Point       004012C0h
Base of Code                 00001000h
Base of Data                 00009000h
Image Base                   00400000h
But in UltraEdit I see 0x000012c0 after counting 16 bytes after magic 0x010B.
3F 02 00 00 E0 00 07 03 0B 01 02 19 00 80 00 00
00 B0 00 00 00 0C 00 00 C0 12 00 00 00 10 00 00
00 90 00 00 00 00 40 00 00 10 00 00 00 02 00 00
04 00 00 00 01 00 00 00 04 00 00 00 00 00 00 00
00 10 01 00 00 04 00 00 91 F6 00 00 03 00 00 00
00 00 20 00 00 10 00 00 00 00 10 00 00 10 00 00
00 00 00 00 10 00 00 00 00 00 00 00 00 00 00 00
00 E0 00 00 C0 06 00 00 00 00 00 00 00 00 00 00
Which one is correct?

A: simply read about IMAGE_OPTIONAL_HEADER structure

AddressOfEntryPoint
A pointer to the entry point function, relative to the image base
  address. For executable files, this is the starting address. For
  device drivers, this is the address of the initialization function.
  The entry point function is optional for DLLs. When no entry point is
  present, this member is zero.

so absolute address of EntryPoint is AddressOfEntryPoint ? ImageBase + AddressOfEntryPoint : 0
in your case AddressOfEntryPoint == 12c0 and ImageBase == 400000
as result absolute address of EntryPoint is 12c0+400000==4012c0


text:
Q: Being someone's pet I heard teacher's pet in a movie and I know it means that teacher likes a student more than other students.
so I have a few questions:

*

*I was wondering if this expression can be applied to other people?

*Can it be used for adults?

Example: my wife is her mom's pet!

A: Another use of pet can be heard in parts of northern England.
It is used as an affectionate term of endearment (like saying hello dear).
Here are some examples:

How are you pet?

( used to refer to someone they know or to a stranger)

Have a great day pet.

other similar affectionate words used in England are dear, love, me duck etc. and any one of them could work in the sentences above.

A: Let's start with this.  Per Merriam-Webster dictionary the FIRST definition of pet is either:

a) a pampered and usually spoiled child, or
  b) a person who is treated
  with unusual kindness or consideration

and the meaning of a domesticated animal is only the SECOND definition.
Thus, teacher's pet is a person that the teacher treats with unusual kindness of consideration (generally because that person is a favorite of the teacher).
Like a teacher, any other person can have a pet:  a boss, a co-worker, a doorman, anyone.
Second, the similar terms pet project/theory/subject/etc are well-known and mean:

a plan, idea, or subject that you particularly like or are interested
  in

All of these terms are related.  For example, when you say that a student is the teacher's pet, it means that that student is a favorite of the teacher. A pet project is the same concept:  a pet project is a favorite project of someone.  Similar with theory, subject or whatever.  The term always means a favorite.
There is a related term that can be applied to other people and used for some adults.  It is pet cat.  It is an example of coach-speak and particularly popularized by American football coach Bill Parcells and his staffs.  The original meaning of the word as used by Parcells and his coaches is:

14 January 2007, Macon (GA) Telegraph, Michael A. Lough column:  "I
  knew it was a bad sign when Bill Parcells talked about how 'very, very
  athletic' his pet cat, Cody, was earlier in the week. Men should never
  publicly acknowledge owning a cat."
30 March 2007, Fort Worth (TX) Star-Telegram, "Trying to eliminate
  'cat' calls," pg. D6:  IRVING — Bill Parcells was a cat guy. He had a
  big, fat pet cat at his house. And he had his pet cats at Valley
  Ranch, too. Especially in April. "Pet cats" is a Parcellsism; they
  were the prospects whom a coach or scout adored. They are often so
  fond of such prospects they try to make sure their "pet cat" is
  drafted, regardless what the scouting consensus is. And every coach,
  general manager or scout has a pet cat; 2004 second-round flop Jacob
  Rogers was a Parcells' pet cat.

However, it has begun to take on a life of it's own and is being used on a broader basis:

Among Cowboys fans, pet cat has since come to refer to a player who is
  a bubble player (even making the practice squad is often considered
  pet cat success) and is commonly selected from the very bottom of the
  roster where you'll find late-round draft picks, undrafted free agents
  or even street free agents. The pet cat is often - and preferably -
  chosen without the slightest factual or quantifiable basis. In fact,
  some would argue that you do not choose your pet cat, your pet cat
  chooses you.

A: "Teachers pet" is a stand-alone idiomatic expression, and I have never heard "pet" used this way with other things.  I suppose it could be, but it doesn't sound very clever.
In creative writing, of course, you can metaphorically say someone is a "pet":

He was her pet, her plaything, something to whistle over when she was lonely and to brush away when she became bored.

but this negative meaning of an owned animal is quite different from "teacher's pet", which is usually more positive.
I suppose "teacher's pet" can apply to adults, but it would be weird, with possible sexual overtones.  In this case you would soften the idiom with "like a teacher's pet" to diminish any awkward connotations.


text:
Q: Ubuntu 21.04 drivers updates not working, E: Sub-process /usr/bin/dpkg returned an error code (1) Its been a while since i have installed Ubuntu and after 4 weeks later i remembered that i didn't configure or install any driver manually. This happened because my touch pad was lagging a bit and didn't feel the same as it was before on Ubuntu. I tried finding drivers for my laptop[dell latitude e6420] on dell original site, but the thing is they have only got drivers till Ubuntu 10.04
I tried them too though i wasn't sure that i was doing the right way but when i did they showed me this error
sameer@Lattitude:~/Desktop/latitude_touchpad_10.10_A02/scripts/chroot-scripts/fish$ sudo ./12-alps-driver-psmouse-maverick-2.6.35.22.sh
[sudo] password for sameer:
./12-alps-driver-psmouse-maverick-2.6.35.22.sh: line 2: /usr/share/dell/scripts/fifuncs: No such file or directory
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
alps-driver-psmouse-maverick-dkms is already the newest version (2.6.35.22).
0 upgraded, 0 newly installed, 0 to remove and 2 not upgraded.
1 not fully installed or removed.
After this operation, 0 B of additional disk space will be used.
Do you want to continue? [Y/n] y
Setting up alps-driver-psmouse-maverick-dkms (2.6.35.22) ...
Removing old alps-driver-psmouse-maverick-2.6.35.22 DKMS files...

------------------------------
Deleting module version: 2.6.35.22
completely from the DKMS tree.
------------------------------
Done.
Loading new alps-driver-psmouse-maverick-2.6.35.22 DKMS files...
Building for 5.11.0-25-generic
Building for architecture x86_64
Building initial module for 5.11.0-25-generic
ERROR: Cannot create report: [Errno 17] File exists: '/var/crash/alps-driver-psmouse-maverick-dkms.0.crash'
Error! Bad return status for module build on kernel: 5.11.0-25-generic (x86_64)
Consult /var/lib/dkms/alps-driver-psmouse-maverick/2.6.35.22/build/make.log for more information.
dpkg: error processing package alps-driver-psmouse-maverick-dkms (--configure):
 installed alps-driver-psmouse-maverick-dkms package post-installation script subprocess returned error exit status 10
Errors were encountered while processing:
 alps-driver-psmouse-maverick-dkms
E: Sub-process /usr/bin/dpkg returned an error code (1)
sameer@Lattitude:~/Desktop/latitude_touchpad_10.10_A02/scripts/chroot-scripts/fish$

After this I am just stuck, I have no clue what to do next any idea???
my laptop: Dell latitude e6420
bios version: A26
os: Ubuntu 21.04

Edit: I want a way to either new driver or how can re install them


text:
Q: css Background positioning of sprite Is the background-position css property used to indicated where in the element should the image be displayed (like this) or what part of the image should be displayed (like when using sprites) ?
In my instance i have a div of let's say 300px width, i want the image to be shown in the right part of that element so normally i just added a center right to my background declaration, though now my image is a spirit so how can i control the coordinate of the image that i want to display ?
 Seems to me that this background property act in 2 different way.. Am i missing something ?

A: If the place where you want to put element of the sprite is larger then the element then you need to put white space (trasnparent) around it. And you can't use keywords like center, you need to use pixels, because you will center whole sprite and not your element.
Using sprites is like using window where background is larger then background image so you need to position the window (actually you position the background).

A: If your container is larger than the background sprite image part you want to display then the other part of image will also be displayed. Better use Sprite cow to generate sprite it will give you the css for different parts of sprite image
http://www.spritecow.com/


text:
Q: kill spawn processes and stop for loop in bash I have a bash script that spawns other processes
script1.sh
for i in "${array[@]}"; do
    ./script2.sh $i
done

the problem is that if I terminate script2.sh the subsequent scripts gets called in the for loop and there's no way to kill script1.sh and stop the for loop.
how do I solve this issue?

A: You should be able to use break,
for i in "${array[@]}"; do
    if ! ./script2.sh $i ; then break ; fi
done


text:
Q: FREAD row criteria in R Since I have more than 10gb of data, I am looking to find a way to create a row filter criteria before reading the dataset into R so that the data read would be less than 10gb and the time required would be less.
Currently I am using the fread and even though it has the select criteria c("a","b"), I was not able to find a row filter critera (e.g. Col A > 2).
Is there a workaround for this in fread?
If not then is there any other way?


text:
Q: Drupal 6 how to prevent automatic password recovery and reset for a specific user I have an client website with a special user name 'guest' that allows unauthorized users to login and register for events.  But lately the password has been getting changed and it appears that it is being done at the login by requesting a password recovery/reset. That reset is done automatically and although it emails the temporary password to the ~manager~ of the guest account, it requires repeated resetting of the password back to its original and known value.
So, is is possible to prevent a password recovery/reset only when the user name is 'guest', specifically?  Thus not affecting other authorized users from getting a reset when they have forgotten their password?
FYI: the last post I saw on this on drupal was 2005 ... nothing since, and it was a node/16909. In that post a patch was offered, but it was applicable to Drupal version 5, and one of the comments was by Dries where he said that patch would not be folded into a release until a better solution was found.  I'm on Drupal 6.
Any solutions???
carl

A: Why not just do away with the guest account and use the systems built in anonymous user? Fighting Drupal always ends in tears.


text:
Q: Will binary model be automatically mirrored if train set inverted? Suppose we are training binary classifier to output 0s and 1s. It is trained and now returning float values y in range from 0 to 1.
Now suppose we inverted the train set (replaced 0s by 1s and vice versa) and trained the same classifier again.
Will it automatically return exactly 1-y values in the same points?
Does this depend on a model type, for example, random forest or neural network?

A: First of all, it depends on the model. If you use a simple decision tree with commonly known settings, your label values (0,1,2 etc.) don't event matter. So, using the same seed, with single-threaded applications of course, random forest will also give the inverted result, because it uses decision trees under the hood.
Generalizing this concept for gradient based methods is not healthy. Your gradient updates will have different numerical values and you go somewhere else in the parameter space. You could even fall in a different local minimum, which is highly possible in neural nets, and obtain slightly or totally different class assignments.
A model with convex loss function (e.g. logistic regression) might converge to inverted labels in the long run, which is intuitive; but, we're always stopping our algorithm at some point, in which it isn't guaranteed that you'll get exactly $1-y$ for your points. If it were guaranteed, then you'd also get inverted labels at each learning iteration.


text:
Q: pytest in pycharm: usage problems recently I started using pytest in pycharm.
My test program (test_a01_binary_hex.py, in the same directory as a01_binary_hex.py) looks like this:
import pytest
from a01_binary_hex import *

@pytest.mark.parametrize("bin, is_bin",
                         [
                             ("1001",True),
                             ("102", False),
                             ("11001 ", True),
                             ("1js2", False)
                         ])
def test_is_binary_number(bin, is_bin):
    assert is_binary_number(bin) == is_bin

@pytest.mark.parametrize("bin, is_bin",
                         [
                             ("1001",True),
                             ("102", False),
                             ("11001 ", True),
                             ("1js2", False)
                         ])
def test_is_binary_numberv2(bin, is_bin):
    assert is_binary_number_v2(bin) == is_bin

@pytest.mark.parametrize("hex, is_hex",
                         [
                             ("abc1",True),
                             ("102abcdefg", False),
                             ("11001 ", True),
                             ("1hij99", False)
                         ])
def test_is_hex_number(hex, is_hex):
    assert is_hex_number(hex) == is_hex

Now I have two questions:

*

*Why do I have to specifically import a01_binary_hex? In other examples I have seen the functions of the file could be used without specifically importing.

*When executing the test program through pycharm, the test only executes the last of the three parametrize blocks, but I would like to have the output of all three blocks:

...
elif version.LooseVersion(pytest.version) >=
version.LooseVersion("6.0"):
============================= test session starts ============================= collecting ... collected 4 items
test_a01_binary_hex.py::test_is_binary_numberv2[1001-True] PASSED
[ 25%] test_a01_binary_hex.py::test_is_binary_numberv2[102-False]
PASSED        [ 50%]
test_a01_binary_hex.py::test_is_binary_numberv2[11001 -True] PASSED
[ 75%] test_a01_binary_hex.py::test_is_binary_numberv2[1js2-False]
PASSED       [100%]
============================== 4 passed in 0.02s ==============================
Process finished with exit code 0

I am using python 3.10 (platform win32 -- Python 3.10.4, pytest-7.1.3, pluggy-1.0.0).
Kind regards
Bastian


text:
Q: Highlight rows in quick edit view In the quick edit view, I would like some rows to be highlighted based on values from two columns. One of the columns is a choice column and the other is a text column.
I was able to highlight using js and one column.How can I check values in 2 columns for highlighting the rows. Would appreciate any help!thanks.
Here is my current code:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $Text = $("td.ms-cellstyle.ms-vb2:contains('test2')");
        $Text.css("background-color", "#EAC117");
    });
</script>

A: Plenty alternative solutions explained here:
https://sharepoint.stackexchange.com/search?tab=newest&q=user%3a32871%20icc
Basic concept is to make the row color itself, instead of using bloated jQuery and ductaping caode on the page after it already loaded.
 =IF(  AND ( [TextField]="text2" , [ChoiceField] = "choice1" )
     ,"<IMG src="blank.gif" onload="""

       Execute JavaScript to color 'this' TR row

     ,"<!--Non matching fields-->"

 )

Note: same can be done with CSR - Client Side Rendering, also no jQuery required


text:
Q: Is there a way to use translateZ on an element without it automatically antialiasing all nested text? I'm doing some simple transitions in my page (basic stuff like fades with opacity, background color changes, and border radius updates) and experiencing some flicker, both in the elements I'm animating and other unrelated elements on the page. Generally the quick fix for something like this is to add translateZ(0) to the element that you're animating, but in Webkit when you do this it seemingly automatically sets all nested text to -webkit-font-smoothing: antialiased.
This is an undesired effect for me as I frequently use -webkit-font-smoothing: antialiased and -webkit-font-smoothing: subpixel-antialiased throughout my pages to ensure my text is looking its best when it can.
Is there any way to avoid this side-effect of using translateZ(0)? FYI: this same thing happens when applying -webkit-backface-visibility: hidden.


text:
Q: C# WPF Draw equilateral polygons programatically I'm working on a method to programatically draw equilateral polygon shapes in C#, WPF. But I have been stuck and I can't solve calculating the angles. Where is the problem? How should I correct this? I have given the public int, R(radius) a value of 100.
private Path EquilateralPolygon(int sides)
    {
        //Centering
        Point center = new Point(canvasSize.Width / 2, canvasSize.Height / 2);

        PathFigure myPathFigure = new PathFigure();

        int alfa = 360 / sides;
        int[] angles = new int[6];
        for (int i = 0; i < sides; i++)
            angles[i] = 360 - alfa * i;

        MessageBox.Show(angles.Sum().ToString());

        Point A = new Point(center.X, center.Y - R);

        myPathFigure.StartPoint = A;
        PolyLineSegment myLineSegment = new PolyLineSegment();
        for (int i = 1; i < sides; i++)
        {
            myLineSegment.Points.Add(new Point(center.X + Math.Cos(angles[i]) * R, center.Y + Math.Sin(angles[i]) * R));
        }

        myLineSegment.Points.Add(A);

        PathSegmentCollection myPathSegmentCollection = new PathSegmentCollection();
        myPathSegmentCollection.Add(myLineSegment);

        myPathFigure.Segments = myPathSegmentCollection;

        PathFigureCollection myPathFigureCollection = new PathFigureCollection();
        myPathFigureCollection.Add(myPathFigure);

        PathGeometry myPathGeometry = new PathGeometry();
        myPathGeometry.Figures = myPathFigureCollection;

        Path myPath = new Path();
        myPath.Stroke = Brushes.Red;
        myPath.StrokeThickness = 1;
        myPath.Data = myPathGeometry;

        return myPath;

    }

A: You've posted a lot of code and were not specific about how it's not working, so there may be more than one issue with your code. However, one big issue is that the Math.Cos (and related trig methods) take the angle in the form of radians, not degrees as you have them.

Parameters
d

Type: System.Double An angle, measured in radians.

You will need to convert them to radians. To convert, multiply by π (available via Math.PI) then divide by 180 degrees.
myLineSegment.Points.Add(
    new Point(center.X + Math.Cos(angles[i] * Math.PI / 180.0) * R,
    center.Y + Math.Sin(angles[i] * Math.PI / 180) * R));

EDIT: In addition to the radians/degrees issue, I can see you may be experiencing integer truncation, both in the use of your angles array and your calculation of alfa. I would suggest you try changing your use of integers to double so that your code works fine with fractions of a degree.


text:
Q: SSH...Reading PCAP file to determine the IDle time and connection type of a SSH connection I am develping a project in Python for analysing SSH.
Curently i am stuck at two things:

*

*Determining the idle time of a connection (percentage of time when no data was transferred over the connection)

*Determining the connection type ( shell, tunnel, scp etc..) -> What sort of channel is inside the connection

How to approach this problem?

A: Working with encrypted traffic can sometimes reveal a surprising amount of information when exploiting domain-specific details. It is worthwhile revisiting past research to understand the methodologies. For SSH in particular, I recommend reading Dawn Song's paper on inferring login passwords from SSH sessions.
Another example: Bro uses a heuristic discern successful from unsuccessful logins based on the number of bytes transferred at the beginning of the connection.
In general, I recommend recording traces of the activity you want to profile/classify later. This way, you have ground truth and can find out where SSH behaves differently from what you expect.

*

*To determine the idle time of interactive sessions, you need to understand the noise, if any, that SSH injects during periods of no activity. Then you may create a time series of the number of bytes transferred and experiment with the time resolution to see what granularity models best your trace. Moreover, you can decompose the times series into two components, one being SSH protocol noise and one user activity.

*This sounds like a classical unsupervised learning issue: clustering, e.g. k-means or mixtures. Coming up with the right set of features will probably involve some research. For example, determining an interactive session from a tunnel could be difficult if the tunnelled connection is also interactive. In your model, you could factor in the size delta or even include more context, such as in stepping stone detection.


text:
Q: substr with a custom field in Wordpress I'd like to use substr function to remove unnecessary characters from a link.
I'll put an "youtube" input on post editor, but I need to ignore "https://www.youtube.com/watch?v=" and print only the video ID (such wGoM_wVrwng).
So I tried:
<?php
echo substr('https://www.youtube.com/watch?v=wGoM_wVrwng', 32);
?>

But, I need to put an <?php the_field(); ?> there. something like
<?php
echo substr('https://www.youtube.com/watch?v= **THE_FIELD()**', 32);
?>

how to proceed?
Thanks in advance

A: <?php
  if (preg_match('%http(?:s)?://(?:www\.)?youtu(?:be\.com/watch\?v=|\.be/)(\w*)(&(amp;)?[\w\?=]*)?%', $subject, $regs)) {
      $result = $regs[1];
  } else {
      $result = false;
  }
?>

Now if $result !== false, it contains that part (the video ID).
Also this would work with and without https, with youtu.be and youtube.com, etc.

A: You can use a simple way if the delimiter i am using is unique.
$link = "https://www.youtube.com/watch?v=123456";

$array = explode("?v=", $link);
var_dump($array);
array (size=2)
  0 => string 'https://www.youtube.com/watch' (length=29)
  1 => string '123456' (length=6)

$sameLink = implode("?v=", $array);
echo $sameLink;

https://www.youtube.com/watch?v=123456


text:
Q: Convert Dynamic Column Mysql to JSON Heiii i have some problem, i have a dynamic query / pivot table mysql, i want convert this query to json, this is my script php
$db=new mysqli($dbhost,$dbuser,$dbpass,$dbname);
$supervisor='ganda.padeardja';
//-- query
$multi="
SET @SQL = NULL;

SELECT
GROUP_CONCAT(
DISTINCT CONCAT(
'MAX(IF(salesman = ''',
salesman,
''', total_aktivitas, 0)) AS `',
salesman,
'`'
)
) INTO @SQL
FROM
v_dashboard_supervisor_activity2
WHERE
supervisor LIKE '%ganda.padeardja%';

SET @SQL = CONCAT(
'SELECT v_calendar.cdate as aktivitas,',
@SQL,
' FROM v_dashboard_supervisor_activity2 RIGHT JOIN v_calendar ON v_calendar.cdate=v_dashboard_supervisor_activity2.tgl_aktivitas WHERE cdate BETWEEN CURDATE() - INTERVAL 6 DAY AND CURDATE() GROUP BY cdate ORDER BY cdate ASC '
);

PREPARE stmt
FROM
@SQL;

EXECUTE stmt;

";
if($result=$db->multi_query($multi)) {
$i=0;
do{
$db->next_result();
if(++$i==5)$result=$db->store_result();
}while($db->more_results() && $i<5);
}
$data=array();
$i=0;
print_r($db->error_list);
while($meta=$result->fetch_field()){
$data[$i]=array();
$data[$i]['name']=$meta->name;
$data[$i++]['data']=array();
}
$result->data_seek(0);
while($datas=$result->fetch_row()){
$i=0;
foreach($datas as $d){
$data[$i++]['data'][]=$d;
}
}
echo json_encode($data);

But result are :

Array ( )
Fatal error: Call to a member function fetch_field() on a non-object
  in D:\xampp\htdocs\test\index_try2.php on line 53

And the results I expected was like this :
[{"name":"aktivitas","data":`["2015-11-22","2015-11-23","2015-11-24","2015-11-25","2015-11-26","2015-11-27","2015-11-28"]},

{"name":"abdul.qodir","data":["0","11","4","6","2","6","1"]},{"name":"andrinanta.putra","data":["0","4","7","6","5","0","0"]},{"name":"ganda.sls","data":["0","0","0","0","0","0","0"]},{"name":"paulus.jatmiko","data":["0","5","5","4","5","5","0"]},{"name":"sandy.wibowo","data":["0","0","0","6","5","12","0"]}]

Can you help me where I made a mistake and miss something ??