text:
Q: Unable to load some functions from DLL with GetProcAddress() I'm trying to build a DLL which I would later like to inject into some processes using the SetWindowsHookEx() function. Strange thing is that when I try to load the DLL and try to get use GetProcAddress to get the address of the procedure contained within it, it returns NULL if I try to get the address of the CBT message handling procedure, but it works fine for the other functions.
This is the code.
DLL HEADER (.h)
#include <windows.h>

extern "C" {
    __declspec(dllexport) LRESULT CALLBACK hookProc(int code, WPARAM wParam, LPARAM lParam);
    __declspec(dllexport) int add(int a, int b);
}

DLL FILE (.cpp)
#include "SimpleHook.h"

extern "C" {
    __declspec(dllexport) LRESULT CALLBACK hookProc(int code, WPARAM wParam, LPARAM lParam) {
        return CallNextHookEx(0, code, wParam, lParam);
    }

    __declspec(dllexport) int add(int a, int b) {
        return a + b;
    }
}

MAIN FILE
#include <iostream>
#include <windows.h>
#include <tchar.h>

int main(int argc, char* argv[]) {
    HINSTANCE dllHandle = LoadLibrary(_T("SimpleHook.dll"));

    if (dllHandle) {
        // returns the correct address
        cout << "add address: " << GetProcAddress(dllHandle, "add") << endl;

        // returns NULL
        cout << "hookProc address: " << GetProcAddress(dllHandle, "hookProc") << endl;
    }
}

If I use GetLastError() I get the 127 error code with means:

ERROR_PROC_NOT_FOUND: The specified procedure could not be found.

Strange thing is that the other functions from the same file are loaded correctly.
Any help is greatly appreciated!

A: The calling convention changes the name mangling. __stdcall functions always have their names prepended by _ and mangled in some other ways too, so the link fails, but the __cdecl function isn't mangled and so it's found.
To import from a DLL that you built with __declspec(dllexport), you should always include a header with __declspec(dllimport) on everything you want to import and link the lib you got from building the DLL. This will guarantee that all of your functions link correctly, and you don't have to go down to C-compatible linking.
You shouldn't be using GetProcAddress, nor extern "C" in conjunction with __declspec(dllexport).
Header:
#include <windows.h>

#ifndef MAIN
#define DLL_API __declspec(dllexport)
#else
#define DLL_API __declspec(dllimport)
#endif

DLL_API LRESULT CALLBACK hookProc(int code, WPARAM wParam, LPARAM lParam);
DLL_API int add(int a, int b);

DLL .cpp file:
#include "SimpleHook.h"

DLL_API LRESULT CALLBACK hookProc(int code, WPARAM wParam, LPARAM lParam) {
    return CallNextHookEx(0, code, wParam, lParam);
}

DLL_API int add(int a, int b) {
    return a + b;
}

Main .cpp file:
#define MAIN
#include "SimpleHook.h"

int main(int argc, char* argv[]) {

    if (dllHandle) {
        // returns the correct address
        cout << "add address: " << add << endl;

        // returns NULL
        cout << "hookProc address: " << hookProc << endl;
    }
}

Don't forget to add the lib to the linker.

A: The CALLBACK macro resolves to __stdcall. Therefore, you have to prepend an underscore character and append the size of the arguments to the function's name:
cout << "hookProc address: " << GetProcAddress(dllHandle, "_hookProc@12")
     << endl;

A: You must use a tool such as dumpbin or Dependency Walker to learn the mangled name.
Or you can use a DEF file when linking, to put a name of your choice in the export table.


text:
Q: Why do we require $K$ to be compact instead of just finite in $(X=\mathbb{R} \cup \{P\}, \tau_2=\tau_e \cup \{X\setminus K\})$ for compactness? Example 1:
Let $\tau_{disc}$ be the discrete topology
We know $(\mathbb{R},\tau_{disc})$ is not compact
If we add a point P so that  we have $X=\mathbb{R} \cup \{P\}$ and define a new topology as
$\tau_1=\tau_{disc} \cup \{X\setminus F\}$, where $F$ is $F\subseteq \mathbb{R}$ and  finite, then the new space $(\mathbb{R},\tau_1)$ is compact.
The reason is that if we take any open covering, there would be an open set containing P  which is almost everything but a  finite quantity $t$ of points, then we can take t open sets, one for each point, and we have a covering made of $t+1$ open sets
Example 2
Let  $\tau_{e}$ be the euclidean topology
We know $(\mathbb{R},\tau_e)$ is not compact
If we add a point $P$ so that  we have $X=\mathbb{R} \cup \{P\}$ and define a new topology as
$\tau_2=\tau_e \cup \{X\setminus K\}$, where $K$ is $K\subseteq \mathbb{R}$ and  compact, then the new space $(\mathbb{R},\tau_2)$ is compact.
Why isn't enough to apply the same reasoning as in Example 1 and define K as finite, instead of compact?

A: It is certainly possible to give $\Bbb R\cup\{P\}$ the topology $$\tau_3=\tau_e\cup\{X\setminus F:F\text{ is a finite subset of }\Bbb R\}\;,$$ and the resulting space is indeed compact. It is not, however, Hausdorff: if $x\in\Bbb R$, there do not exist $U,V\in\tau_3$ such that $x\in U$, $P\in V$, and $U\cap V=\varnothing$. The space $\langle X,\tau_2\rangle$, on the other hand, is Hausdorff, and since it is compact and Hausdorff, it is even normal. (In fact it turns out to be homeomorphic to $S^1$, the unit circle, so it is even metrizable.) Thus, $\langle X,\tau_2\rangle$ is a much nicer space than $\langle X,\tau_3\rangle$. Thus, if we're looking for a nice compact space that has $\Bbb R$ as a dense subspace, $\langle X,\tau_2\rangle\rangle$ is preferable to $\langle X,\tau_3\rangle$. (Some people even make Hausdorffness part of the definition of compactness, so for them the space $\langle X,\tau_3\rangle$ isn't compact.)
In any case, these examples are almost certainly setting you up for the definition of the one-point (or Alexandroff) compactification. A compactification of a space $X$ is an embedding of $X$ into a compact Hausdorff space $Y$ as a dense subspace. Your examples embed $\langle\Bbb R,\tau_{\text{disc}}\rangle$ and $\langle\Bbb R,\tau_e\rangle$ as dense subsets of compact Hausdorff spaces, so they are example of compactifications. My example above is an embedding of $\langle\Bbb R,\tau_e\rangle$ into $\langle X,\tau_3\rangle$ as a dense subset, and $\langle X,\tau_3\rangle$ is compact, but it's not Hausdorff, so this is not an example of a compactification of $\langle\Bbb R,\tau_e\rangle$.
Your examples are not just compactifications: they are compactifications in which only one point has been added to the original space, hence the name one-point compactification. It turns out that such a compactification of a space $\langle X,\tau\rangle$ exists if and only if $X$ is a locally compact Hausdorff space, and in that case the one-point compactification is defined exactly as in Example 2: the open nbhds of the new point $P$ are the sets of the form $\{P\}\cup(X\setminus K)$, where $K$ runs over all compact subsets of $X$.

A: The 2nd version is a general construction for any (Haussdorf) topological space $X$, and is called the 'one point compactification'.
If we have an open cover $U_i$ of $X\cup\{P\}$, then $P$ is also covered by some base set $U_i=(X\cup\{P\})\setminus K$, but then the rest must cover the compact $K$ and thus a finite subcover can be selected.
Observe that the 1st version is a special case of the above, as in a discrete topological space the singleton sets are all open, thus they form an open cover, so exactly the finite subsets  are the compact ones.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Random String generation from a given string, and inverse transform I am working on a requirement where a function f will use string s as a seed and generate n no of strings y0..n , I can easily do this, but I also want to do inverse ie, f-1(yi) of generated strings will give me back s.
y0 = f(s) # first time I call f(s) it gives me y0
y1 = f(s) # second time I call f(s) it gives me y1
...
yi = f(s) # ith time I call f(s) it gives me yi
and so on.
The inverse function,
s = f-1(yi)
How can find the functions f and f-1, the other constraint the character size cannot to be too large for these strings, say max 20-25 characters.
Any suggestions please ?

A: Ok, this will get too channel-coding specific if I do it in broadness, here, but:
These are mathematical concepts, so let's map strings to numbers and look at them algebraically:
Your 20-character string space, assuming we're just using the 128 common ASCII characters, has 27 * 20 elements. That's pretty many elements.
However, communication technology has a method called scrambling which is a reversible process of mingling the bits in a sequence in a way that spreads the per-bit energy over the whole sequence. That leads to pretty randomly looking bit streams. It's typically implemented using feedback shift registers.
It's possible to find a 2140 state LFSR that fulfills your scrambling needs, and you can interpret the output of a multiplicative scrambler as the next element in your sequence.
However, please be aware that your problem is a hard one, which I hope I've illustrated sufficiently -- getting something that has good random properties is a harsh thing, and I can't recommend implementing something like that yourself -- it's going to make problems as soon as you need to rely on mathematical properties of your pseudorandom string.


text:
Q: Communication between services in a microservices architecture, is direct communication okay? I've been reading a lot on why one should use messages (w/ event sourcing/CQRS) for microservices communication and I get it. But most of the stuff I read online state that the main reason for using message brokers over direct http REST API communication is the cascade failure effect when a a service is down. Well, that can be solved by making services high available.
For me, the main reason behind using messaging is the fact that if one uses direct http requests then it's a synchronous request, even if using callbacks, the service is still expecting a response and that makes the microservices highly coupled, turning it into basically a distributed monolith (we kind of lose the microservices main benefits, right?).
With an event driven architecture the microservices are decoupled and it's certain that a given request will be executed eventually. But what if I need the requests do be executed synchronously? As far as I understand, a given user can make a request to create a certain entity, and if one the needed services is down, the user will just have to wait for it to go up again to see its entity created. The same goes with high loading scenarios, the "request" won't fail but it can take a long time to processed.
Not to mention read operations, those have to be synchronous.
So, I see two different use cases, using an event driven archicture in microservices is preferred because it enables low coupling between services, but it only fits eventual consistency scenarios. The other use case is when requests do have to be synchronous, would you still suggest using an event driven architecture? Or is it okay to use direct http REST calls between the services? Or microservices shouldnt be used at all when synchronous requests are a requirement?
Update: I changed some terms that were not correct and did not express what I meant

A: You mix a couple of things here, let's go in order:
1. "Event sourcing" is not a competing thing to "REST Endpoints", they have absolutely nothing to do with each other. "Event sourcing" is just a storage strategy for things that are best represented as a series of changes, instead of the end-state.
"REST API" (I think you just mean HTTP) is a communication technology. They are on completely different levels of architecture.
2. REST Endpoints are synchronous. No, they're not. Synchronicity is an implementation detail. You can call HTTP endpoints asynchronously very easily. Maybe you mean that the server has to do things immediately before returning the response. Even that isn't true, there is no such requirement of HTTP, nor REST.
3. Neither of the above makes services a "distributed monolith". A distributed monolith is the result of badly placed responsibilities, or often, no responsibilities at all. For example having a bunch of CRUD services and then one or few "smart" services that know almost everything. Or a bunch of small services that all know basically the same things (the same or similar events, data, formats, etc)
4. Event sourcing doesn't make services decoupled. See point above, decoupling is achieved by placing responsibilities correctly. Events sometimes help, but just having events that everybody has to know will still result in a big ball of mud.
With all that out of the way: Yes, you can use synchronous requests between services.
You should however prefer each service to be able to execute its "main function" without relying on other services. All the advantages are in this simple capability. This is what causes you service to be not just technically, but operationally independent from others.


text:
Q: Bad SOlr indexing with datastax. scaling from 1 node to 2 cassandra nodes and one search node I'm working with Datastax 3.1.4
I'm trying to go from a simple ring (with one node with Solr enable) to a little ring with 2 cassandra nodes (Solr disabled) and one search node (Solr enabled).
The cluster is well deployed according to Opscenter but when I insert data using the Solr HTTP API there is a problem...
I got no warning or error, but if values are inserted in all nodes (even the one with Solr enable) as I checked, the Solr index is wrong: According to solr only few docs are inserted 9 (whereas 20 has been inserted and are present in my cassandra table)
I'm quite sure it's a simple configuration problem, but I can't figure out what it is...

A: All of the Solr-enabled nodes must be in the same DC (data center), with only Solr-enabled nodes in that DC.
If you want to have non-Solr nodes, you need to put them in separate data centers than the Solr-enabled nodes.
A single DSE ring can handle multiple DC's or workloads, such as one or more Cassandra-only nodes or Cassandra-only and Hadoop analytics nodes, or Cassandra-Solr-enabled search nodes. Hadoop-enabled and Cassandra-only nodes can be mixed in the same DC, but Solr-enabled nodes cannot be mixed in a DC with Cassandra-only or Cassandra-Hadoop nodes.
You can read more about "mixed workloads" here:
http://www.datastax.com/docs/datastax_enterprise3.1/solutions/dse_search_cluster


text:
Q: Firebase Database - getData() returns wrong snapshot if parent value change was observed I integrated Firebase Realtime Database into my Xcode project, in which there are two UIViewControllers: TableViewController and DetailViewController.
The simplified database design looks like this:
{
    "uid1": {
         "category1": {},
         "category2": {}
    },
}

In TableViewController, I'm observing .value change under the current user, like so:
override func viewWillAppear(_ animated: Bool) {
    // dbHandle is removed in viewWillDisappear()
    dbHandle = dbRef.child(user.uid).observe(.value, with: { snapshot in
        // List all categories under user.uid
    })
}

In DetailViewController, I have some logic to check if there's any existing category data under <userID>/<categoryID>:
let categoryRef = dbRef.child(user.uid).child(categoryID)
categoryRef.getData( { error, snapshot in
    if snapshot.hasChildren() {
        // Handle error and return, since each user can have only one item for each category
    }
}

However, I noticed that getData() returns wrong snapshot if I ever visited TableViewController first. The parent value was returned in the snapshot, not the child specified by categoryID:
// 1. Visit TableViewController and observe `dbRef.child("uid1")` once, then remove observer

// 2. Then getData() returns wrong snapshot
dbRef.child("uid1").child("category3").getData { error, snapshot in
    // snapshot.value is {"category1": {}, "category2": {}}, which is wrong
    // snapshot.hasChildren() == true, which is wrong
}

I didn't see this issue if I never observed dbRef.child("uid1"):
// 1. Do NOT visit TableViewController and NEVER observe `dbRef.child("uid1")`

// 2. Directly go to DetailViewController and getData() returns right snapshot
dbRef.child("uid1").child("category3").getData { error, snapshot in
    // snapshot.value is nil, snapshot.hasChildren() == false, both are expected
}

Is this a bug in Firebase or is there anything that I'm missing?


text:
Q: Several Links to the Same URL I have an HTML file that has several links to the same URL. Is there a way to specify the URL once, instead of in each anchor? Currently, if I change the URL, I manually change it in each anchor. I would consider a Javascript solution, but would prefer something a bit simpler and lightweight. Here is a code sample with two links to google.com:

Preferred search engine

Google

A: You can use the <base> element:

For example:
<!DOCTYPE html>

<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Untitled 1</title>
<base href="https://www.google.com/">

Preferred search engine

Google

Any links you specicfy will be relative to the base URL, so if you had Preferred search engine the link would be https://www.google.com/foo.html

A: You have to use javascript to do that. jQuery will do nicely:
$(function() {
   $('a').attr('href','https://www.google.com');
});

Then you can call the same thing if the URL changed.
If you don't want to use jQuery this is the equivalent js code:

You cal trigger the changehref from anywhere you want.
BTW: the above function is equal to document.ready.


text:
Q: How to rename the default property name I can call an NPM package API with? For example, I want to use two similar libraries: @meforma/vue-toaster and vue-toastification.
Both of them set a .$toast property to the context to call their API.
Can I rename these properties, for example to $toast1 and $toast2? If not how can I use both of them if I want to register them globally?
Vue version - 3


text:
Q: In component data is fetched only when i make some changes in it I am trying to add markers on map, using a view and component
In view where i call an api and then i pass that data to component using v:bind but console.log in that component shows an empty array, when i make some changes in that component the page reloads and data is fetched following is my code in view and then component.

//Script for View

//Script For Map.vue

//Template for View
<template>

    <LoadingOverlay
            v-bind:loadingConfig="loadingConfig">
    </LoadingOverlay>
  <Maps v-bind:zones_and_locations="zones_and_locations"
  ></Maps>

</template>
//Template for Component
<template>

</template>

A: Data from the parent component are loaded asynchronously, so the created lifecycle hook inside the component is executed before the actual data comes, when they're still set as an empty array and are not reactive to change.
You can fix this by setting a watch inside the component, like this:
methods: {
  ...
},
watch: {
  zones_and_locations (newVal, oldVal) {
    this.loadGoogleMaps();
  }
}

orelse you can set a reference to the child component and invoke its method when data comes:

  <Maps
    v-bind:zones_and_locations="zones_and_locations"
    ref="myMap"
  ></Maps>

    async fetchPlacesData() {
      const { data } = await Catalogs.getZoneLocations();
      if (data.output === null) {
        this.nullDataException();
      } else {
        const places = [];
        data.output.forEach((value, index) => {
          places.push(value);
        });
        this.zones_and_locations = places;
        // using $refs
        this.$refs.myMap.loadGoogleMaps();
        this.loadingConfig.isLoading = false;
      }
    },


text:
Q: Unable to get statistics of some youtube videos using json link Am trying to get the statistics of youtube video using Api but am not able to get for some videos here is the link I used
https://www.googleapis.com/youtube/v3/videos?id=osY4Szdiv5s&key=apikey&part=statistics
https://www.googleapis.com/youtube/v3/videos?id=KdVvPQVbI_E&key=apikey&part=statistics
Am able to get the stattistics for the second video but not for the first video can any one help me out

A: There seems to be an issue with the API at the moment, an issue has been opened at Google's tracker - https://issuetracker.google.com/issues/37107133


text:
Q: Rails (Puma server) Phantomjs don't run on production I want to run PhantomJs on Controller.
in my file test.js
use 'strict';
console.log('HELLO WORLD');

in my_controller.rb
def test
  rs = `phantomjs 'path/to/test.js' `
  puts rs
end

When i run project on local in mode development,

*

*i go to action /test => it display 'HELLO WORLD' ( work )

But when i deploy, and run it on mode production
It not display HELLO WORLD, seem like phantom js don't run.
I use Phantomjs 2.1.1, rails 5.1.5, ruby 2.3.5 and boot use Puma server.
Anyone can show me a way can fix it.

A: try to make sure phantomjs is installed on your prod server, and the path setting is proper. run phantomjs  from your shell to verify this


text:
Q: How to find the roots of this equation I am trying to find the intercepts of:
$$y = 2 + 3x^2 - x^3$$
I have that the $y$-intercept is at $y=2$ so the point $(0,2)$ is on the graph.
But I'm having trouble finding the $x$-intercept. Factored, I have this equation:
$$3x^2 - x^3 = -2$$
$$x^2(3-x) = -2$$
Where can I go from here? Is there a simple way to do this by hand?
Same goes for this equation. What are the $x$-intercepts?
$$y = x^4 - 8x^2 + 8$$
I can't use the quadratic formula here right?

A: For the second equation:$$y=x^4-8x^2+8$$ let $A=x^2$.
$$y=x^4-8x^2+8\implies y=A^2-8A+8$$
$y=A^2-8A+8$ is in quadratic form, you can solve it like a quadratic equation.
Once you find the value of $A$, substitute $A$ for $x^2$, to find the possible values of $x$.
Step By Step. Solve for $A$ in:
$$0=A^2-8A+8$$
What do you get?

$$A=4\pm\sqrt{16-8}=4\pm2\sqrt 2$$
 Substituting $x^2$ for $A$, you get:
$$x^2=4\pm2\sqrt 2$$
$$x=\pm\sqrt{4\pm2\sqrt 2}$$

A: For the first by hand you must refer to the depressed cubic equation formula.
For the second just take $x^2=t$ to reduce to a quadratic equation.


text:
Q: Continuous covariance operator I have a really hard time to prove that
$\int_{H} \langle h,x-m \rangle^{2}\mu(dx) $
is continuous where $\mu$ is a gaussian measure, $h$ functional on  Hilbert space.
And also why do we need the covariance operator to be trace class , the only thing that I found is in order to be the variance finite.
All helps or hints are welcome.

A: First we translate the integral so that the mean value is $0$:
$$q(h) := \int \langle h, x-m \rangle^2 \, \mu(dx) = \int \langle h, x \rangle^2 \, \mu_0(dx)$$
Then we take a sequence $h_k$ converging to $h$:
$$q(h_k) = \int \langle h_k, x \rangle^2 \, \mu_0(dx)$$
Now,
$$\begin{align}
|q(h_k) - q(h)|
& = \left| \int \langle h_k, x \rangle^2 \, \mu_0(dx) - \int \langle h, x \rangle^2 \, \mu_0(dx) \right| \\
& = \left| \int \left( \langle h_k, x \rangle^2 - \langle h, x \rangle^2 \right) \, \mu_0(dx) \right| \\
& \leq \int \left| \langle h_k, x \rangle^2 - \langle h, x \rangle^2 \right| \, \mu_0(dx) \\
& = \int \left| \langle h_k, x \rangle + \langle h, x \rangle \right| \, \left| \langle h_k, x \rangle - \langle h, x \rangle \right| \, \mu_0(dx) \\
& = \int \left| \langle h_k + h, x \rangle \right| \, \left| \langle h_k - h, x \rangle \right| \, \mu_0(dx) \\
& \leq \int \|h_k + h\| \|x\| \, \|h_k - h\| \|x\| \, \mu_0(dx) \\
& = \|h_k + h\| \|h_k - h\| \int \|x\|^2 \, \mu_0(dx) \\
& < 3\|h\| \, \epsilon \int \|x\|^2 \, \mu_0(dx)  \\
\end{align}$$
which can be made as small as we want.
Sorry, I don't have time to explain more now. I will do it later, especially if you have questions.


text:
Q: gcloud nodejs datastore: how to create an entity with a parent? How to create an entity with a parent using gcloud, datastore and nodejs?
How to search for all the entities with a given parent?
Something like (this does not work):
var path = [{kind: 'Parent', id: parentId}, {kind: 'Me'}];
var key = ds.key(path);
var entity = {
  key: key,
  data: toDatastore(data, ['description'])
};
ds.save(entity)

Reading the docs I did not find any example of creating an entity with a given parent. I searched (without success) here:
https://googlecloudplatform.github.io/gcloud-node/#/docs/v0.19.1
while on the counterpart in python there are some specific proprieties to specify the parent entity:
http://googlecloudplatform.github.io/gcloud-python/latest/datastore-keys.html
Please provide an example of code of how create and search for an entity with a parent

A: I think you just want something like:
var key = ds.key(['Parent', parentId, 'Me']);

*

*Key docs


text:
Q: Using cURL to download a file, but with logging in before I am trying to automate file download with cURL. But the file can only be downloaded when you are logged in. The login is a quite standart POST request, which I have looked at in browser network analysis and now how it´s build up. Now how do I do it with cURL so that I get recognised as logged in and can download the file? Because obviously just sending the POST request before downloading won´t work.

A: Try one of these.
curl http://name:passwd@machine.domain/full/path/to/file

curl -u name:passwd http://machine.domain/full/path/to/file

A: You very likely need to store cookies. The answer by @jsotola is only appropriate for Basic authentication, which is becoming less common. And you said this is a POST request.
Have a look at the -b and -c options.
First issue a curl request to log in and save your cookies using the above mentioned options. Then repeat the call to download the file eg:
curl -b /tmp/cookies -c /tmp/cookies <url> ...

The point of using cookies is to store the authentication tokens, without which every call you make is independent from previous requests.
Of course it is possible that the website involves Javascript/Ajax and curl will not always do the job.
Bonus: if you try with a browser like Firefox, the Web developer tools can even generate the Curl requests for you.


text:
Q: How to make right alignment when using Tikz I use tikz to draw an image, below is part of the image. But the variable name is central alignment, how to make it right alignment?

Below is the related code
\foreach \i [count=\j from 1] in {5,4,3,2,1} {
\pic () at (-0.5,\i) {myarrow};
\node[xshift=-2.5cm] at (-1,\i) {VARIABLE NAME};
}

A: Is this what you seek? Use of text width=the longest length and align=left,center, right of your selections.

Code
\documentclass[border=10pt]{standalone}%[12pt,twoside,a4paper]{book}
\usepackage{graphicx,wrapfig,tikz}
\usetikzlibrary{positioning,shapes}
\tikzset{myarrow/.pic = {
\begin{scope}[rotate=-90,scale=0.5]
\draw[fill=black] (-0.5,0) -- (0,0.5)--(0.5,0)--(0.5,1)--
(0,1.5)--(-0.5,1)--(-0.5,0) ;
\end{scope}},
}

\begin{document}
\begin{tikzpicture}
\draw (0,0) rectangle (0,6);

% draw myarrows on the left side
\foreach \i/\k  in {5/{FUEL\_LEVEL\_TOT},4/{PBRAKE\_APPLIED\_HIGH},
3/{FUEL\_VOLUME},2/{FUEL\_LEVEL},1/{FUEL\_CONSUMPTION\_RATE}} {
\pic () at (-0.5,\i) {myarrow};
\node[xshift=-6cm,text width=8cm,align=right] at (-1,\i) {RTDB\_{\k}\_E};
}
\end{tikzpicture}
\end{document}


text:
Q: PDF printer decreases filesize of pdflatex output considerably. Why? This is probably not exactly a TeX question, but I assume many people concerned with TeX might also have ideas about this issue.
If I compile the following "minimum" example with pdflatex on Windows, the resulting PDF file is 92kb in size. If I then print it to a PDF file (using Acrobat 7), the resulting PDF file is 32kb in size. It looks the same (in particular it is not rasterized). Why is that and more importantly: are there any options I can give to pdflatex to create a file of this smaller size in the first place?
\documentclass[a4paper,12pt]{article}
\usepackage[T1]{fontenc}
\begin{document}
\textbf{Ad d}) By the residue theorem we have
\begin{eqnarray*}
\int_{\gamma }f &=& 2\pi i\sum_{z\in C\backslash \left\vert \gamma \right\vert }n(\gamma ,z)\mathop{res}(f,z) \\
&=&2\pi i(n(\gamma ,0)\mathop{res}(f,0)+n(\gamma ,\pi )\mathop{res}(f,\pi )+n(\gamma ,i\pi )\mathop{res}(f,i\pi )) \\
&=&-4ie^{\frac{1}{\pi -i\pi }}\approx 0.74-4.63i
\end{eqnarray*}
\end{document}

edit: I just tried it using the free program pdfcreator, and the size is even reduced to 22kb! Almost all of the size difference is due to the fonts part, as the space auditing of acrobats pdf optimizer tells me. Yet even this optimizer doesn't achieve these large savings, a printing process seems necessary. I wonder why.

A: Software by (Adobe) Acrobat is proprietary, and it would therefore only be speculation as to how/what is employed to obtain smaller file sizes though reprinting. However, there may be some standard techniques to "optimizing" PDF files, as suggested by the manual of QPDF. Although they distinguish between "linearization" and "optimization", I would suggest reading the "richly commented" QPDF_optimization.cc source file for specific techniques used in reprocessing the input PDF.
Edit: Acrobat's utility to "Reduce file size" option gives a broad overview of the types of reductions involved in reproducing a PDF. I would assume that similar optimization may be performed when reprinting an existing PDF. This includes, compression of images, embedded font removal (for standard, well-known/used fonts across platforms), transparency flattening, and others. Perhaps the file reduction stems from removal of items that does not influence functionality.


text:
Q: Normal map from height map I am trying to create a normal map from a height map in HLSL. I followed this https://stackoverflow.com/a/5284527/451136 which is for GLSL. Here is how I translated GLSL to HLSL:

GLSL:
uniform sampler2D unit_wave
noperspective in vec2 tex_coord;
const vec2 size = vec2(2.0,0.0);
const ivec3 off = ivec3(-1,0,1);

    vec4 wave = texture(unit_wave, tex_coord);
    float s11 = wave.x;
    float s01 = textureOffset(unit_wave, tex_coord, off.xy).x;
    float s21 = textureOffset(unit_wave, tex_coord, off.zy).x;
    float s10 = textureOffset(unit_wave, tex_coord, off.yx).x;
    float s12 = textureOffset(unit_wave, tex_coord, off.yz).x;
    vec3 va = normalize(vec3(size.xy,s21-s01));
    vec3 vb = normalize(vec3(size.yx,s12-s10));
    vec4 bump = vec4( cross(va,vb), s11 );

HLSL:
sampler2D image : register(s0);

noperspective float2 TEXCOORD;
static const float2 size = (2.0,0.0);
static const int3 off = (-1,0,1);

float4 main(float2 uv : TEXCOORD) : COLOR
{

    float4 color = tex2D(image, uv);
    float s11 = color.x;
    float s01 = tex2D(image, uv + off.xy).x;
    float s21 = tex2D(image, uv + off.zy).x;
    float s10 = tex2D(image, uv + off.yx).x;
    float s12 = tex2D(image, uv + off.yz).x;
    float3 va = normalize((size.xy,s21-s01));
    float3 vb = normalize((size.yx,s12-s10));
    float4 bump = (cross(va,vb), s11);

    return bump;
}

The output is a black and white image, with the darker pixels being more transparent (since the alpha is the height).

How can I generate a normal map like this http://www.filterforge.com/filters/3051-normal.jpg from a height map?
Edit

I followed the megadan's suggestions , and I also had some synthax errors that I fixed. Here is the working HLSL code:
float Width : register(C0);

float Height : register(C1);

sampler2D image : register(s0);

noperspective float2 TEXCOORD;
static const float2 size = {2.0,0.0};
static const float3 off = {-1.0,0.0,1.0};
static const float2 nTex = {Width, Height};
float4 main(float2 uv : TEXCOORD) : COLOR
{

    float4 color = tex2D(image, uv.xy);

    float2 offxy = {off.x/nTex.x , off.y/nTex.y};
    float2 offzy = {off.z/nTex.x , off.y/nTex.y};
    float2 offyx = {off.y/nTex.x , off.x/nTex.y};
    float2 offyz = {off.y/nTex.x , off.z/nTex.y};

    float s11 = color.x;
    float s01 = tex2D(image, uv.xy + offxy).x;
    float s21 = tex2D(image, uv.xy + offzy).x;
    float s10 = tex2D(image, uv.xy + offyx).x;
    float s12 = tex2D(image, uv.xy + offyz).x;
    float3 va = {size.x, size.y, s21-s01};
    float3 vb = {size.y, size.x, s12-s10};
    va = normalize(va);
    vb = normalize(vb);
    float4 bump = {(cross(va,vb)) / 2 + 0.5, 1.0};

    return bump;
}

I read that using GetDimensions to automatically get the width and height of the texture is supported on Direct3D 10.1 or higher, so the width and height of the texture must be passed into the shader since I need it to be compatible with Direct3D 9  as well.

A: One possibility is that your normals are pointing in the wrong direction. This could happen because OpenGL uses texture coordinates with the origin at the bottom left of the image where the Y axis points up and DirectX uses texture coordinates with the origin at the top left where the Y axis points down.
If you map out where the code is taking height samples for DirectX, you'll see that s01 is to the left, s21 is to the right, s10 is to the top, and s12 is to the bottom.  In OpenGL s10 and s12 will be reversed.
When you create the vector vb by subtracting s10 from s12 it will point one way for DirectX and the opposite way for OpenGL.  Now when you take a cross product between two vectors, it forms a perpendicular vector that can point in either of two directions depending on the order of the cross product using the right hand rule: http://en.wikipedia.org/wiki/Cross_product.  This will cause the cross products for DirectX and OpenGL to point in opposite directions.
So, if this is an issue, the fix could be to swap the order of the vectors in the cross product or to swap the locations of the s10 and s12 samples.
There is also an issue with your texture coordinates. uv should be in the range of [0, 1]. When you add off to it, it puts it out of range and the result depends on whatever texture addressing mode is active. In each of your tex2D samples, you'll need to divide the first component of off by the texture width and the second by the texture height.
Finally, the result of the cross product with have values in the range [-1, 1]. If you want to store this as a color, you need to convert these to [0, 1]. So something like cross(vb, va) * 0.5 + 0.5 will work.  When normal maps are sampled in a shader, the colors are then converted back into normal range of [-1, 1].


text:
Q: Como se modela um papel em orientação a objetos? Como normalmente se modela um papel (role) em orientação a objetos?
É por meio de uma composição, correto? Por exemplo, para modelar que uma Pessoa executa o papel de um Cliente ou Fornecedor, modela-se que a Pessoa tem um Cliente, ou um Fornecedor, etc.
Como fica isso na UML? E no código?
Como atua a delegação (forwarding) nessa história? (Vide exemplo)
Editado: Isso que dá ficar só na teoria. Demorei a perceber que meu problema é Cliente ter uma Pessoa e não o contrário... pelo menos o contrário não é necessário a princípio. Vide.

A: Copiado da resposta do Maniero, só que em pseudo-Java, para visualizar melhor (e tome boilerplate. Quem tiver o que melhorar é só editar).
De forma muito simplificada:
public class Pessoa {
    private String nome;
}

public interface Papel {
    void umMetodo();
}

public class Cliente implements Papel {
    private Pessoa pessoa;
    private BigDecimal credito;
}

public class Faturamento {
    public void venda(Cliente cliente) {
        System.out.println(cliente.getPessoa().getNome());
    }
}

Se desejar que pessoa tenha ciência dos papéis que ele exerce poderia fazer de duas formas:
public class Pessoa {
    private String nome;
    private Cliente cliente;
    private Fornecedor fornecedor;
}

Cada papel que for adicionar precisa mudar a classe, o que viola alguns princípios, mas que nem sempre é um problema.
Outra forma:
public enum TipoPapel { Cliente, Fornecedor }

public class Pessoa {
    private String Nome;
    private Map<TipoPapel, Papel> papeis = new HashMap<>();

    public void adicionaPapel(TipoPapel tipo, Papel papel) {
        papeis.put(tipo, papel);
    }
}

Em vez de enum poderia usar String que pode facilitar ou dificultar, dependendo do caso. Poderia usar outra estrutura, até mais especializada, no lugar do mapa. Poderia ter o controle dos papéis em um tipo separado que abstraísse o mapa.

A: De forma muito simplificada:
class Pessoa {
    string Nome;
}
class Cliente {
    Pessoa pessoa;
    decimal credito;
}
class Faturamento {
    Venda(Cliente cliente) => Write(cliente.pessoa.Nome);
}

Se desejar que pessoa tenha ciência dos papéis que ele exerce poderia fazer de duas formas:
class Pessoa {
    string Nome;
    Cliente cliente;
    Fornecedor fornecedor;
}

Cada papel que for adicionar precisa mudar a classe, o que viola alguns princípios, mas que nem sempre é um problema.
Outra forma:
enum TipoPapel { Cliente, Fornecedor }

class Pessoa {
    string Nome;
    List<(TipoPapel, IPapel)> papeis = new();
    AdicionaPapel(TipoPapel tipo, Ipapel papel) => papeis.Add((tipo, papel));
}

Coloquei no GitHub para referência futura.
Em vez de enum poderia usar string que pode facilitar ou dificultar, dependendo do caso. Poderia usar um dicionário no lugar da lista, ou outra estrutura, até mais especializada. E poderia usar um tipo específico no lugar da tupla. Poderia ter o controle dos papéis em um tipo separado que abstraísse a lista.
UML é uma das coisas mais trolhas que já vi, então não :)


text:
Q: Getting existing paypal account and email account error I have used the paypal express checkout payment method with config value 'SOLUTIONTYPE=sole' which enable the user to make the payment with debit or credit card but when I am trying to make the payment after filling the all the testing card details I get the below error:
"You cannot use an email address or card number that belongs to an existing PayPal account. If you have a PayPal account, please log in. If you don't, please change the email address or card number and try again."
Is there any option that I disable to checked the existing account..
See the below configuration value
$padata = '&METHOD=SetExpressCheckout';
    $padata .= '&RETURNURL=' . urlencode(PPL_RETURN_URL);
    $padata .= '&CANCELURL=' . urlencode(PPL_CANCEL_URL);
    $padata .= '&SOLUTIONTYPE=' . urlencode('sole');

Thanks

A: That error means the email address that you filled in the credit card payment option has been linked to a registered paypal account. So please update to a  new email address or that is never linked to an existing paypal account will bypass this error immediately.


text:
Q: Check if cached url and current url are the same or different I have a webview that is loading data and caching it , in the code below this cached data is being loaded if it is found
However I want the webview to reload from the network if it finds a change in the url rather than just loading the recent cached item
Is there a way for me to compare the current url with the cached one , or someway to have the webview load the cache if the same or the new one when different
wvStructue.settings.javaScriptEnabled=true
        wvStructue.settings.loadWithOverviewMode = true
        wvStructue.settings.useWideViewPort = true
        wvStructue.settings.databaseEnabled = true
        wvStructue.settings.domStorageEnabled = true
        wvStructue.settings.cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK
        wvStructue.settings.builtInZoomControls = true
        wvStructue.settings.displayZoomControls = false

A: Refer this link
Set webview cache mode LOAD_CACHE_ELSE_NETWORK.
Override WebViewClient methods :
@SuppressWarnings("deprecation")
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            if (view.getUrl().equals(failingUrl)){
                showInternetConnectionError();
            }
            super.onReceivedError(view, errorCode, description, failingUrl);
        }

        @TargetApi(android.os.Build.VERSION_CODES.M)
        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            onReceivedError(view, error.getErrorCode(), error.getDescription().toString(), request.getUrl().toString());
        }


text:
Q: Apache tika architecture & processing nodes I have just started exploring Apache Tika.
I want to check how apache tika back ground processes work.
I tried executing Tika in a standalone machine but wanted to know how it works in Cloudera Cluster real time environment.
Example: I have a 200 page pdf content and use Tika to extract the text or features. Will Tika execute this process using a single node (i.e considering one file as one block) or will it execute using multiple nodes?
Im just comparing Tika process to Mapreduce and learn if Tika is also processing a file block by block.
Please help me to understand this background processes.
I don't have the code with me now.
Please help me to understand this background processes work in terms of nodes.

A:
I want to check how apache tika back ground processes work.

Apache Tika uses an abstraction TikaInputStream on the top of Java's InputStream class. Which means in reads the files as stream of bytes. No blocks, nothing fancy at low level!

I tried executing Tika in a standalone machine but wanted to know how it works in Cloudera Cluster real time environment.
Example: I have a 200 page pdf content and use Tika to extract the
  text or features. Will Tika execute this process using a single node
  (i.e considering one file as one block) or will it execute using
  multiple nodes?
Im just comparing Tika process to Mapreduce and learn if Tika is also
  processing a file block by block.

Since you mentioned Map-Reduce specifically, the behavior of using Apache Tika on CDH cluster can be found here. Basically, on CDH, your MR app will read the files from HDFS (using blocks methodology) and process the split using the Apache Tika libraries just like you are doing on standalone basis. Note that processing will be splitted based on Input Splits(Underlying HDFS blocks). A working example can be found here :
https://github.com/ppruski/tika-hadoop-mapreduce
So you can definitely use CDH cluster to achive the efficiency of parallel processing as MR or Spark both uses same methodology to calculate input splits.


text:
Q: PHP session lost after 2nd redirect but not first I have a PHP project, which also has a Kohana PHP project in a subfolder on the site "/reports".
I redirect to the reports project like so:
redirectreports.php
<?php
session_start();
header('Location: /reports');
exit();

When a user clicks the href link, it opens the above in a new window. On the first click of the link, everything works fine and session data is available in the reports project.
The issue happens when I close the window of reports, and then click the reports link a 2nd time. My session data cannot be found the 2nd time I am redirected to reports.
I have tried passing the session id in the query string and then passing that to Session::instance('native', $_GET['id']);
But still get the following error:
Session_Exception [ 1 ]: Error reading session data.

A: Thanks for the comments.
The actual issue here was that there was an object being stored in the session data by the "reports" package. Result in a __PHP_Incomplete_Class error.
That class wasn't accessible to the core project and so the shared info is stored as an array rather than an object.


text:
Q: Flutter Go_router, save history of routes I have this code of router
final _router = GoRouter(
  routes: [
    GoRoute(
      path: '/',
      builder: (BuildContext context, GoRouterState state) {
        return const LoginScreenWidget();
      },
      routes: <RouteBase>[
        GoRoute(
          path: 'main',
          builder: (BuildContext context, GoRouterState state) {
            return const MainScreenWidget();
          },
          routes: [
            GoRoute(
              path: 'my-friends',
              builder: (BuildContext context, GoRouterState state) {
                return const FriendsScreenWidget();
              },
              routes: [
                GoRoute(
                  path: ':userId',
                  builder: (BuildContext context, GoRouterState state) {
                    return FriendProfileScreenWidget(
                      userId: state.params['userId'],
                    );
                  },
                  routes: [
                    GoRoute(
                      path: 'friends',
                      builder: (BuildContext context, GoRouterState state) {
                        return ProfileFriendsScreenWidget();
                      },
                    ),
                  ],
                ),
              ],
            ),
          ],
        ),
      ],
    ),
  ],
);

class AppRouterDelegate extends GetDelegate {
  @override
  Widget build(BuildContext context) {
    return Navigator(
      onPopPage: (route, result) => route.didPop(result),
      pages: currentConfiguration != null
          ? [currentConfiguration!.currentPage!]
          : [GetNavConfig.fromRoute('main')!.currentPage!],
    );
  }
}

And on different screens I go deeper and deeper. And it works the way I need it. But when I click back, I don't move back through the history, but go back to the beginning
context.go('/main')

context.go('/main/my-friends')

context.go('/main/my-friends/${friendsList[index].id}')

context.go('/main/my-friends/${userId}/friends')

context.go('/main/my-friends/${friendsList[index].id}')

How do I make it so that when we click back, we return to the previous page, and not to the initial one?
back buttons have this code
Navigator.pop(context);

At first I tried to do it through a regular Navigator, then through Navigator 2.0. But it didn't work. Then I found this go router and I liked it, but I can't solve the last problem

A: Use context.push('routeName') instead of context.go('routeName'). That should resolve the issue.


text:
Q: Using MinGw64 and CodeLite is running my program too slow I downloaded the MinGw64 compiler on my external drive D: and set its path on env variables accordingly.
I then proceeded to download the IDE CodeLite on the same D: and was able to create a project using the MinGw64 as the compiler.
When writing a simple Hello World it builds instantanly but then takes about 22 seconds to print the result on the Windows console.
Any idea what I might be doing wrong?


text:
Q: GDAL Calc using different raster grid sizes I have several GeoTIFFs (.tif) that I am conducting raster calculations on using gdal_calc.py, all three are of different sizes. These rasters can be best illustrated with the following image:

All three rasters domains overlap across the northern extent, however the blue raster is of full size and covers the entire area of interest.
I'd like to perform a simple raster calculation (say gdal_calc.py -A redgrid.tif -B greengrid.tif -C bluegrid.tif --calc="(A+B+C)/3"), and generate an output raster in which I will get resultant values across the extent of the largest raster available, or the blue domain. Currently, this calculation will only yield an output raster with the smallest extent, or the red domain.
I've considered filling the other two grids with np.nan to match the extent of the blue domain, though I believe that this division would return nan in areas where the three grids do not overlap.

A: Zeroing will disturb the mean.
Maybe a more complex solution, case-by-case is called for. If nodata is -9999
Cases
There are 7 cases:

*

*1 case where all 3 exist

*3 cases where 1 doesn't but 2 do exist

*3 cases where 1 does but 2 don't exist

Test if all 3 exist. * acts like a logical AND if arguments are 1 or 0:
(A>-9999) * (B>-9999) * (C>-9999)

produces 1 or 0 for each pixel. Multiply that by (A+B+C):
(A>-9999) * (B>-9999) * (C>-9999) * (A+B+C)

to get the answer where all 3 pixels are defined. If only 2 pixels are defined, the third must be OFF.
(A>-9999) * (B>-9999) * (C=9999) * (A+B)

There are 2 more cases like this. When only one dataset is valid at a point, the same applies
(A>-9999) * (B=-9999) * (C=-9999) * A

There are 2 more cases like this.
Combining Cases
Just as * represents AND, use + to represent OR. There seem to be 7 cases (add as required). Final equation is thus
(A>-9999) * (B>-9999) * (C>-9999) * (A+B+C) +
(A>-9999) * (B>-9999) * (C=9999) * (A+B) +
(A>-9999) * (B=-9999) * (C>9999) * (A+C) +
(A=-9999) * (B>-9999) * (C>9999) * (B+C) +
(A>-9999) * (B=-9999) * (C=-9999) * A +
(A=-9999) * (B>-9999) * (C=-9999) * B +
(A=-9999) * (B=-9999) * (C>-9999) * C

Line breaks are just to keep it neater. Maybe use a text editor to write it and then paste it into gdal_calc_py :-)


text:
Q: How to link C++ program with Boost using CMake What should my CMake file look like for linking my program with the Boost library under Ubuntu?
The errors shown during running make:
main.cpp:(.text+0x3b): undefined reference to `boost::program_options::options_description::m_default_line_length'

The main file is really simple:
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/option.hpp>
using namespace std;
#include <iostream>

namespace po = boost::program_options;

int main(int argc, char** argv) {

    po::options_description desc("Allowed options");
    desc.add_options()
        ("help", "produce help message")
        ;

    return 0;
}

I've managed to do that. The only lines that I've added to my CMake files were:
target_link_libraries(
my_target_file
${Boost_PROGRAM_OPTIONS_LIBRARY}
)

A: Two ways, using system default install path, usually /usr/lib/x86_64-linux-gnu/:
find_package(Boost REQUIRED regex date_time system filesystem thread graph)
include_directories(${BOOST_INCLUDE_DIRS})
message("boost lib: ${Boost_LIBRARIES}")
message("boost inc:${Boost_INCLUDE_DIR}")

add_executable(use_boost use_boost.cpp)
target_link_libraries(use_boost
        ${Boost_LIBRARIES}
        )

If you install Boost in a local directory or choose local install instead of system install, you can do it by this:
set( BOOST_ROOT "/home/xy/boost_install/lib/" CACHE PATH "Boost library path" )
set( Boost_NO_SYSTEM_PATHS on CACHE BOOL "Do not search system for Boost" )

find_package(Boost REQUIRED regex date_time system filesystem thread graph)
include_directories(${BOOST_INCLUDE_DIRS})
message("boost lib: ${Boost_LIBRARIES}, inc:${Boost_INCLUDE_DIR}")

add_executable(use_boost use_boost.cpp)
target_link_libraries(use_boost
        ${Boost_LIBRARIES}
        )

Note the above dir /home/xy/boost_install/lib/ is where I install Boost:
xy@xy:~/boost_install/lib$ ll -th
total 16K
drwxrwxr-x 2 xy xy 4.0K May 28 19:23 lib/
drwxrwxr-x 3 xy xy 4.0K May 28 19:22 include/

xy@xy:~/boost_install/lib$ ll -th lib/
total 57M
drwxrwxr-x 2 xy xy 4.0K May 28 19:23 ./
-rw-rw-r-- 1 xy xy 2.3M May 28 19:23 libboost_test_exec_monitor.a
-rw-rw-r-- 1 xy xy 2.2M May 28 19:23 libboost_unit_test_framework.a
.......

xy@xy:~/boost_install/lib$ ll -th include/
total 20K
drwxrwxr-x 110 xy xy  12K May 28 19:22 boost/

If you are interested in how to use a local installed Boost, you can see this question How can I get CMake to find my alternative Boost installation?.

A: Adapting @MOnsDaR answer for modern CMake syntax with imported targets, this would be:
find_package(Boost 1.40 COMPONENTS program_options REQUIRED)

add_executable(anyExecutable myMain.cpp)

target_link_libraries(anyExecutable Boost::program_options)

Note that it is not necessary to specify the include directories manually, since it is already taken care of through the imported target Boost::program_options.

A: The following is my configuration:
cmake_minimum_required(VERSION 2.8)
set(Boost_INCLUDE_DIR /usr/local/src/boost_1_46_1)
set(Boost_LIBRARY_DIR /usr/local/src/boost_1_46_1/stage/lib)
find_package(Boost COMPONENTS system filesystem REQUIRED)
include_directories(${Boost_INCLUDE_DIR})
link_directories(${Boost_LIBRARY_DIR})

add_executable(main main.cpp)
target_link_libraries( main ${Boost_LIBRARIES} )

A: Here is my take:
cmake_minimum_required(VERSION 3.15)

project(TryOuts LANGUAGES CXX)

find_package(Boost QUIET REQUIRED COMPONENTS program_options)

if(NOT Boost_FOUND)
    message(FATAL_ERROR "Boost Not found")
endif()

add_executable(helloworld main.cpp)

target_link_libraries(helloworld PUBLIC Boost::program_options)

A: In CMake you could use find_package to find libraries you need. There usually is a FindBoost.cmake along with your CMake installation.
As far as I remember, it will be installed to /usr/share/cmake/Modules/ along with other find-scripts for common libraries. You could just check the documentation in that file for more information about how it works.
An example out of my head:
FIND_PACKAGE( Boost 1.40 COMPONENTS program_options REQUIRED )
INCLUDE_DIRECTORIES( ${Boost_INCLUDE_DIR} )

ADD_EXECUTABLE( anyExecutable myMain.cpp )

TARGET_LINK_LIBRARIES( anyExecutable LINK_PUBLIC ${Boost_LIBRARIES} )

I hope this code helps.

*

*Here's the official documentation about FindBoost.cmake.

*And the actual FindBoost.cmake (hosted on GitHub)

A: Which Boost library? Many of them are pure templates and do not require linking.
Now with that actually shown concrete example which tells us that you want Boost program options (and even more told us that you are on Ubuntu), you need to do two things:

*

*Install libboost-program-options-dev so that you can link against it.

*Tell cmake to link against libboost_program_options.

I mostly use Makefiles so here is the direct command-line use:
$ g++ boost_program_options_ex1.cpp -o bpo_ex1 -lboost_program_options
$ ./bpo_ex1
$ ./bpo_ex1 -h
$ ./bpo_ex1 --help
$ ./bpo_ex1 -help
$

It doesn't do a lot it seems.
For CMake, you need to add boost_program_options to the list of libraries, and IIRC this is done via SET(liblist boost_program_options) in your CMakeLists.txt.


text:
Q: Javascript "..." waiting dot looping with interval Instead of using an animated gif, I would like to instead have text in a span:

*

*Waiting

*Waiting.

*Waiting..

*Waiting...

I would like to loop through each and then return to the first in an infinite loop.  I would also like to control the interval to speed up or slow it down.  I'd like to have my HTML to be:

Waiting

And simply cycle the span innerHTML.  Thanks!

A: This would probably set you in the right direction. I think the code should explain itself.
function iterateDots(){
    var el = document.getElementById("dots");
    var dotsStr = el.innerHTML;
    var dotsLen = dotsStr.length;

    var maxDots = 3;
    el.innerHTML = (dotsLen < maxDots ? dotsStr + '.' : '');
}

function startLoading(){
    var intervalMs = 300;

    var interval = setInterval("iterateDots()", intervalMs);
}

A: dots = document.getElementById('dots'); will get the DOM element you want to put dots in, and the innerHTML attribute of that element will let you manipulate the content inside it.
As for changing the content of the span on a specific interval, have a look at setInterval() and setTimeout(). You'll have to pick the one that best suits your needs.
I'm not going to post an actual solution since you haven't really showed any effort on this one, but this should point you in the right direction.


text:
Q: Confused with this Salesforce recruiting app question I don't want the answer to this question but I just want someone to guide me the right way.
Following is the question...

My question is..
Where is the clue in the question for me to understand that I, as developer, have to choose look-up relationship for this situation? As far as my knowledge is concerned, in look-up relationships, if we delete the parent, there is no effect on child.
[PS: I was asked by an admin not to post certification question. I respect that. I suppose this is the right way to ask.]

A: read once again information about master-detail relationship.
try here
http://www.salesforce.com/us/developer/docs/api/Content/relationships_among_objects.htm
here is some tip:
check sharing and security :)

A: First thing you can identify is the OWD setting for the objects, using the most restricted user in the requirement. Then try to eliminate the options which does not fit OWD setting.
I hope this helps.

A: Lookups relationships can be set to cascade delete.
For a ton of information about the different types of relationships in Salesforce, read this help article: http://help.salesforce.com/HTViewHelpDoc?id=relationships_considerations.htm&language=en_US


text:
Q: Is there a C function to clear command line input after a program execution? (Windows especially) I am writing a basic program in C using Windows API to read from standard input and display it flawlessly on the standard out. The whole program works great but as soon as I quit the program, there are some trailing characters left behind on a terminal input. Maybe I am a little bit too picky about it but for me, it is too frustrating.
The code is the following:
#include <stdio.h>
#include <Windows.h>
#include <stdlib.h>

/*********************************************************/

/* ClearScreen function definition .... */

struct Keys {
    unsigned int k1: 1;
    unsigned int k2: 1;
    unsigned int k3: 1;
    unsigned int k4: 1;
};

void check_key(struct Keys* keys)
{
    keys->k1 = 0; keys->k2 = 0; keys->k3 = 0; keys->k4 = 0;
    if (GetKeyState('A') & 0x8000)
    {
        keys->k1 = 1;
    }
    if (GetKeyState('S') & 0x8000)
    {
        keys->k2 = 1;
    }
    if (GetKeyState('D') & 0x8000)
    {
        keys->k3 = 1;
    }
    if (GetKeyState('F') & 0x8000)
    {
        keys->k4 = 1;
    }
}

void print_keys(struct Keys keys)
{
    ClearScreen();
    printf("K1 = %d | K2 = %d | K3 = %d | K4 = %d",
            keys.k1, keys.k2, keys.k3, keys.k4);
    printf("\n");
    printf("P1 = 1");
}

int main ()
{
    hStdOut = GetStdHandle( STD_OUTPUT_HANDLE );
    if (hStdOut == INVALID_HANDLE_VALUE) return -1;

    struct Keys keys = {0, 0, 0, 0};

    while (1)
    {
        check_key(&keys);
        print_keys(keys);
        Sleep(100);
    }

    CloseHandle(hStdOut);

    return 0;
}

Example:
Let's say I am running this program and input the following keystrokes sequence "zczxcvcvbxxvbc". After the execution of the program I am left with this on my terminal:

What I want to achieve is to have clear terminal input after usage, without those characters in place.
Is there any way to achieve this?

A: The program hasn't requested any input. So the buffered input you typed appeared afterwards, in the shell. A windows program could do
while (1)
{
    check_key(&keys);
    print_keys(keys);
    while(kbhit())
       getch();
    Sleep(100);
}

in the loop to adsorb those key presses.
You might want to use _kbhit and _getch to avoid compiler warnings.


text:
Q: How to return all rows in a group where a specific value appears at least once How can I return all rows in group of records where a specific value appears?
For instance here is the example table:
id code
1  E100
1  E200
1  E300
2  E100
2  E300
3  E300
3  E400

In this table I want to get all id's and code's, where the code E100 appears. So if it appears against id=1, I want to return all rows where id=1.
Desired output based on above data:
id code
1  E100
1  E200
1  E300
2  E100
2  E300

id=3 is not included as it doesn't hold a value E100 in the code column.

A: Use Exists Operator
select *
from yourtable a
where exists
(
select 1
from yourtable b
where a.id=b.id
and b.code ='E100'
)

A: SELECT * FROM Table WHERE id IN (
   SELECT id FROM Table WHERE code = 'E100'
)


text:
Q: Parameter '...' implicitly has an 'any' type I am using VS Code for my project, where I encountered this error. I checked other solutions like setting "noImplicitAny: false" but the problem - "Parameter 'res' implicitly has an 'any' type" & "Parameter 'id' implicitly has an 'any' type" persists. The TypeScript code is given below.

  getContacts()
  {
    return this.http.get('http://localhost:3000/api/contacts')
    .map(res => res.json());
  }

  //add contact method
  addContact (newContact)
  {
    var headers = new Headers();
    headers.append('content-Type', 'application/json');
    return this.http.post('http://localhost:3000/api/contact', newContact, {headers:headers})
      .map(res => res.json());
  }

  //delete method
  deleteContact(id)
  {
    return this.http.delete('http://localhost:3000/api/contact/'+id)
      .map(res => res.json());
  }

A: Maybe try changing res => to (res: any) =>


text:
Q: Dimension of Kernel of Composition of Linear Transformations Take two linear transformations $T \colon U \to V$ and $S \colon V \to W$ where $U$, $V$ and $W$ are finite.
I want to show that
$$
       \dim \ker (S \circ T)
  \leq \dim \ker S + \dim \ker T.
$$

Attempt: I've been using the dimensional theorem because of the finity from each vector space. So I got that
\begin{align*}
   &\, \dim \ker T + \dim \ker S
   \\
  =&\, \dim \ker (S \circ T)
       + \dim V
       + \dim \operatorname{im} (S \circ T)
       - \dim \operatorname{im} T
       - \dim \operatorname{im} S.
\end{align*}
I have been using the inequalities

*

*$\dim \operatorname{im} S > \dim \operatorname{im} (S \circ T)$,

*$\dim V > \dim \mathrm{im} T$,

and that $\ker T \subseteq \ker (S \circ T)$.

But with such inequalities I couldn't conclude anything.
Any tips or hint in order to progress or get the answer?

A: We do it like this:
Lemma $1$: $T[\ker (S \circ T)] = \ker S \cap {\rm Im}\,T$.
Proof: you do it, okay?

Lemma $2$: If $F\colon V_1 \to V_2$ is linear and $Z \subseteq V_2$ is a subspace, then $F^{-1}[Z]$ is a subspace of $V_1$ and $\dim F^{-1}[Z] \leq \dim \ker F + \dim Z$.
Proof: I'll check only the formula. Applying the rank-nullity theorem for the restriction of $F$ to $F^{-1}[Z]$, we get $$\dim F^{-1}[Z]= \dim \ker F\big|_{F^{-1}[Z]}+\dim {\rm Im}\,F\big|_{F^{-1}[Z]} \leq \dim \ker F + \dim Z.$$

Now to prove what you want we need only note that
$$\begin{align} \dim \ker(S \circ T) &\stackrel{(1)}{\leq} \dim T^{-1}[T[\ker S \circ T]]  \\ &\stackrel{(2)}{=} \dim T[\ker(S \circ T)] + \dim \ker T \\ &\stackrel{(3)}{=} \dim (\ker S \cap {\rm Im}\,T)+\dim \ker T \\ &\stackrel{(4)}{\leq} \dim \ker S + \dim \ker T,\end{align}$$where in (2) we apply lemma $2$, in (3) we apply lemma $1$, and (1) and (4) follow because of elementary set-theoretic considerations.


text:
Q: Accessing begin and end in RcppParallel (exmaple calculating the mean of a vector) I'm having a problem while trying to learn RcppParallel.
I tried to modify the code form https://rcppcore.github.io/RcppParallel/ for the vector summation to calculate the mean of a vector instead, to see if I understand the general principle.
My code is shown below. Using the function parallelVectorMean() on c(1,2,3,4,5) delivers inconsistent and most often incorrect results. I assume this has to do with me not understanding how to access begin and end correctly to scale my partial means accordingly during the join.
// [[Rcpp::depends(RcppParallel)]]
#include <RcppParallel.h>
#include <Rcpp.h>
using namespace RcppParallel;

struct Mean : public Worker
{
   // source vector
   const RVector<double> input;

   // accumulated value
   double value;

   // number of elements
   double num;

   // constructors
   Mean(const Rcpp::NumericVector input) : input(input), value(0), num(0) {}
   Mean(const Mean& mean, Split) : input(mean.input), value(0), num(0) {}

   // accumulate just the element of the range I've been asked to
   void operator()(std::size_t begin, std::size_t end) {
      num = (double) end - (double) begin;
      value += (std::accumulate(input.begin() + begin, input.begin() + end, 0.0) / num);
   }

   // join my value with that of another Mean
   void join(const Mean& rhs) {
      value = (num*value + rhs.num*rhs.value)/(num + rhs.num);
      num = num + rhs.num;
   }
};

// [[Rcpp::export]]
double parallelVectorMean(Rcpp::NumericVector x) {

   // declare the MeanBody instance
   Mean mean(x);

   // call parallel_reduce to start the work
   RcppParallel::parallelReduce(0, x.length(), mean);

   // return the computed mean
   return mean.value;
}

I'm looking forward to learning from you guys.

A: Accessing begin and end is fine, but your operator function's logic isn't correct.
Check this:
   void operator()(std::size_t begin, std::size_t end) {
      double temp_num = (double) end - (double) begin;
      double temp_value = (std::accumulate(input.begin() + begin, input.begin() + end, 0.0) / temp_num);
      value = (num*value + temp_num*temp_value)/(num + temp_num);
      num = num + temp_num;
   }

A thread may continue running on a new range without joining, so you have to account for that possibility.


text:
Q: how to change float array into integers array in json file     human_pose ='''{
    "annotations": [
        {
            "area": "356725",
            "image_id": "1",
            "iscrowd": "0",
            "category_id": "1",
            "keypoints": [
                371.5701271305881,
                188.86769422623237,
                2,
                380.9752835872622,
                174.5554996182501,
                2,
                353.4413472938106,
                177.5542451551607,
                2,
                397.6046906555844,
                184.91480238212299,
                2,
                328.49723669132726,
                196.90978452976526,
                2,
                478,
                258,
                2,
                302,
                285,
                2,
                577,
                287,
                1,
                343,
                390,
                2,
                661,
                282,
                2,
                431,
                363,
                2,
                430,
                486,
                1,
                352,
                477,
                2,
                416,
                662,
                2,
                335,
                643,
                2,
                329,
                785,
                2,
                307,
                810,
                2
            ]

        }]}'''

import json
import math

data = json.loads(human_pose)

for person in data['annotations']:
    key = person["keypoints"]
    [math.trunc(key) for key in key]

    #del person['area']

new_string = json.dumps(data)
print(new_string)

output:

{"annotations": [{"image_id": "1", "iscrowd": "0", "category_id": "1", "keypoints": [371.5701271305881, 188.86769422623237, 2, 380.9752835872622, 174.5554996182501, 2, 353.4413472938106, 177.5542451551607, 2, 397.6046906555844, 184.91480238212299, 2, 328.49723669132726, 196.90978452976526, 2, 478, 258, 2, 302, 285, 2, 577, 287, 1, 343, 390, 2, 661, 282, 2, 431, 363, 2, 430, 486, 1, 352, 477, 2, 416, 662, 2, 335, 643, 2, 329, 785, 2, 307, 810, 2]}]}

I am trying to convert the keypoint float values into integers the json.dumps save the changes like i perform (del person['area']) but do not save the changes i applied on keypoint. in CLI of python it displays the keypoints as integer array but when i dumps it to new json file the changes are not don and save as the same original. Help appreciate

A: You have to reassign the keypoints in the given json after converting the data.
check below code:
for person in data['annotations']:
    key = person["keypoints"]
    person["keypoints"] = [math.trunc(k) for k in key]


text:
Q: If $\mu$ is a (sub-)probability measure on $\mathbb{R}$, then $\mu(\left\{x\right\})=0$ for all continuity points $x$ of the DF of $\mu$ Let $\mu$ be a (sub-)probability measure on $\left(\mathbb{R},\mathcal{B}(\mathbb{R})\right)$ and $F$ be the distribution function of $\mu$. How can we deduce $$\mu\left(\left\{x\right\}\right)=0\;\;\;\text{for all continuity points }x\in\mathbb{R}\text{ of }F\tag{1}$$ from the definition of $\mu$?

I've tried the following:

*

*Let $(\Omega,\mathcal{A},\nu)$ be a $\sigma$-finite measure space and $\mathcal{F}\subseteq\mathcal{A}$ be a family of pairwise disjoint
sets with positive $\nu$-measure

*We can show, that $\mathcal{F}$ is at most countable

Thus, since $$\mathcal{F}=\left\{\left\{x\right\}:x\in\mathbb{R}\right\}$$ is isomorphic to $\mathbb{R}$, it's impossible that $$\mu\left(\left\{x\right\}\right)>0\;\;\;\text{for all }x\in\mathbb{R}$$ How can we conclude that $(1)$ must be true?

A: By definition, $$F(x) := \mu(-\infty,x].$$
1. Let $(x_j)_{j \in \mathbb{N}}$ be an arbitrary sequence such that $x_j \uparrow x$. Conclude from the continuity of the measure that $$F(x-) = \lim_{j \to \infty} F(x_j) = \mu((-\infty,x)).$$
2. Let $(x_j)_{j \in \mathbb{N}}$ such that $x_j \downarrow x$. Show that $$F(x) = \lim_{j \to \infty} F(x_j) = \mu((-\infty,x]).$$
3. Conclude that for any continuity point $x$ of $F$, we have $$\mu(\{x\})=0.$$


text:
Q: SQL Server SMO on IIS with Windows Auth I'm getting a strange error when I enable windows authentication on IIS and try to run some database update scripts:

Invalid token for impersonation - it
  cannot be duplicated.

I have not enabled any explicit impersonation.
I have narrowed it down to being something to do with SMO as when I change to a normal SqlClient and use ExecuteNonQuery, the problem goes away. This unfortunately is not a long term solution as the update scripts must be able to contain the 'GO' keyword which is not recognized by the standard SqlClient.

A: IIS worker processes are running as some user. When you use windows authentication, you are implicitly doing impersonation to the that user.
If your SQL server is on a different host, this probably isn't good enough. The impersonated user I think can only access local resources.
http://msdn.microsoft.com/en-us/library/ff647405.aspx#paght000025_usingimpersonation
Is SQL Server using windows authentication?


text:
Q: $\sqrt{n}P(A_n)\to c\implies P(A_n)\leq c/\sqrt{n}$? As the title already says, I am wondering if the following implication is correct.
$\sqrt{n}P(A_n)\to c\implies P(A_n)\leq c/\sqrt{n}$?
Don't know where to start. Thank you for help.

A: No. But for any $c'>c$ $$ P(A_n)\le \frac{c'}{\sqrt n}$$
for almost all $n$.


text:
Q: Are unnecessary semicolons syntax errors? This morning, after doing a git refresh, IntelliJ complained that my project wasn't compiling clean any more. The culprit:
import javax.naming.Context;;

IntelliJ complains:

Error:(33, 29) java: Syntax error on token ";", delete this token

That code was pushed by a person who is not using IntelliJ, and it passed our backend build.
Question: is javac at fault, or IntelliJ? And what would be the document/spec that clarifies whether the above code should be an error or a warning?
This is IntelliJ 2019.2 CE EAP, running on MacOs.
And just to be precise: there seems to be a mismatch between the IntelliJ "editor compile", and the result of hitting the "build" action. Fun fact: we have "use eclipse compiler" in our project setup. Changing it that to use javac fixes the problem, the double ;; is just a warning then.

A: Unnecessary semicolons are not an error. They are considered as empty statements. And an empty statement, which does nothing, is not an error.
Cross check your code. It might also be IntelliJ at fault too. Its linting service might not be considering it as a legal statement.
The question is similar to this
Edit 1: The IntelliJ has an option in it's settings to which posts redundant semicolons as error.

A: Disclaimer
This does not resolve the issue, as it turns out the error occurs in relation to usage of the Eclipse compiler (as opposed to the default javac compiler).
This might still be useful to troubleshoot / highlight the inspection customization feature of IntelliJ.

You can set the level of severity for unnecessary semicolons (among many other things) in IntelliJ, in the Inspections profile.
The default setting for redundant semi-colons is "warning".
Probably yours has been set to "Error".

This should not impact on the Java compiler, as redundant semi-colons are not a syntactic error.

A: According to the Java Language Specification §7.6 ; is a valid Type Declaration:

A top level type declaration declares a top level class type (§8 (Classes)) or a top level interface type (§9 (Interfaces)).

TypeDeclaration:

*

*ClassDeclaration

*InterfaceDeclaration

*;

Extra ";" tokens appearing at the level of type declarations in a compilation unit have no effect on the meaning of the compilation unit. Stray semicolons are permitted in the Java programming language solely as a concession to C++ programmers who are used to placing ";" after a class declaration. They should not be used in new Java code.

If there is no setting in InteliJ that would change this behavior, then the extra semicolon should not produce an error.


text:
Q: git show logs exclude some user or committer I don't know how to do this
I try these already:

git log -p --author="user" --not Sites/Web/Templates

git log -p --author="!user" Sites/Web/Templates

still show log of that user. Help, please.


text:
Q: VBA Runtime Error 1004 the extract range has a missing or invalid field name Please, I am getting an error in this part of my macro. It shows me this error:
1004 the extract range has a missing or invalid field name

In this line:
Range("'CF Backlog.xls'!DATA").AdvancedFilter Action:=xlFilterCopy, _
    CriteriaRange:=Range("A1:B2"), CopyToRange:=Range("C1:BJ1"), Unique:= _
    False

Code:
Sheets("Template").Activate
Range("A1:B2").Select
ActiveWorkbook.Names.Add Name:="Criteria", RefersToR1C1:= _
    "=Template!R1C1:R2C2"
ActiveWorkbook.Names.Add Name:="Criteria", RefersToR1C1:= _
    "=Template!R1C1:R2C2"
     'Range("C1:BJ1").ClearContents
Range("'CF Backlog.xls'!DATA").AdvancedFilter Action:=xlFilterCopy, _
    CriteriaRange:=Range("A1:B2"), CopyToRange:=Range("C1:BJ1"), Unique:= _
    False

I have spent many hours checking forums. But, I still can't fix the problem. Any suggestions?

A: Maybe try clearing the destination range
Sheets("Template").Activate
Range("A1:B2").Select
ActiveWorkbook.Names.Add Name:="Criteria", RefersToR1C1:= "=Template!R1C1:R2C2"
'ActiveWorkbook.Names.Add Name:="Criteria", RefersToR1C1:= "=Template!R1C1:R2C2" ' why do you add the same named range two times ??!!
Range("C1:BJ1").ClearContents  ' <-- uncomment this line
Range("'CF Backlog.xls'!DATA").Select  ' and check if this gives any error
Range("'CF Backlog.xls'!DATA").AdvancedFilter Action:=xlFilterCopy, _
    CriteriaRange:=Range("A1:B2"), CopyToRange:=Range("C1:BJ1"), Unique:= _
    False


text:
Q: Saving data in div after page refresh I am creating a search bar where the user can select parameters which creates a chip in the search bar. This chip will be created dynamically for every selection in a div with the class name 'chips'. After submitting the selection, the page redirects based on the selection. As the chips were dynamically created, they will be deleted on page reload. My question: Is there a way to store this dynamic data without deleting it after the page refresh?
  <div class="chips" id="createdChips" >
         <span> class ='someclass' </span>
         <span> class ='someclass' </span>
  </div>

A: You can store your dynamically created data in cookies or session storage. When your page load, search if there's data stored in above storage and draw the chips based on data.

A: delete on browser close:
// Store item
sessionStorage.setItem('example', 'some item');

// Get Item
sessionStorage.getItem('example') // 'some item'

// Remove Item
sessionStorage.remove('example');

// Remove all items
sessionStorage.clear();

never be deleted unless the user clears website data (through browser settings):
// Store item
localStorage.setItem('example', 'some item');

// Get Item
localStorage.getItem('example') // 'some item'

// Remove Item
localStorage.remove('example');


text:
Q: java using method error : they said "can not resolve symbol x"
public class MethodExemple {

    public static void main(String[] args) {

        MethodExemple methodExemple = new MethodExemple();
        methodExemple.StrCombine( x: "hello", y:"hongdroid");

        System.out.println(methodExemple.StrHongdroid( hong:"hollo"));

    }

    public void StrCombine (String x, String y) {
        String result = x + y;
        System.out.println(result);
    }

    public String StrHongdroid (String hong, String droid){
        String result = hong +droid;
        return result;

    }
}

I coded as I learned in class. However, an error occurred only in my code. The contents of the error are as follows.

cannot resolve symbol 'x' and 'y'

A: When calling a method in Java, you shouldn't specify the argument names, just provide them in order:
methodExemple.StrCombine("hello", "hongdroid");

A: You don't need to include x and y when calling the method StrCombine(). Here is the correct way methodExemple.StrCombine( "hello", "hongdroid"); either passing string literals like this or string variables


text:
Q: Ria Service Generated Code Not Accessible in Silverlight Code I have the following Ria Service define:
namespace SilverlightTest.Web
{
    [EnableClientAccess()]
    public class ContactService : LinqToEntitiesDomainService<AdventureWorksEntities>
    {
        public IQueryable<Contact> GetContactSearch(string lastName)
        {
            ContactRepository rep = new ContactRepository();
            return rep.SearchByLastName(lastName);
        }
    }
}

When I compile the solution, my SilverlightTest project does create the SilverlightTest.Web.g.cs file and the appropriate Context objects are created when I look at it.  However, when I attempt to import the SilverlightTest.Web namespace to access the Data Context class for the above service, it says it cannot find the Web namespace.
The only difference I can see between what I'm doing and many examples that are out there on the web is that my AdventureWorksEntities data context is located in a separate business object dll.  I tried to query the context directly instead of using the Repository Pattern I'm attempting to do and it also isn't work working.
Any ideas?  Is it possible to have Ria Services access a separate DLL handling data access or does it HAVE to be in the same project?

A: I've been able to put the Ria service in a separate project before, although I do remember having issues.  Not sure exactly what it was, but I would check two things: your references and your web.config (in the hosting website).  When you add a ria service to a web project it does some things behind the scenes that wire everything up correctly.
Could try adding a service to your web project temporarily and see what it adds.

A: It seems that Resharper does not recognize the .gs files and their name spaces. If you disable R# or just code without intelisense it works.


text:
Q: Pass request to model form using generic view in Django I using Django and a generic view "django.views.generic.create_update.create_object"
I have a model form wich i pass to the generic view:
url(r'^add$', create_object, {'template_name':'tpl.html','form_class':MyModelForm,'post_save_redirect':'/'},name = 'add'),

I need to get current user in my ModelForm.save method..
But i can't find way to get it, please help me to find convinient way?

class MyModelForm(forms.ModelForm):
class Meta:
    model = MyModel

def save(self,*a,**b):
    MyModel.save(user=request.user) #how can i get here request.user?

In common way the question is - how can i accsess request params in forms passed to generic view.

A: You could probably hack something up to inject the request into the form instantiation, but why would you bother? Generic views are meant as a quick-and-easy solution to the basic requirements only. As soon as you start needing massive customisations, you might as well just write the actual view yourself. It's not very much code, after all.

A: Look at that:
url(r'^add$', create_object_with_request, {'template_name':'tpl.html','form_class':MyModelForm,'post_save_redirect':'/'},name = 'add'),

,
def create_object_with_request(request, *args, **kwargs):
    def inject_request(fun):
        def helper(*args, **kwargs):
            return fun(*args, request=request, **kwargs)
        return helper
    kwargs['form_class'] = inject_request(kwargs['form_class'])
    return create_object(request, *args, **kwargs)

So you have passed request to your class constructor. Or you can add it as attribute:
def create_object_with_request(request, *args, **kwargs):
    def inject_request(fun):
        def helper(*args, **kwargs):
            res = fun(*args, **kwargs)
            res.request = request
            return res
        return helper
    kwargs['form_class'] = inject_request(kwargs['form_class'])
    return create_object(request, *args, **kwargs)

A: thnx this helps) I have some problems this syntax and _meta attr and i finished with this

def create_object_with_request(request, *args, **kwargs):
def inject_request(fun):

    def helper(*args, **kwargs):
        finst = fun(*args, **kwargs)
        finst.request = request
        return finst

    helper._meta = fun._meta
    return helper
kwargs['form_class'] = inject_request(kwargs['form_class'])
return create_object(request,*args, **kwargs)


text:
Q: Java, xml, XSLT: Prevent DTD-Validation I use the Java (6) XML-Api to apply a xslt transformation on a html-document from the web. This document is wellformed xhtml and so contains a valid DTD-Spec (<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">).
Now a problem occurs: Uppon transformation the XSLT-Processor tries to download the DTD and the w3-server denies this by a HTTP 503 error (due to Bandwith Limitation by w3).
How can I prevent the XSLT-Processor from downloading the dtd? I dont need my input-document validated.
Source is:
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

--
   String xslt = "<?xml version=\"1.0\"?>"+
   "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">"+
   "    <xsl:output method=\"text\" />"+
   "    <xsl:template match=\"//html/body//div[@id='bodyContent']/p[1]\"> "+
   "        <xsl:value-of select=\".\" />"+
   "     </xsl:template>"+
   "     <xsl:template match=\"text()\" />"+
   "</xsl:stylesheet>";

   try {
   Source xmlSource = new StreamSource("http://de.wikipedia.org/wiki/Right_Livelihood_Award");
   Source xsltSource = new StreamSource(new StringReader(xslt));
   TransformerFactory ft = TransformerFactory.newInstance();

   Transformer trans = ft.newTransformer(xsltSource);

   trans.transform(xmlSource, new StreamResult(System.out));
   }
   catch (Exception e) {
     e.printStackTrace();
   }

I read the following quesitons here on SO, but they all use another XML-Api:

*

*"DTD download error while parsing XHTML document in XOM"
Thanks!

A: I recently had this issue while unmarshalling XML using JAXB.  The answer was to create a SAXSource from an XmlReader and InputSource, then pass that to the JAXB UnMarshaller's unmarshal() method.  To avoid loading the external DTD, I set a custom EntityResolver on the XmlReader.
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xmlr = sp.getXMLReader();
xmlr.setEntityResolver(new EntityResolver() {
    public InputSource resolveEntity(String pid, String sid) throws SAXException {
        if (sid.equals("your remote dtd url here"))
            return new InputSource(new StringReader("actual contents of remote dtd"));
        throw new SAXException("unable to resolve remote entity, sid = " + sid);
    } } );
SAXSource ss = new SAXSource(xmlr, myInputSource);

As written, this custom entity resolver will throw an exception if it's ever asked to resolve an entity OTHER than the one you want it to resolve.  If you just want it to go ahead and load the remote entity, remove the "throws" line.

A: Try setting a feature in your DocumentBuilderFactory:
URL url = new URL(urlString);
InputStream is = url.openStream();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
DocumentBuilder db;
db = dbf.newDocumentBuilder();
Document result = db.parse(is);

Right now I'm experiencing the same problems inside XSLT(2) when calling the document function to analyse external XHTML-pages.

A: The previous answers led me to a solution but is wasn't obvious for me so here is a complete one:
private void convert(InputStream xsltInputStream, InputStream srcInputStream, OutputStream destOutputStream) throws SAXException, ParserConfigurationException,
        TransformerFactoryConfigurationError, TransformerException, IOException {
    //create a parser with a fake entity resolver to disable DTD download and validation
    XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
    xmlReader.setEntityResolver(new EntityResolver() {
        public InputSource resolveEntity(String pid, String sid) throws SAXException {
            return new InputSource(new ByteArrayInputStream(new byte[] {}));
        }
    });
    //create the transformer
    Source xsltSource = new StreamSource(xsltInputStream);
    Transformer transformer = TransformerFactory.newInstance().newTransformer(xsltSource);
    //create the source for the XML document which uses the reader with fake entity resolver
    Source xmlSource = new SAXSource(xmlReader, new InputSource(srcInputStream));
    transformer.transform(xmlSource, new StreamResult(destOutputStream));
}

A: You need to be using javax.xml.parsers.DocumentBuilderFactory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource src = new InputSource("http://de.wikipedia.org/wiki/Right_Livelihood_Award")
Document xmlDocument = builder.parse(src.getByteStream());
DOMSource source = new DOMSource(xmlDocument);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer(xsltSource);
transformer.transform(source, new StreamResult(System.out));

A: if you use
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

you can try disable the dtd validation with the fllowing code:
 dbf.setValidating(false);


text:
Q: .NET FirebirdClient.FbException (0x80004005): Your user name and password are not defined My c# service tries to connect to the remote host and failing all the time, but Flamerobin with same credentials working fine, also I can connect to this server over firebird isql tool.
Version of my Firebird ADO.net provider is 5.8.0
The service works fine with other clients (with other db servers), so I think that problem in Firebird version on the current server or some network problems.
On the server we have windows and Firebird 3.0.3 with Legacy_Auth is On, and users are created as legasy.
SYSDBA                          Legacy_UserManager
CHEA                            Legacy_UserManager
SYSDBA                          Srp

I try different connectionStrings, like
connectionString="User=SYSDBA;Password=masterkey;Database=bd;DataSource=10.0.0.56;Port=3050;Dialect=3;Charset=WIN1251;"

or
connectionString="User=SYSDBA;Password=masterkey;Database=/info/bd.fdb;DataSource=10.0.0.56;Port=3050;Dialect=3;Charset=WIN1251;"

all this way work in flamerobin and not work in .net service. Service return error:

FirebirdSql.Data.FirebirdClient.FbException (0x80004005): Your username and password are not defined. Ask your database administrator to set up a Firebird login. ---> Your username and password are not defined. Ask your database administrator to set up a Firebird login.
     в FirebirdSql.Data.FirebirdClient.FbConnectionInternal.Connect() в C:\Users\Jiri\Documents\devel\NETProvider\working\Provider\src\FirebirdSql.Data.FirebirdClient\FirebirdClient\FbConnectionInternal.cs:строка 172
     в FirebirdSql.Data.FirebirdClient.FbConnectionPoolManager.Pool.CreateNewConnectionIfPossibleImpl(FbConnectionString connectionString) в C:\Users\Jiri\Documents\devel\NETProvider\working\Provider\src\FirebirdSql.Data.FirebirdClient\FirebirdClient\FbConnectionPoolManager.cs:строка 195
     в FirebirdSql.Data.FirebirdClient.FbConnectionPoolManager.Pool.GetConnection(FbConnection owner) в C:\Users\Jiri\Documents\devel\NETProvider\working\Provider\src\FirebirdSql.Data.FirebirdClient\FirebirdClient\FbConnectionPoolManager.cs:строка 99
     в FirebirdSql.Data.FirebirdClient.FbConnection.Open() в C:\Users\Jiri\Documents\devel\NETProvider\working\Provider\src\FirebirdSql.Data.FirebirdClient\FirebirdClient\FbConnection.cs:строка 516

I lost a couple days trying to solve the problem, can you help me?
Can it be some FirebirdClient version collision, or something else?


text:
Q: App crash, How to resolve? I have a problem when I run my app and select an item from my spinner instead of opening a new class like it is supposed to the app crashes, I was wondering if anyone could help me with why this is happening.  I am not sure what part of the code to include, so I will include the Logcat and if you request any code I will edit this post.
Thanks.
Logcat:
03-09 15:36:53.814: E/AndroidRuntime(13429): FATAL EXCEPTION: main
03-09 15:36:53.814: E/AndroidRuntime(13429): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.famouspeople/com.example.famouspeople.SeanConnery}: java.lang.NullPointerException
03-09 15:36:53.814: E/AndroidRuntime(13429):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
03-09 15:36:53.814: E/AndroidRuntime(13429):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
03-09 15:36:53.814: E/AndroidRuntime(13429):    at android.app.ActivityThread.access$600(ActivityThread.java:140)
03-09 15:36:53.814: E/AndroidRuntime(13429):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
03-09 15:36:53.814: E/AndroidRuntime(13429):    at android.os.Handler.dispatchMessage(Handler.java:99)
03-09 15:36:53.814: E/AndroidRuntime(13429):    at android.os.Looper.loop(Looper.java:137)
03-09 15:36:53.814: E/AndroidRuntime(13429):    at android.app.ActivityThread.main(ActivityThread.java:4898)
03-09 15:36:53.814: E/AndroidRuntime(13429):    at java.lang.reflect.Method.invokeNative(Native Method)
03-09 15:36:53.814: E/AndroidRuntime(13429):    at java.lang.reflect.Method.invoke(Method.java:511)
03-09 15:36:53.814: E/AndroidRuntime(13429):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
03-09 15:36:53.814: E/AndroidRuntime(13429):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
03-09 15:36:53.814: E/AndroidRuntime(13429):    at dalvik.system.NativeStart.main(Native Method)
03-09 15:36:53.814: E/AndroidRuntime(13429): Caused by: java.lang.NullPointerException
03-09 15:36:53.814: E/AndroidRuntime(13429):    at com.example.famouspeople.SeanConnery.initialize(SeanConnery.java:44)
03-09 15:36:53.814: E/AndroidRuntime(13429):    at com.example.famouspeople.SeanConnery.onCreate(SeanConnery.java:28)
03-09 15:36:53.814: E/AndroidRuntime(13429):    at android.app.Activity.performCreate(Activity.java:5206)
03-09 15:36:53.814: E/AndroidRuntime(13429):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1083)
03-09 15:36:53.814: E/AndroidRuntime(13429):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
03-09 15:36:53.814: E/AndroidRuntime(13429):    ... 11 more

A: Normally when app crashes with the click on spinner, the problem lies with the adapter you are using to populate the spinner, check carefully the length of apapter you defined. Follow this code
 int num = SpinnerData.length;
    SpinnerData = new String[num];
Log.d("ArrayAdapter",""+ SpinnerData.length);
                    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(CurrentActivity.this, android.R.layout.simple_list_item_1, SpinnerData);
                    //spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    spinner.setAdapter(spinnerArrayAdapter);

check carefully length ..I hope this help


text:
Q: Read TXT file with semicolon separated texts using Python sample data in text file is as follows:
Select * from Table1; Select * from Table2; select * from table3;Select * from table4
I want to read this text and  break into multiple lines at semicolon(;) and process each line separately.
Basically each line represents a select query which I need to query one by one against a database
I tried below code but getting error: AttributeError: 'list' object has no attribute 'split'
ListData = open(FilePath).readlines()
for line in ListData.split(';'):

data.append(line)

Also tried below code but getting error as AttributeError: '_io.TextIOWrapper' object has no attribute 'split'
with open(SQLFilePath) as f:
    for line in f.split(';'):
      data.append(line)

Thanks

A: Try to use for(). For example:
text='Select * from Table1; Select * from Table2; select * from table3;Select * from table4'
for t in text.split(';'):
    print(t)

Answer:
Select * from Table1
 Select * from Table2
 select * from table3
Select * from table4

If read data from file, you can use pandas:
import pandas as pd
df=pd.read_csv(r'C:\Users\Desktop\test.txt', header = None)
t=[]
for index, row in df.itertuples():
    t=t+str(row).split(';')

Console:
print(t)
['Select * from Table1', ' Select * from Table2', ' select * from table3', 'Select * from table4', 'Select * from Table1', ' Select * from Table2', ' select * from table3', 'Select * from table4']


text:
Q: Use settings file in .net core 3.1, single file published windows service How to correctly use JSON settings files in windows services build in 3.1 net core, that are published in a single file.

A: *

*Publishing as single file, requires you to do two things. First, exclude the settings JSON file from the single file. If you do not do it, it will be unpacked together with the rest, loaded and it will appear to work, if there are default values in it. And second, copy the settings file to the publish directory. You can do this by adding this:

    <ItemGroup>
            <Content Update="appsettings.json">
                <CopyToPublishDirectory>Always</CopyToPublishDirectory>
                <ExcludeFromSingleFile>true</ExcludeFromSingleFile>
            </Content>
    </ItemGroup>

In your pubxml profile. Building it from the interface with: Build > Publish (Project name) will not work. You gotta use the command line from now on.

*Once packed into a single file, the base path of your application is changed. Simply placing the JSON files next to your exe will not do the trick. Also, you will be using windows services. Starting the exe is one thing, starting the service is another universe. In most situations you can use the following:

    Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);

To get the directory of your single-file packed exe service.

*The packed exe checks the temp folder it creates for resources, you need to redirect some of the features to another folder. You will want to do this, at least for your log files and settings. For example, if you want the application to check for JSON files near your exe, you add this:

.ConfigureAppConfiguration((context, config) =>
                {
                    config.SetBasePath(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName));
                })

in your CreateHostBuilder method.
I hope that this will save you some time. Ive been fighting this all morning.


text:
Q: Native JS HOF for property access Consider the following snippet of Javascript:
const getter = (key) => (obj) => obj[key]
const stuff = [{ name: 'Harry', age: 28 }, { name: 'Alice', age: 29 }]
const names = stuff.map(getter('name')) // 'Harry', 'Alice'

Is there a native JS function that does the equivalent of the getter function here?

A: You could get Reflect.get,
Reflect.get(target, propertyKey)
Reflect.get(target, propertyKey, receiver)

but this does not work as a callback for array methods, because of the wrong paramter order.


text:
Q: VB.NET error using linq I am using the following example from Stackoverflow:
How to find the oldest Folder in a Folder vb.net
Dim dirPrograms As New DirectoryInfo("c:\program files")

' LINQ query for oldest directory
Dim dir = (From dir In dirPrograms.EnumerateDirectories()).Min(function (o) o.CreationTime).FirstOrDefault()

I get the following error:
Range variable 'dir' hides a variable in an enclosing block or a range variable previously defined in the query expression.
No one else is complaining about an error so I assume I must be doing something wrong.

A: Do this:-
Dim directoryInfo = (From dir In dirPrograms.EnumerateDirectories())
                        .Min(function (o) o.CreationTime)

Your dir declared variable (where you are storing the result) is same as your range variable dir in query-From dir In dirPrograms.. so compiler is complaining as these names will be obviously confusing between the two, So you need to change either of the two names.
Apart from this, You should not use FirstOrDefault after a Min as Min method will return a single value and not IEnumerable.


text:
Q: Better alternative to polling when waiting for a HTTP request in django? I have a django application that needs to communicate with a backend service. Usually I would do it like this:
def my_view(request, id):
    backend_response = requests.get('http://backend.com/{}/'.format(id))
    return HttpResponse(status=backend_response.status_code)

Unfortunately the backend service in this case does not work like that. Instead of including the results in the HTTP response it will send them in a separate HTTP request.
My current approach is to write the results to the database and wait for them in the original request handler:
def my_view(request, id):
    requests.get('http://backend.com/{}/'.format(id))
    while True:
        sleep(1)
        try:
            backend_response = BackendResponse.objects.get(id=id)
            break
        except BackendResponse.DoesNotExist:
            pass
    return HttpResponse(status=backend_response.status_code)

This feels very weird to me. Are there better solutions for this problem?