text:
Q: How to create server-side application logic on Racer / DerbyJS? I'm learning the ins and outs of the new DerbyJS stack, and I can't find a way to put application logic server-side. The stated intent is that all code should be able to run both in the server, and in the client. However, I need certain data to be kept hidden, and only sent to the client if authenticated based on user session info. How can I accomplish this using a Racer store?

A: You can place server-side application logic in the app/server directory. On the server, Derby apps expose an Express middleware, so you can chain other middleware before this. For example, you could have an authentication middleware that prevents certain routes from being rendered if the user is not logged in.
However, this is not a sufficient solution to authentication, because data updates come in as messages over Socket.IO, and they won't go through the Express middleware that initial page requests go through.
We are going to add a simple solution that makes it possible to authenticate users and then authorize them based on the path whenever they subscribe to or modify data, but this is not implemented yet. This is high on the list of things that need to be done, and Derby is still under rapid development.


text:
Q: Check For Voltage With A Raspberry Pi 2b GPIO Pin I want to build a simple (game)controller for my raspberry pi 2b. My plan is to connect the 3.3 voltage output to a button and than to whatever GPIO pin.
Is it possible to check for voltage with the GPIO pin? Or are there more smoother ways to build one (Analog to Digital)?
Please respect that I am developing in Visual Studio 2015 C# and my RP-OS is Windows 10.

A: You can read the status of the pin (High/Low) or you can use interrupts to receive events when the status changes.
The button and LED project is the very first examples either on the Raspberry Pi site or Windows IoT site. The PushButton sample for C# uses interrupts to detect status changes.
The OS or language doesn't matter so much as the fact that you are using an RPi. In order to work with a pin, you need to open it, set its mode and then, either retrieve its value periodically ,or listen to an interrupt.
In the sample, the following steps are taken:

*

*Open the button pin: buttonPin = gpio.OpenPin(BUTTON_PIN);

*Set it as input: buttonPin.SetDriveMode(GpioPinDriveMode.InputPullUp);

*Listen to the interrupt with an event handler: buttonPin.ValueChanged += buttonPin_ValueChanged;
Generally speaking, you should work with both Raspbian and Windows IoT to understand how RPi behaves:

*

*Windows IoT doesn't yet support RPi's full functionality yet so there are things that are far easier to do with Raspbian than Windows IoT, eg using temperature sensors or any device with 1-Wire support.

*Sensor manufacturers provide samples, code and even libraries for Rapsbian or Arduino. Getting the sensor to work is hard enough, you shouldn't have to translate from Raspbian to Windows IoT as well.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting Thumbnail from RSS Feed and Display in Listview i need some help with my RSS Feed Reader Script...
I want Thumbnails in my Listview taken from Rss Feeds Thumbnail
"content": [
      {
       "medium": "image",
       "url": "http://www......de/wp-content/uploads/2010/11/sgroth_web.jpg",
       "title": {
        "type": "html",
        "content": "sgroth_web"
       },
       "description": {
        "type": "html",
        "content": "contenthere 4."
       },
       "thumbnail": {
        "url": "http://www.sdddd.de/wp-content/uploads/2010/11/sgroth_web-150x150.jpg"
       }

have a look what i mean:
Preview
First comes the Thumbnail and then the Title of the Rss Feed..
This Code is Jquery and PHP...
and here is my Code to Display RssFeeds in JS:
$(function(){

getOnlineFeed('http://salzstreuner.de/category/aktuelle_ausgabe/feed');
    });
/* functions */
var listEntries = function(json) {
  if (!json.responseData.feed.entries) return false;
  $('#widgetTitle').text(json.responseData.feed.title);
  var articleLength =json.responseData.feed.entries.length;
  articleLength = (articleLength > maxLength) ? maxLength : articleLength;
  for (var i = 1; i <= articleLength ; i++) {
    var entry = json.responseData.feed.entries[i-1];
    $('#link' + i).text(entry.title);
    $('#articleHeader' + i).text(entry.title);
    $('#openButton' + i).attr('href', entry.link);
    $('#articleContent' + i).append(entry.content);
 $('#articleImage').append('');
  }
  $('#article1 .prevButton').remove();
  $('#article' + articleLength + ' .nextButton').remove();
  if (articleLength < maxLength) {
    for (i = articleLength + 1; i <= maxLength; i++) {
      $('#list' + i).remove();
      $('#article' + i).remove();
    }
  }
};
var getOnlineFeed = function(url) {
  var script = document.createElement('script');
  script.setAttribute('src', 'http://ajax.googleapis.com/ajax/services/feed/load?callback=listEntries&hl=ja&output=json-in-script&q='
                      + encodeURIComponent(url)
                      + '&v=1.0&num=' + maxLength);
  script.setAttribute('type', 'text/javascript');
  document.documentElement.firstChild.appendChild(script);
};
var getOfflineFeed = function(url) {
  var script = document.createElement('script');
  script.setAttribute('src', url);
  script.setAttribute('type', 'text/javascript');
  document.documentElement.firstChild.appendChild(script);
};

Output looks like This:
for(var i=1; i<=maxLength; i++){
  document.write(
    '

'
  );

I have Played with #articleImage but it doesn't work. I hope someone Outside can help me with this littleBig Problem...
THX
MAsterluke

A: You should use the url of the thumbnail:
('#articleImage').append('');


text:
Q: How can I convert the response coming from the api to image I have response coming from the api like attached image. I want to convert this response to the image. I have tried to convert this into base64 string but i am not able to do it as well.
Image of the response

api is like this:
          axios.get(`https://api.bamboohr.com/api/gateway.php/tadigital/v1/employees/2223/photo/large`,
                { auth: {
                    username: 'xxxxxxxxxxxxxxxxx',
                    password: 'xxxxxxxxxxxxxxxxx'
                  }
                }
                ).then(resp => {
                  console.log(resp.data)
          });

I want the solution without using responseType in the get request because api is not accepting the response type. I am not getting a way to convert this to image

A: 1 Encoding should be base64 you can do that on either on the server or the client.
2 The Raw data should be set as the following -
    <img ng-src="data:image/*;base64,{{Raw Binary Data}}"/>

A: It seems like the server is sending raw data
You can convert it to blob by using fetch like below:
const res = await fetch(url);
const data = await res.blob();
const image = URL.createObjectURL(data);

Set Image as src of an image tag

A:
I want the solution without using responseType in the get request because api is not accepting the response type.

responseType has nothing to do with server. It tells Axios how to handle the expected response data. In this scenario you could pass responseType: "blob", which can be passed to URL.createObjectURL() to create an URL that can be used as <img> src.
const url = 'https://api.bamboohr.com/api/gateway.php/tadigital/v1/employees/2223/photo/large';
axios.get(url, {
  auth: {
    username: 'xxxxxxxxxxxxxxxxx',
    password: 'xxxxxxxxxxxxxxxxx',
  },
  responseType: 'blob',
}).then((resp) => {
  const img = document.createElement('img');
  img.src = URL.createObjectURL(resp.data);
  img.alt = 'employee photo';

  document.body.append(img);
});

const url = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9Ii0xMS41IC0xMC4yMzE3NCAyMyAyMC40NjM0OCI+CiAgPHRpdGxlPlJlYWN0IExvZ288L3RpdGxlPgogIDxjaXJjbGUgY3g9IjAiIGN5PSIwIiByPSIyLjA1IiBmaWxsPSIjNjFkYWZiIi8+CiAgPGcgc3Ryb2tlPSIjNjFkYWZiIiBzdHJva2Utd2lkdGg9IjEiIGZpbGw9Im5vbmUiPgogICAgPGVsbGlwc2Ugcng9IjExIiByeT0iNC4yIi8+CiAgICA8ZWxsaXBzZSByeD0iMTEiIHJ5PSI0LjIiIHRyYW5zZm9ybT0icm90YXRlKDYwKSIvPgogICAgPGVsbGlwc2Ugcng9IjExIiByeT0iNC4yIiB0cmFuc2Zvcm09InJvdGF0ZSgxMjApIi8+CiAgPC9nPgo8L3N2Zz4K";

axios.get(url, {
  responseType: "blob",
}).then((resp) => {
  const img = document.createElement("img");
  img.src = URL.createObjectURL(resp.data);
  img.alt = "React icon";

  document.body.append(img);
}).catch((error) => {
  console.log(error);
});
<script crossorigin src="https://unpkg.com/axios@1/dist/axios.js"></script>

Note that you should call URL.revokeObjectURL() if you no longer need the URL.


text:
Q: Why here used return; in catch block? Why there is using return; keyword and what will happen when there will not use return;
i know that will go end of the function but still i don't understand what is meaning of that.
It's used at the main method how it will be go end of the main method???
try {
         //some code
    }

catch (//...) {

         return;  //why here using return; keyword
    }


text:
Q: How to inspect a Process Explorer full dump I've been having some trouble with Visual Studio 2010. It stops working, and I see it increases in memory usage. So I suspect a memory leak (in one of the plugins maybe). I took a Full Dump with Process Explorer (procexp.exe), but am a bit at loss of what to do with it.
I tried loading it in WinDbg (through File > Open Crash Dump), but get an error 'Symbol file could not be found'.
Can anyone point me in the right direction? Making dump files is easy, but what do you do with them afterwards?

A: You might want to check this out for more information: https://www.networkworld.com/article/2320271/how-to-solve-windows-system-crashes-in-minutes.html


text:
Q: Facebook api permission issue I am having problems with the Facebook Graph API when trying to call the webservice for publishing a wall post for a user.
I have correctly authenticated my user with my app and it shows that I have permission for "Post to my Wall" in privacy settings.
I call the webservice URL http://graph.facebook.com/me/feed and use these as parameters:

*

*access_token=xxxxxxx  (access token back from authenticating)

*message=test message

Everytime I get a 403 error from the webservice

{"error":{"type":"OAuthException","message":"(#200)
  The user hasn't authorized the
  application to perform this action"}}

What could I be doing wrong ?

A: From the error message, it sounds like either the access token is incorrect or lacks the publish_stream permission.  (You said you're providing a token with that permission, but since that's the error message it's worth double checking.)
Reference: http://developers.facebook.com/docs/reference/api/status/, http://developers.facebook.com/docs/authentication/permissions.

A: I not sure why I was getting this error, but as I am using Ruby on Rails I tried the Facebook Graph API gem fp_graph and it worked a treat.
Thanks anyway guys.


text:
Q: What's the rationale for preventing assignment to arrays? I've tried to google this and have read:

*

*Why can't arrays of same type and size be assigned?

*Assigning arrays

*Assign to array in struct in c
But they all state the obvious: you can't assign to arrays because the standard says so. That's great and all, but I want to know why the standard doesn't include support for assigning to arrays. The standard committee discusses things in detail, and I'd be surprised if they never discussed making arrays assignable. Assuming they've discussed it, they must have some rationale for not letting arrays be assigned to.
I mean, we can put an array in a struct and assign to the struct just fine:
struct wrapper
{
    int array[2];
};

struct wrapper a = {{1, 2}};
struct wrapper b = {{3, 4}};
a = b; // legal

But using an array directly is prohibited, even though it accomplishes effectively the same thing:
int a[2] = {1, 2};
int b[2] = {3, 4};
a = b; // Not legal

What is the standard committee's rationale for prohibiting assigning to arrays?

A: The answer is simple: It never was allowed before the committee got involved (even struct-assignment was considered too heavy), and considering there's array-decay, allowing it would have all kinds of interesting consequences.
Let's see what would change:
int a[3], b[3], *c = b, *d = b;
a = b; // Currently error, would assign elements
a = c; // Currently error, might assign array of 3?
c = a; // Currently pointer assignment with array decay
c = d; // Currently pointer assignemnt

So, allowing array-assignment would make (up to) two currently disallowed assignments valid.
That's not the trouble though, it's that near-identical expressions would have wildly different results.
That gets especially piquant if you consider that array-notation in function arguments is currently just a different notation for pointers.
If array assignment was introduced, that would become even more confusing.
Not that enough people aren't completely confounded by things as they are today...
int g(int* x);  // Function receiving pointer to int and returning int
int f(int x[3]);// Currently the same. What afterwards? Change to value-copy?

A: Understand that the intent wasn't to make array expressions unassignable; that wasn't the goal1.  Rather, this behavior falls out of a design decision Ritchie made that simplified array handling in the compiler, but in exchange made arrays expressions "second-class" objects; they lose their "array-ness" in most contexts.
Read this paper (especially the section titled "Embryonic C") for some background; I also have a more detailed answer here.

1.  With the possible exception of Perl or PHP2, most blatant language WTFs are generally accidents of design or the result of compromises; most languages aren't deliberately designed to be stupid.

2.  I'm only trolling a little bit; Perl and PHP are straight-up messes.

A: C is written in such a way that the address of the first element would be computed when the array expression is evaluated.
Quoting an excerpt from this answer:

This is why you can't do something like
int a[N], b[N];
a = b;

because both a and b evaluate to pointer values in that context; it's equivalent to writing 3 = 4.  There's nothing in memory that actually stores the address of the first element in the array; the compiler simply computes it during the translation phase.

A: In C, assignment copies the contents of a fixed-size object to another fixed-size object. This is well defined and fairly straightforward to implement for scalar types (integers, floating-point, pointers, complex types since C99). Assignment of structs is nearly as simple; larger ones might require a call to memcpy() or equivalent, but it's still straightforward since the size and alignment are known at compile time.
Arrays are a different matter. Most array objects have sizes that aren't determined until run time. A good example is argv. The runtime environment constructs an array of char for each command-line argument, and an array of char* containing pointers to the arguments. These are made available to main via argv, a char**, and via the dynamically allocated char[] arrays that the elements of argv point to.
C arrays are objects in their own right, but they're not generally accessed as objects. Instead, their elements are accessed via pointers, and code traverses from one element to the next using pointer arithmetic.
Languages can be designed to treat arrays as first-class objects, with assignment -- but it's complicated. As a language designer, you have to decide whether an array of 10 integers and an array of 20 integers are the same type. If they are, you have to decide what happens when you try to assign one to the other. Does it copy the smaller size? Does it cause a runtime exception? Do you have to add a slice operation so you can operate on subsets of arrays?
If int[10] and int[20] are distinct types with no implicit conversion, then array operations are inflexible (see Pascal, for example).
All these things can be defined (see Ada), but only by defining higher-level constructs than what's typical in C. Instead, the designers of C (mostly Dennis Ritchie) chose to provide arrays with low-level operations. It's admittedly inconvenient at times, but it's a framework that can be used to implement all the higher-level array operations of any other language.

A: Maybe it would be helpful to turn the question around, and ask why you'd ever want to assign arrays (or structs), instead of using pointers?  That's much cleaner & easier to understand (at least if you've assimilated the Zen of C), and it has the benefit of not concealing the fact that a lot of work is hidden under the "simple" assignment of multi-megabyte arrays.

A: The reason is basically historic. There was a C even before ISO C89 which was called "K&R" C, after Kernighan and Ritchie. The language was designed to be small enough so a compiler would fit in severely limited (by today's standards) memory of 64kb.
This language did not allow assigning arrays. If you wanted to copy same-sized arrays, memcpy was there for your needs. Writing memcpy(a, b, sizeof a) instead of a = b is certainly not a big complication. It has the additional advantage of being generalizable to different-sized arrays and array slices.
Interestingly, the struct assignment workaround you mention also did not work in K&R C. You had to either assign members one by one or, again, use memcpy. The first edition of K&R's The C Programming language mentions struct assignment as a feature for future implementation in the language. Which eventually happened with C89.


text:
Q: Some problems about live data In sign up fragment,  I have term condition part. When you click this text, bottom sheets opens. I  click the button that end of the page(Accept Button). I want checkbox in sign up should be clicked.
Repository
  var resultOk = MutableLiveData<Boolean>()
  fun checkResult(){
    resultOk.value = true
}

Sign Up View Model
`
private var _resultOk = MutableLiveData<Boolean>()
val resultOk: LiveData<Boolean>
    get() = _resultOk

 init {
    _resultOk = firebaseRepo.resultOk
}

Sign Up Fragment
      viewModel.resultOk.observe(viewLifecycleOwner, Observer {
        binding.cbTermsAndCondition.isChecked = it
    })

BottomSheetView Model
  init {
    checkResult()
}

fun checkResult() {
    fireBaseRepository.checkResult()
}

BottomSheet Fragment
     binding.btnTermAccept.setOnClickListener {
        //Constant.result.value = true
        //viewModel.resultOk.value
        viewModel.checkResult()
        dismiss()
    }

Why checkbox is not clicked, when I click "accept button" end of the bottomsheet.

A: I found my answer. There are 2 way to solve this problem.
1) var result =MutableLiveData(false) you should do it as Singleton and then observe it.
2) You can use shared viewModel enter link description here


text:
Q: Detecting if the silverlight plugin is installed but disabled Using silverlight.js and calling Silverlight.isInstalled(slVersionNumber) accurately returns whether an up-to-date enough version of Silverlight is installed. However, if the Silverlight plugin has been disabled, it still returns true.
Is there a way to determine via JS whether the installed Silverlight plugin is enabled or disabled?
(note: testing in IE8 on Windows 7)

A: You can do this with two steps:
1st step: Detect whether Silverlight is working, e.g. host a test plugin and let it invoke a javascript method like this
Silverlight
HtmlPage.Window.Invoke("setSilverlightWorks", new bool[] { true });

Javascript
var silverlightWorks = false;
setSilverlightWorks(value) { globalSilverlightWorks = value;}

2nd step: If Silverlight does not work, you can do your IsInstalled-test. If it has been installed, it must be disabled.


text:
Q: Intersection of two lists in jinja templates for condition? [Home Assistant] How to intersect two lists in Home Assistant jinja templates?
The goal is to return a single boolean value, so it can be used in conditions.
Example (HA Developer Tools / Temaples):
{% set my_test_json = {
  "list1": ["a1", "a2", "b1", "b2"],
  "list2": ["a2", "b2", "c2", "d2"]
} %}

How to return true if there are common elements between list1 and list2 or false otherwise?
Thanks!


text:
Q: How to remove the P tag from TinyMCE I work with TinyMCE and it surrounds my text with a <p> tag.
I tried using this: forced_root_block : "" following this: How can I remove p tags that are auto added within tinymce
and this isn't working for me :X
I saw this post too:
remove the extra p tag in tinyMCE
and added:
forced_root_block : "",
force_br_newlines : true,
force_p_newlines : false

and this isn't helping.
This is my current code part:
<script type="text/javascript">
    tinymce.init({
        selector: ".mytextarea",
        plugins: "paste",
        paste_auto_cleanup_on_paste : true,
        paste_remove_styles: true,
        paste_remove_styles_if_webkit: true,
        paste_strip_class_attributes: "all",
        forced_root_block : "",
        force_br_newlines : true, // tried with and without
        force_p_newlines : false // tried with and without
        //paste_remove_spans : true
    });
</script>

A: you need to add the following line to your init statement
forced_root_block :false

<script type="text/javascript">
    tinymce.init({
        selector: ".mytextarea",
        plugins: "paste",
        paste_auto_cleanup_on_paste : true,
        paste_remove_styles: true,
        paste_remove_styles_if_webkit: true,
        paste_strip_class_attributes: "all",
        forced_root_block : false,
        force_br_newlines : true, // tried with and without
        force_p_newlines : false // tried with and without
        //paste_remove_spans : true
    });
</script>

if this not work than try  change in "tiny_mce.js" and not in "tiny_mce_src.js"


text:
Q: If a segment of length 1 is randomly divided into n intervals, with what probability are all intervals are less than 1/k? If $n-1$ points are chosen at random on a line segment of length $1$ (with uniform distribution), thus dividing it into $n$ segments, what is the probability that no segment has a length greater than $1/k$?
I've gotten this far as of now-
For $k=2$, only one segment can be greater than $1/2$, so, the probability is just 1 - n times the probability of first segment being of length greater than $1/2$.
so $P = 1-(n/2^{n-1})$

A: Let us write
$$F_n(x) = \mathbb{P}\left(\max_{1\leq i \leq n} L_{n,i} \leq x \right), $$
where $L_{n,i}$ is the length of the $i$-th gap created by $n-1$ points chosen uniformly at random on $[0, 1]$, independent of each other.
Now let $U_1, \cdots, U_n \sim \mathcal{U}[0,1]$ be independently chosen points on $[0, 1]$ and $L_{n+1,i}$ be the length of the corresponding $i$-th gap. Conditioning on $L_{n+1,1} = \min\{U_1,\cdots,U_n\}$, we easily check that
\begin{align*}
F_{n+1}(x)
&= \mathbb{P}\left( \{ L_{n+1,1} \leq x \} \cap \Big\{ \max_{2\leq i \leq n+1} L_{n+1,i} \leq x \Big\} \right) \\
&= \sum_{k=1}^{n} \mathbb{P}\left( \{ U_k \leq x \} \cap \{ \forall l \neq k \ : \ U_l > U_k \} \cap \Big\{ \max_{2\leq i \leq n+1} L_{n+1,i} \leq x \Big\} \right) \\
&= \sum_{k=1}^{n} \mathbb{E} \left[ \mathbb{P}\left( \{ \forall l \neq k \ : \ U_l > U_k \} \cap \Big\{ \max_{2\leq i \leq n+1} L_{n+1,i} \leq x \Big\} \, \middle| \, U_k \right) \mathbf{1}_{\{ U_k \leq x \}} \right] \\
&= \sum_{k=1}^{n} \mathbb{E} \left[ F_n\left(\frac{x}{1-U_k}\right) (1 - U_k)^{n-1} \mathbf{1}_{\{ U_k \leq x \}} \right] \\
&= \int_{0}^{x \wedge 1} F_n\left(\frac{x}{1-u}\right) n(1-u)^{n-1} \, du
\end{align*}
Here, the last line follows from the fact that, given the value of $U_k$ and $U_l > U_k$ for $l \neq k$, points $\{U_l : l \neq k\}$ are i.i.d. and uniformly distributed over $[U_k, 1]$.
With the initial condition $F_1(x) = \mathbf{1}_{[1,\infty)}(x)$, this completely determines $F_n$ at least theoretically. As to an exact formula, we claim that

Claim. We have
$$ F_n(x) = \sum_{k=0}^{n} (-1)^k \binom{n}{k}(1-kx)_{+}^{n-1}, \tag{*} $$
where we interpret $x_+^0 = \mathbf{1}_{\{x > 0\}}$ when $n = 1$.

This easily follows from the recursive formula of $(F_n)$ together with the integration formula
$$\int_{a}^{b} n x_+^{n-1} \, dx = b_+^n - a_+^n$$
for $a \leq b$ and $n \geq 1$. In particular, this tells that

*

*$F_n(\frac{1}{2}) = 1 - n(\frac{1}{2})^{n-1}$,

*$F_n(\frac{1}{3}) = 1 - n(\frac{2}{3})^{n-1} + \frac{n(n-1)}{2}(\frac{1}{3})^{n-1}$,

*$F_n(\frac{1}{4}) = 1 - n(\frac{3}{4})^{n-1} + \frac{n(n-1)}{2}(\frac{2}{4})^{n-1} - \frac{n(n-1)(n-2)}{6}(\frac{3}{4})^{n-1}$
and so forth.

Addendum. The formula $\text{(*)}$ seems to suggest an inclusion-exclusion argument but I haven't tried pursuing this direction.

A: Let $L_i$ be the length of some subsegment. We have that:
$\mathbb{P}[L_i\leq1/k:\forall i]=1-\mathbb{P}[L_i>1/k:\exists i]$
Now $\mathbb{P}[L_i>1/k:\exists i]\implies$there are all $n-1$ points in a subsegment $(1-\frac{1}{k},1]$. Keep in mind that since $L_i>1/k$ the point forming $L_i$ is also in this length.
Since points are uniformly distributed and $\mathbb{P}[\textrm{point in }(1-\frac{1}{k},1]]=1-\frac{1}{k}$, we get:
$\mathbb{P}[n-1\textrm{ points in }(1-\frac{1}{k},1]]=\mathbb{P}[\textrm{point in }(1-\frac{1}{k},1]]^{n-1}=(1-\frac{1}{k})^{n-1}$
Hence
$\mathbb{P}[L_i\leq1/k:\forall i]=1-(1-\frac{1}{k})^{n-1}$


text:
Q: Tomcat http to https redirect with custom cache control header We have a spring boot application deployed in tomcat. We want tomcat to redirect http requests to https. But we want to disable tomcat adding 'Cache-Control:private' to all response headers by default.
For rest API  requests we want the default cache header added by spring boot.
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Pragma:no-cache
Expires:0

but from tomcat it is
Cache-Control:private
Cache-Control:private
Expires:Wed, 31 Dec 1969 19:00:00 EST
Expires:Wed, 31 Dec 1969 19:00:00 EST

Seems as if 'Expires' header will give same no cache effect. But would like to know if there is way to stop tomcat from adding cache header. For static files also the header is 'private, max-age=2592000, public' instead of 'max-age=2592000, public'.  Below are my tomcat configurations and code to add custom cache header for static files.
server.xml
...
<Connector port="80" protocol="HTTP/1.1" connectionTimeout="20000"
           redirectPort="443"/>
....
 <Connector port="443" protocol="org.apache.coyote.http11.Http11NioProtocol"
           maxThreads="150" SSLEnabled="true" secure="true" scheme="https" compression="on"
     sslProtocol="TLSv1.2" sslEnabledProtocols="TLSv1.2" sslCipherSuite="SHA1/SHA2"
     acceptCount="100" clientAuth="false" disableUploadTimeout="true"
     keystoreFile="mycertificate" keystorePass="mypassword" server="Server">

web.xml
...
<security-constraint>
     <web-resource-collection>
         <web-resource-name>Protected Context</web-resource-name>
         <url-pattern>/*</url-pattern>
     </web-resource-collection>
     <user-data-constraint>
         <transport-guarantee>CONFIDENTIAL</transport-guarantee>
     </user-data-constraint>
</security-constraint>
...

Custom Caching
@Configuration
public class LocaleConfiguration extends WebMvcConfigurerAdapter{

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry
            .addResourceHandler("/content/**")
            .addResourceLocations("/content/")
            .setCacheControl(CacheControl.maxAge(30, TimeUnit.DAYS).cachePublic());
    }
}


text:
Q: Using external data in a package In a package I am working on, I would like to use data from another package (say, "pckg"). That package is imported ("Imports: pckg" in DESCRIPTION and import(pckg) in NAMESPACE). In one of the functions, I have the following:
someFunc <- function() {
  data(pckgdata)
  foo <- pckgdata$whatever
}

This results in the following error message when checking the package:
someFunc: no visible binding for global variable 'pckgdata'
someFunc : <anonymous>: no visible binding for global variable
  'pckgdata'
Undefined global functions or variables:
  pckgdata

How should I correctly use data sets from other packages in my own package?

A: Here is the description of the answer from @hrbmstr (see comments to the question). In short: first, create a global variable holding a new environment. Then, load the data into that environment. Then, access the data through the global variable:
.myenv <- new.env(parent=emptyenv())

someFunc <- function() {
  data("pckgdata", package="pckg", envir=.myenv)
  foo <- .myenv$pckgdata$whatever
}


text: Q: How to determine the angle for constructive interference of incoherent light in Young's double slit experiment? I understand that we would need to consider the phase difference to answer this question but I am unsure of how to do so.


text:
Q: ESP8266 Exception 3 I use the WiFiClient to connect to an external host and read the payload. That part of the code works fine until I've tried to collect the chars into one string to parse it after.
There is the code
#include <ESP8266WiFi.h>

const char* ssid = "***";
const char* password = "***";

const char* host = "host.com";

void setup()
{
  Serial.begin(115200);
  Serial.println();

  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println(" connected");
  pinMode(D5, OUTPUT);
}

void runBullshit()
{
  digitalWrite(D5, true);
  delay(500);
  digitalWrite(D5, false);
}

void loop()
{
  WiFiClient client;

  if (client.connect(host, 80))
  {
    client.print(String("GET /path") + " HTTP/1.1\r\n" +
             "Host: " + host + "\r\n" +
             "Connection: close\r\n" +
             "\r\n"
            );

    char payload[] = "";
    int size = 0;

    while (client.connected())
    {
      if (client.available())
      {
        char data = client.read();
        payload[size] = data;
      }
      size++;
    }
    payload[sizeof(payload)] = '\0';
    Serial.println(payload);
    client.stop();
  }
  else
  {
    Serial.println("connection failed!]");
    client.stop();
  }
  delay(3000);
}

And there are the errors
Connecting to MikroTik-35C8D8 . connected

Exception (3):
epc1=0x40202611 epc2=0x00000000 epc3=0x00000000 excvaddr=0x40016d7f        depc=0x00000000

ctx: cont
sp: 3ffffd80 end: 3fffffd0 offset: 01a0

>>>stack>>>
3fffff20:  00000000 40203ce8 3ffe8510 00000000
3fffff30:  3fffdad0 3ffeeab4 40203e0c 3fffefb0
3fffff40:  3fffdad0 00000000 00000064 40203ec6
3fffff50:  3fffdad0 00000000 3fffff98 40203f09
3fffff60:  3fffdad0 00000000 00000048 40203482
3fffff70:  3ffe88b9 00000000 40016d7f 40202611
3fffff80:  40204348 00000000 00001388 40203908
3fffff90:  00000000 3ffef77c 00000000 00000000
3fffffa0:  00000000 00000000 00000000 00000000
3fffffb0:  3fffdad0 00000000 3ffeeaac 40203e98
3fffffc0:  feefeffe feefeffe 3ffe8510 40100739
<<<stack<<<

ets Jan  8 2013,rst cause:2, boot mode:(3,7)

load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
vbb28d4a3
~ld

So, if I'll just put the data into the Serial I'll see the whole payload with no errors, but in the case, up above I catch the Exception 3 and cause 2.
PS And yeah, in my code I have digitalWrite and so on because I'm going to use the response to decide set the pin to HIGH or not

A: The problem is that you define payload as an array of size 1. You can not store your data into it.
On Arduino you can use the String type:
String payload;

while (client.connected())
{
  if (client.available())
  {
    char data = client.read();
    payload += data;
  }
}

Serial.println(payload);
client.stop();


text:
Q: Python 3 : in a text file, get the x occurrences of a string in the y lines where it occurs I have a text (CountOccurrences.txt)
Paris Rome
berlin London Berlin
London Rome London
Paris Berlin Berlin
Rome London
Berlin Madrid
Parisian Berliner

I want to count the x occurrences of a string in the y lines where it occurs.
Here is my code
f = open('CountOccurrences.txt')

word = input("Enter word to be looked for : ")

oc = 0
li = 0

for line in f:

    if word in line:
        li = li + 1

    words = line.split()
    for i in words:
        if(i==word):
            oc = oc + 1

print('Considering that this search is case-sensitive, \
there are', oc, 'occurrence(s) of the word, \
in', li, 'line(s)')

f.close

Here are the results for each word, with, as you can see, 2 problems :
Berlin       4 oc, 4 li (pb)
berlin       1 oc, 1 li
Berliner     1 oc, 1 li
London       4 oc, 3 li
Madrid       1 oc, 1 li
Paris        2 oc, 3 li (pb)
Parisian     1 oc, 1 li
Rome         3 oc, 3 li

I do not understand what goes wrong.
Thanks in advance for your help

A: The problem is if word in line: will return True when word is "Berlin", and the line includes "... Berliner..." because it exists as a substring of the "[Berlin]er".
Instead, do the check after splitting the line as  follows:
for line in f:
    words = line.split()
    for i in words:
        if(i==word):
            oc = oc + 1

    if word in words: # modified part
        li = li + 1


text:
Q: How can I write to a text file reliably from Excel VBA? I'm trying to use Excel VBA to write to a text file.  I'm doing a few of these:
MyFile1 = "C:\outputFromExcel1.txt"
fnum1 = FreeFile()
Open MyFile1 For Output As fnum1

and then writing to them like this:
Print #fnum1, text

All variables in the above are declared just with Dim.  I'm writing hundreds of lines to the files and, very rarely, lines are being truncated -- i.e. the ends are being chopped off.  Is there a better way to write to a file in Excel VBA?
EDIT: I've just realized that it's always the last lines to be written that are truncated.  So I guess I need to close or flush the files somehow?

A: Yes, you should be closing the files with the Close method. I'm not sure if that's what causing the problems but you should be doing that either way.
If you're doing a lot of filehandling in your VBA code it might be worth looking at using FSO (FileSystemObject), I think it was originally for letting VBScript do file processing, but I prefer it to both VB6s and VBAs built in file handling.
See here for more details (and there's a big sample showing off how to do most things you need in one of those pages as well).

A: You can use Close #fnum1 to close the file handle and it should flush the remaining buffer contents.

A: Have you considered writing the text to a different sheet (or a different workbook) and then using:
ActiveWorkbook.SaveAs Filename:="C:\MyFile.txt", FileFormat:=xlText

Not sure if this would give you better results (in terms of performance and/or formatting), but perhaps worth a try.

A: Just a necro solution: I have found the Close #1 method to still leave a truncated file. Instead, or in addition to, use the Application.Quit for Excel to close Excel. This flushes the cache and completes the write to the text file.


text:
Q: How can I decode UTF-16 data in Perl when I don't know the byte order? If I open a file ( and specify an encoding directly ) :
open(my $file,"<:encoding(UTF-16)","some.file") || die "error $!\n";
while(<$file>) {
    print "$_\n";
}
close($file);

I can read the file contents nicely. However, if I do:
use Encode;

open(my $file,"some.file") || die "error $!\n";
while(<$file>) {
    print decode("UTF-16",$_);
}
close($file);

I get the following error:
UTF-16:Unrecognised BOM d at F:/Perl/lib/Encode.pm line 174

How can I make it work with decode?
EDIT: here are the first several bytes:
FF FE 3C 00 68 00 74 00

A: You need to specify either UTF-16BE or UTF-16LE. See http://perldoc.perl.org/Encode/Unicode.html#Size%2c-Endianness%2c-and-BOM

A: If you simply specify "UTF-16", Perl is going to look for the byte-order mark (BOM) to figure out how to parse it. If there is no BOM, it's going to blow up. In that case, you have to tell Encode which byte-order you have by specifying either "UTF-16LE" for little-endian or "UTF-16BE" for big-endian.
There's something else going on with your situation though, but it's hard to tell without seeing the data you have in the file. I get the same error with both snippets. If I don't have a BOM and I don't specify a byte order, my Perl complains either way. Which Perl are you using and which platform do you have? Does your platform have the native endianness of your file? I think the behaviour I see is correct according to the docs.
Also, you can't simply read a line in some unknown encoding (whatever Perl's default is) then ship that off to decode. You might end up in the middle of a multi-byte sequence. You have to use Encode::FB_QUIET to save the part of the buffer that you couldn't decode and add that to the next chunk of data:
open my($lefh), '<:raw', 'text-utf16.txt';

my $string;
while( $string .= <$lefh> ) {
    print decode("UTF-16LE", $string, Encode::FB_QUIET)
    }

A: What you're trying to do impossible.
You're reading lines of text without specifying an encoding, so every byte that contains a newline character (default \x0a) ends a line.  But this newline character may very well be in the middle of an UTF-16 character, in which case your next line can't be decoded.
If your data is UTF-16LE, this will happen all the time – line feeds are \x0a \x00.  If you have UTF16-BE, you might get lucky (newlines are \x00 \x0a), until you get a character with \x0a in the high byte.
So, don't do that, open the file in the right encoding.


text:
Q: Trouble rendering CSV data as an interactive table in GitHub When viewed, any .csv file committed to a GitHub repository automatically renders as an interactive table, complete with headers and row numbering. By default, the first row is your header row. The tables were supposed to look nice as below:

However, there's an error happening in my tabular data, and despite indicating the error, I can't fix it:

I'm using a .csv file with a semicolon separator. Does anyone have an idea of what's happening?

A: According to the docs, Github can only do its lay-out thing with .csv (comma-separated) and .tsv (tab-separated) files.
Using a semicolon as a separator isn't supported, at least not officially, and a spurious comma in a semicolon-separated file could well throw the algorithm off.
You could try replacing all semicolons with tabs and see how you fare.
If that doesn't work, try using commas as separators and enclose all text table cell data with quotes, like:

"Liver fibrosis, sclerosis, and cirrhosis","c370800","102922","Cystic fibrosis related cirrhosis","Diagnosis of liver fibrosis, sclerosis, and cirrhosis"

Note: no spaces after the commas. Also, if you have quotes in the text fields, you will have to escape those to "" (two quotes), or the algorithm will get confused.
You may get away with using quotes only for the offending text data, but that could well be more difficult to generate than just putting the quotes around all fields.


text:
Q: Where does Scrapy actually do the html request? I am using the Scrapy (Scrapy==1.6.0) library with Python3. I am wondering, where in the code does Scrapy actually do the HTML request? I want to set a breakpoint there so I can see exactly what headers / cookies / urls / and user agent is actually being passed.
Also, where exactly is the response received as well? Right now my spider is failing to find any pages, so I imagine I'm getting either a blank HTML document or a 403 error, however I have no idea where to look to confirm this.
Can anyone familiar with the scrapy library point me to exactly where in code I can check these parameters?

A: I believe you can check out scrapy/core/engine.py method _download.
Though I'd suggest you make use of scrapy shell. It will let you execute particular request, inspect response, open response in browser to see what was received by Scrapy. Also with a bit more of tuning you can import your spider in your shell and call a particular method of your spider and put a breakpoint there.
If your spider fails to find any pages then the problem is likely to be with your spider, not the framework.


text:
Q: Displaying the corresponding div which is linked to a nav element while updating the hash value As part of my thesis I implement a website. It has a nav with elements and divs with content.
I try to use the hash values in the url to display the right content div, the other divs are hidden/ set to none.
The url updates when I click the nav element (like the default behavior), but it's not showing the right div, because it's not adding the active class like it should.
The active class only sets display to block, like the commented line above.
I really don't know how to structure this whole thing. I also thought about merging the two parts, but I don't know how it would be best.
const pathName = window.location.hash.replace("#", "");

// Linking nav element with div
// And displaying active
navLinks.forEach((link) => {
  link.addEventListener("click", (e) => {
    // e.preventDefault();
    const targetDiv = link.getAttribute("href").substring(1);
    divs.forEach((div) => {
      if (div.id === targetDiv || !pathName) {
       // div.style.display = "block";
        div.classList.add("active");
      } else if (div.id == pathName) {
        document.getElementById(pathName).classList.add("active");
      } else {
       // div.style.display = "none";
        div.classList.remove("active");
      }
    });
  });
});

console.log("Pathname: " + pathName);
if (!pathName || pathName == "") {
  // document.getElementById("Home").style.display = "block";
  document.getElementById("Home").classList.add("active");
} else {
  // document.getElementById(pathname).style.display = "block";
  document.getElementById(pathName).classList.add("active");
}

A: After a comment from @Yogi helped me, this is my working code if anyone has the same issue:
const navLinks = document.querySelectorAll(".nav-links a");
const divs = document.querySelectorAll("div.articleDiv");

// Linking nav element with div
// And displaying active
navLinks.forEach((link) => {
  link.addEventListener("click", (e) => {
    e.preventDefault();
    const targetDiv = link.getAttribute("href").replace("#", "");
    divs.forEach((div) => {
      if (div.id === targetDiv) {
        div.classList.add("active");
      } else {
        div.classList.remove("active");
      }
    });
  });
});

const pathName = window.location.hash.replace("#", "");

window.addEventListener("load", (event) => {
  if (!pathName || pathName == "") {
    document.getElementById("Home").classList.add("active");
  } else {
    document.getElementById(pathName).classList.add("active");
  }
});


text:
Q: C# nested json object issue I think my json object is setup incorrectly. Trying to setup a nested json object.
 string jsonString = "{\"subsidiary\":\"2\", \"vendor_name\":\"644\", \"bill_no\":\"1\", \"due_date\":\"24/04/2016\", \"item:{\"item :\"38\", \"taxcode\":\"13\", \"rate\":\"140\"}" + file + "\"" + "}";

It doesn't get parsed correctly with a sytax error like:    SyntaxError: Expected : found i (null$lib#3)
EDIT: Tried the following but still the same error:
Dictionary<string, string> jsonObject = new Dictionary<string, string>(); jsonObject.Add("subsidiary", "2"); jsonObject.Add("vendor_name", "644"); jsonObject.Add("bill_no", "100"); jsonObject.Add("due_date", "24/04/2016"); jsonObject.Add("item", "38"); jsonObject.Add("taxcode", "13"); jsonObject.Add("rate", "100"); string js = JsonConvert.SerializeObject(jsonObject);

string jsonString = "{\"subsidiary\":\"2\", \"vendor_name\":\"644\", \"bill_no\":\"1\", \"due_date\":\"24/04/2016\", \"item\":{\"item\" :\"38\", \"taxcode\":\"13\", \"rate\":\"140\"}, \"file\":\"" + file + "\"" + "}";

A: It looks like you're missing a closing " after item.
You have
\"item:{\"item :\"38\"
it should be
\"item\":{\"item :\"38\"
But why are you building the JSON string manually? Use a library like Newtonsoft.Json and you won't have to worry about it.

A: Try this one:
string jsonString = "{\"subsidiary\":\"2\", \"vendor_name\":\"644\", \"bill_no\":\"1\", \"due_date\":\"24/04/2016\", \"item\":{\"item\" :\"38\", \"taxcode\":\"13\", \"rate\":\"140\"}, \"file\":\"" + file + "\"" + "}";

Demo here...


text:
Q: Setting Vollery ImgController with global variables extending application Im trying to use volley to load an image from a url with the next line:
Image.setImageUrl(url, ImgController.getInstance().getImageLoader());

But ImgController could not be resolved. I checked and found out that I need to register my Custom Application context in AndroidManifest.xml file, with the following line:
<application android:name="ImgController" android:allowBackup="true" android:icon="@drawable/icon" android:label="@string/app_name">

But i am already using a different context from my global variables (class that extends Application), like this:
<application android:name_"example.example.name.Global" android:allowBackup="true" android:icon="@drawable/icon" android:label="@string/app_name">

So here is my question, how can I set the ImgController without tampering with my Global varible class?
Thanks.

A: Ended up using Volley ImageRequest, which works just fine.
Here is the code:
public void fetchBackgroundImage(String url){
    ImageRequest imgRequest = new ImageRequest(url,
            new Response.Listener<Bitmap>() {
                @Override
                public void onResponse(Bitmap bitmap) {
                    Drawable banner = new BitmapDrawable(bitmap);
                    findViewById(R.id.headerImage).setBackgroundDrawable(banner);
                }
            },256,88,null,
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError ex) {
                     System.out.println(ex.getMessage().toString());
                }
            }
    );
    RequestQueue rq = Volley.newRequestQueue(this);
    rq.add(imgRequest);
}


text:
Q: How to update longblob image field in mysql using php  if(isset($_POST['submit']) and isset($_GET['slider_id']))
    {
        $date=date('Y-m-j');
        $imgName=$_FILES['image']['name'];
        $cont=file_get_contents($imgName);
         $cont=addslashes($cont);

         if($imgName=="")
         {
        //$imgData =addslashes(file_get_contents($_FILES['image']['name']));
        $res=mysqli_query($connect,'UPDATE `slider_images` SET `image`=\''.$cont.'\' WHERE id=\''.$_GET['slider_id'].'\'');
             if($res)
             {
                 echo "Updated";
             }
             else
             {
                 echo "Not Updated";
             }
        }
     }

Not understanding the real issue behind this and i have refereed many solution's but no success in that.All solution's i found they tell to store images in folder and store the file name in database table.Reason behind storing images in database is, only 4 images are to be stored, so why not to store them in database. Please guide me through this issue. Following is the issue i am talking about.
Warning Message
Thank's in advance.

A: *

*$_FILES['file']['name'] is the original name of the uploaded file from the user's computer.

*$_FILES['file']['tmp_name'] will contain the temporary file name of the file on the server. This is just a temporary placeholder until you process the file.

So you should access the file like this:
$cont=file_get_contents($_FILES['image']['tmp_name']);

Sidenote: Instead of if($res){ ... } use mysqli_affected_rows() to get number of rows affected by this UPDATE query, like this:

mysqli_query($connect,"UPDATE `slider_images` SET `image`='".$cont."' WHERE id='".$_GET['slider_id']."'");
if(mysqli_affected_rows($connect)){
    echo "Updated";
}else{
    echo "Not Updated";
}

Here's the reference:

*

*mysqli_affected_rows()


text:
Q: How Add user into "Access to this computer from the network" Local Policy by adding a registry key? Do you have any idea how can I add a user in Local policies? I need same effect like this
gpedit.msc -> Computer Configuration / Windows Settings / Security Settings / Local Policies / User Rights Assignment / "Access this computer from the network"
I would like to do that by adding a registry key or by running a command from cmd. If you have any hint or internet resource to share, I would be happy.
Thanks.

A: Here's one I prepared earlier. We use the (lengthy, sorry) wrapper class below to grant "Logon as a service right". The call for this is as follows:
var identity = new WindowsIdentity(logonName);
LsaSecurityWrapper.AddAccountRights(identity.User.AccountDomainSid,
    "SeServiceLogonRight");

You would just need to replace "SeServiceLogonRight" with your own. A quick Google tells me this should be "SeNetworkLogonRight". If you want this in a console app, then you can quickly compile one. Set your Main method like so:
static void Main(string[] args)
{
    var identity = new WindowsIdentity(args[0]);
    LsaSecurityWrapper.AddAccountRights(identity.User.AccountDomainSid, args[1]);
}

Then call as YourConsoleApp.exe logon right. Here's the wrapper:
[StructLayout(LayoutKind.Sequential)]
internal struct LSA_OBJECT_ATTRIBUTES
{
    internal int Length;
    internal IntPtr RootDirectory;
    internal IntPtr ObjectName;
    internal int Attributes;
    internal IntPtr SecurityDescriptor;
    internal IntPtr SecurityQualityOfService;
}

///
/// LSA_UNICODE_STRING structure
///
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct LSA_UNICODE_STRING
{
    internal ushort Length;
    internal ushort MaximumLength;
    [MarshalAs(UnmanagedType.LPWStr)] internal string Buffer;
}

///
/// Wraps LsaAddAccountRights call.
///
public sealed class LsaSecurityWrapper
{
    [DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true),
     SuppressUnmanagedCodeSecurityAttribute]
    internal static extern uint LsaOpenPolicy(
        LSA_UNICODE_STRING[] SystemName,
        ref LSA_OBJECT_ATTRIBUTES ObjectAttributes,
        int AccessMask,
        out IntPtr PolicyHandle
        );

    [DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true),
     SuppressUnmanagedCodeSecurityAttribute]
    internal static extern uint LsaAddAccountRights(
        LSA_HANDLE PolicyHandle,
        IntPtr pSID,
        LSA_UNICODE_STRING[] UserRights,
        int CountOfRights
        );

    [DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true),
     SuppressUnmanagedCodeSecurityAttribute]
    internal static extern uint LsaRemoveAccountRights(
        LSA_HANDLE PolicyHandle,
        IntPtr AccountSid,
        bool AllRights,
        LSA_UNICODE_STRING[] UserRights,
        int CountOfRights
        );

    [DllImport("advapi32")]
    internal static extern int LsaClose(IntPtr PolicyHandle);

    private enum Access : int
    {
        POLICY_READ = 0x20006,
        POLICY_ALL_ACCESS = 0x00F0FFF,
        POLICY_EXECUTE = 0X20801,
        POLICY_WRITE = 0X207F8
    }

    // rights: (http://msdn.microsoft.com/en-us/library/bb545671(VS.85).aspx)
    public static void AddAccountRights(SecurityIdentifier sid, string rights)
    {
        IntPtr lsaHandle;

        LSA_UNICODE_STRING[] system = null;
        LSA_OBJECT_ATTRIBUTES lsaAttr;
        lsaAttr.RootDirectory = IntPtr.Zero;
        lsaAttr.ObjectName = IntPtr.Zero;
        lsaAttr.Attributes = 0;
        lsaAttr.SecurityDescriptor = IntPtr.Zero;
        lsaAttr.SecurityQualityOfService = IntPtr.Zero;
        lsaAttr.Length = Marshal.SizeOf(typeof(LSA_OBJECT_ATTRIBUTES));
        lsaHandle = IntPtr.Zero;

        uint ret = LsaOpenPolicy(system, ref lsaAttr, (int)Access.POLICY_ALL_ACCESS, out lsaHandle);
        if (ret == 0)
        {
            Byte[] buffer = new Byte[sid.BinaryLength];
            sid.GetBinaryForm(buffer, 0);

            IntPtr pSid = Marshal.AllocHGlobal(sid.BinaryLength);
            Marshal.Copy(buffer, 0, pSid, sid.BinaryLength);

            LSA_UNICODE_STRING[] privileges = new LSA_UNICODE_STRING[1];

            LSA_UNICODE_STRING lsaRights = new LSA_UNICODE_STRING();
            lsaRights.Buffer = rights;
            lsaRights.Length = (ushort)(rights.Length * sizeof(char));
            lsaRights.MaximumLength = (ushort)(lsaRights.Length + sizeof(char));

            privileges[0] = lsaRights;

            ret = LsaAddAccountRights(lsaHandle, pSid, privileges, 1);

            LsaClose(lsaHandle);

            Marshal.FreeHGlobal(pSid);

            if (ret != 0)
            {
                throw new Win32Exception("LsaAddAccountRights failed with error code: " + ret);
            }
        }
        else
        {
            throw new Win32Exception("LsaOpenPolicy failed with error code: " + ret);
        }
    }
}

A: I suspect you'll need to use pinvoke and wrap around the appropriate Lsa functions, http://msdn.microsoft.com/en-us/library/windows/desktop/ms721786(v=vs.85).aspx
http://www.pinvoke.net/default.aspx/advapi32.lsaaddaccountrights


text:
Q: WSO2 ESB 4.5.0 fails to start, hanging after mount to the remote registry I'm having a problem with ESB start up. It fails right after mounting to the remote repository after the following INFO message, but previously it started without any problems with the same configuration:
TID: [] [WSO2 Enterprise Service Bus] [2012-11-28 15:16:22,604]  INFO {org.wso2.carbon.registry.core.internal.RegistryCoreServiceComponent} -  Registry Mode    : READ-WRITE {org.wso2.carbon.registry.core.internal.RegistryCoreServiceComponent}

I have enabled debug and notice some recurring messages that never stop to occur:
TID: [] [WSO2 Enterprise Service Bus] [2012-11-28 15:25:21,926] DEBUG    {org.wso2.carbon.registry.core.statistics.StatisticsLog} -  Total Number of Connections Created      : 598 {org.wso2.carbon.registry.core.statistics.StatisticsLog}
TID: [] [WSO2 Enterprise Service Bus] [2012-11-28 15:25:21,926] DEBUG {org.wso2.carbon.registry.core.statistics.StatisticsLog} -  Total Number of Connections Closed       : 614 {org.wso2.carbon.registry.core.statistics.StatisticsLog}
TID: [] [WSO2 Enterprise Service Bus] [2012-11-28 15:25:21,926] DEBUG {org.wso2.carbon.registry.core.statistics.StatisticsLog} -  Total Number of Connections Committed    : 614 {org.wso2.carbon.registry.core.statistics.StatisticsLog}
TID: [] [WSO2 Enterprise Service Bus] [2012-11-28 15:25:21,926] DEBUG {org.wso2.carbon.registry.core.statistics.StatisticsLog} -  Total Number of Connections Rollbacked   : 0 {org.wso2.carbon.registry.core.statistics.StatisticsLog}
TID: [] [WSO2 Enterprise Service Bus] [2012-11-28 15:25:21,926] DEBUG {org.wso2.carbon.registry.core.statistics.StatisticsLog} -  Total Number of Statements Prepared      : 402 {org.wso2.carbon.registry.core.statistics.StatisticsLog}
TID: [] [WSO2 Enterprise Service Bus] [2012-11-28 15:25:21,926] DEBUG {org.wso2.carbon.registry.core.statistics.StatisticsLog} -  Total Number of Statements Closed        : 402 {org.wso2.carbon.registry.core.statistics.StatisticsLog}
TID: [] [WSO2 Enterprise Service Bus] [2012-11-28 15:25:21,926] DEBUG {org.wso2.carbon.registry.core.statistics.StatisticsLog} -  Total Number of Active Transactions      : 0 {org.wso2.carbon.registry.core.statistics.StatisticsLog}
TID: [] [WSO2 Enterprise Service Bus] [2012-11-28 15:25:22,115] DEBUG {org.wso2.carbon.registry.core.statistics.StatisticsLog} -  Total Number of get calls                : 36 {org.wso2.carbon.registry.core.statistics.StatisticsLog}
TID: [] [WSO2 Enterprise Service Bus] [2012-11-28 15:25:22,115] DEBUG {org.wso2.carbon.registry.core.statistics.StatisticsLog} -  Total Number of put calls                : 0 {org.wso2.carbon.registry.core.statistics.StatisticsLog}
TID: [] [WSO2 Enterprise Service Bus] [2012-11-28 15:25:22,115] DEBUG {org.wso2.carbon.registry.core.statistics.StatisticsLog} -  Total Number of import calls             : 0 {org.wso2.carbon.registry.core.statistics.StatisticsLog}
TID: [] [WSO2 Enterprise Service Bus] [2012-11-28 15:25:22,115] DEBUG {org.wso2.carbon.registry.core.statistics.StatisticsLog} -  Total Number of move calls               : 0 {org.wso2.carbon.registry.core.statistics.StatisticsLog}
TID: [] [WSO2 Enterprise Service Bus] [2012-11-28 15:25:22,115] DEBUG {org.wso2.carbon.registry.core.statistics.StatisticsLog} -  Total Number of copy calls               : 0 {org.wso2.carbon.registry.core.statistics.StatisticsLog}
TID: [] [WSO2 Enterprise Service Bus] [2012-11-28 15:25:22,115] DEBUG {org.wso2.carbon.registry.core.statistics.StatisticsLog} -  Total Number of rename calls             : 0 {org.wso2.carbon.registry.core.statistics.StatisticsLog}
TID: [] [WSO2 Enterprise Service Bus] [2012-11-28 15:25:22,115] DEBUG {org.wso2.carbon.registry.core.statistics.StatisticsLog} -  Total Number of delete calls             : 0 {org.wso2.carbon.registry.core.statistics.StatisticsLog}
TID: [] [WSO2 Enterprise Service Bus] [2012-11-28 15:25:22,116] DEBUG {org.wso2.carbon.registry.core.statistics.StatisticsLog} -  Total Number of addAssociation calls     : 0 {org.wso2.carbon.registry.core.statistics.StatisticsLog}
TID: [] [WSO2 Enterprise Service Bus] [2012-11-28 15:25:22,116] DEBUG {org.wso2.carbon.registry.core.statistics.StatisticsLog} -  Total Number of removeAssociation calls  : 0 {org.wso2.carbon.registry.core.statistics.StatisticsLog}
TID: [] [WSO2 Enterprise Service Bus] [2012-11-28 15:25:22,116] DEBUG {org.wso2.carbon.registry.core.statistics.StatisticsLog} -  Total Number of getAssociations calls    : 0 {org.wso2.carbon.registry.core.statistics.StatisticsLog}
TID: [] [WSO2 Enterprise Service Bus] [2012-11-28 15:25:22,116] DEBUG {org.wso2.carbon.registry.core.statistics.StatisticsLog} -  Total Number of getAllAssociations calls : 0 {org.wso2.carbon.registry.core.statistics.StatisticsLog}
TID: [] [WSO2 Enterprise Service Bus] [2012-11-28 15:25:22,116] DEBUG {org.wso2.carbon.registry.core.statistics.StatisticsLog} -  Total Number of executeQuery calls       : 0 {org.wso2.carbon.registry.core.statistics.StatisticsLog}
TID: [] [WSO2 Enterprise Service Bus] [2012-11-28 15:25:22,116] DEBUG {org.wso2.carbon.registry.core.statistics.StatisticsLog} -  Total Number of resourceExists calls     : 234 {org.wso2.carbon.registry.core.statistics.StatisticsLog}
TID: [] [WSO2 Enterprise Service Bus] [2012-11-28 15:25:22,116] DEBUG {org.wso2.carbon.registry.core.statistics.StatisticsLog} -  Total Number of dump calls               : 0 {org.wso2.carbon.registry.core.statistics.StatisticsLog}
TID: [] [WSO2 Enterprise Service Bus] [2012-11-28 15:25:22,116] DEBUG {org.wso2.carbon.registry.core.statistics.StatisticsLog} -  Total Number of restore calls            : 0 {org.wso2.carbon.registry.core.statistics.StatisticsLog}
TID: [] [WSO2 Enterprise Service Bus] [2012-11-28 15:25:24,262] DEBUG {org.wso2.carbon.user.core.util.DatabaseUtil} -  Total Number of Connections Created      : 2 {org.wso2.carbon.user.core.util.DatabaseUtil}
TID: [] [WSO2 Enterprise Service Bus] [2012-11-28 15:25:24,262] DEBUG {org.wso2.carbon.user.core.util.DatabaseUtil} -  Total Number of Connections Closed       : 12 {org.wso2.carbon.user.core.util.DatabaseUtil}

The full log is available here
master-datasource.xml:
 <datasource>
        <name>WSO2_CARBON_DB</name>
        <description>The datasource used for registry and user manager</description>
        <jndiConfig>
            <name>jdbc/WSO2CarbonDB</name>
        </jndiConfig>
        <definition type="RDBMS">
            <configuration>
                <url>jdbc:mysql://localhost:3306/WSO2_ESB?autoReconnect=true</url>
                <username>username</username>
                <password>password</password>
                <driverClassName>com.mysql.jdbc.Driver</driverClassName>
                <maxActive>50</maxActive>
                <maxWait>60000</maxWait>
                <testOnBorrow>true</testOnBorrow>
                <validationQuery>SELECT 1</validationQuery>
                <validationInterval>30000</validationInterval>
            </configuration>
        </definition>
    </datasource>

    <datasource>
        <name>WSO2_CARBON_DB_GREG</name>
        <description>The datasource used for registry </description>
        <jndiConfig>
            <name>jdbc/WSO2CarbonDB_GREG</name>
        </jndiConfig>
        <definition type="RDBMS">
            <configuration>
                <url>jdbc:mysql://localhost:3306/WSO2_REGISTRY?autoReconnect=true</url>
                <username>username</username>
                <password>password</password>
                <driverClassName>com.mysql.jdbc.Driver</driverClassName>
                <maxactive>50</maxactive>
                <maxwait>60000</maxwait>
                <testonborrow>true</testonborrow>
                <validationquery>SELECT 1</validationquery>
                <validationinterval>30000</validationinterval>
            </configuration>
        </definition>
    </datasource>

registry.xml:
<currentDBConfig>wso2registry</currentDBConfig>
<readOnly>false</readOnly>
<enableCache>true</enableCache>
<registryRoot>/</registryRoot>

<dbConfig name="wso2registry">
    <dataSource>jdbc/WSO2CarbonDB</dataSource>
</dbConfig>

<dbConfig name="wso2registry_mounted">
    <dataSource>jdbc/WSO2CarbonDB_GREG</dataSource>
</dbConfig>

<remoteInstance url="https://localhost:9443/registry">
    <id>wso2_registry_mounted</id>
    <dbConfig>wso2registry_mounted</dbConfig>
    <readOnly>false</readOnly>
    <enableCache>true</enableCache>
    <registryRoot>/</registryRoot>
</remoteInstance>

<mount overwrite="true" path="/_system/config">
    <instanceId>wso2_registry_mounted</instanceId>
    <targetPath>/_system/nodes</targetPath>
</mount>

<mount overwrite="true" path="/_system/governance">
    <instanceId>wso2_registry_mounted</instanceId>
    <targetPath>/_system/governance</targetPath>
</mount>

Did anyone suffered the same issue?
Thanks in advance,
Vladimir.

A: I noticed tag errors in your configurations.Tags are case sensitive. below tags are wrong in your second data source configuration.
<maxactive>50</maxactive>
<maxwait>60000</maxwait>
<testonborrow>true</testonborrow>
<validationquery>SELECT 1</validationquery>
<validationinterval>30000</validationinterval>

it should be,
<maxActive>50</maxActive>
<maxWait>60000</maxWait>
<testonBorrow>true</testonBorrow>
<validatiOnQuery>SELECT 1</validatiOnQuery>
<validatiOnInterval>30000</validatiOnInterval>

Same time you can follow the guide in [1].

*

*http://ajithvblogs.blogspot.com/2012/09/create-jdbc-mount-to-wso2-governance.html

A: just had this problem, it was getting stuck at the point where it was trying to mount one of the two mounts we were setting up. we found that by commenting one out it worked.
our end solution to get both mounting was creating a new folder and moving all contents into it, deleting old folder and then renaming the new folder.


text:
Q: Prove that $\mathscr B$ is a basis for topology $\mathscr T$ on $\mathbb R$. Is $\mathscr T$ is a usual topology on $\mathbb R$? Let $A=\{\frac{1}{n}:n\in \mathbb N\}$ and $\mathscr{B}=\{(a,b):a<b\}\cup \{(a,b)\setminus A:a<b\}.$ Prove that $\mathscr B$ is a basis for topology $\mathscr T$ on $\mathbb R$. Is $\mathscr T$ is a usual topology on $\mathbb R$?
Obviously,
(1)$\bigcup_{a,b\in \mathbb R}(a,b)=\mathbb R$
 For the second condition of basis,
(2)Case 1:-
Let $x\in B_1,B_2\in \{(a,b):a<b\}$ , then obviously there exists $x\in B_3$ such that $B_3\subset B_1 \cap B_3$
Case2:-$x\in B_1\in \{(a,b):a<b\}$and $B_2 \in\{(a,b)\setminus A:a<b\}$ I am not able to prove existance of $B_3$ such that $B_3\subset B_1 \cap B_3$
Case 3 $B_1,B_2 \in\{(a,b)\setminus A:a<b\}$. How do I prove formally the existance of $B_3$?
to check whether the given basis generate usual topology or not?
 any open set can be generated by using $\{(a,b):a<b\}$.
Please check my answers.

A: The assertion "there exists $x\in B_3$ such that $B_3\subset B_1 \cap B_3$" doesn't make sense because no $B_3$ has been defined at this point. What you should prove is that for each $x\in B_1\cap B_2$, there exists some $B_3\in\mathcal{B}$ such that $x\in B_3$ and that $B_3\subset B_1\cap B_2$.
And $\mathcal B$ doesn't generate the usual topology, since $A^\complement\in\mathcal B$ and $A^\complement$ doesn't belong to the usual topology. The topology generated by $\mathcal B$ is strictly finer that the usual one.

A: The condition you have to check is

For all $B_1, B_2 \in \mathcal{B}$, and all $x \in B_1 \cap B_2$, there exists a $B_3 \in \mathcal{B}$ such that $x \in B_3 \subseteq B_1 \cap B_2$.

(A condition you sloppily reproduce, be more exact there!)
Now there are indeed cases to consider: suppose $B_1 = (a_1,b_1)$ and $B_2 = (a_2,b_2)$, so they are of "standard type". If we have $x \in B_1 \cap B_2$, then you can note that $B_1 \cap B_2 = (\max(a_1,a_2), \min(b_1,b_2))$ (the intersection is non-empty, so $\max(a_1,a_2) < \min(b_1,b_2)$ and we can use this intersection as our $B_3$ for all $x$ in the intersection.
You state "it's obvious" and go on. Your thoughts are probably along these lines: (but do make them explicit next time): $B_1$ and $B_2$ are standard open. So their intersection is standard open and the "standard type" open intervals already form a base for those, so the condition follows from open intervals being a base for the standard topology.
("existance" should be "existence")
If $B_1, B_2$ are of type two, an open interval minus $A$ (this case you skipped): You can use the observation above that the intersection of two open intervals is an interval or empty. So if non-empty, we can use $B_1 \cap B_2$ again for all points in it, as
$$((a,b) \setminus A) \cap ((c,d) \setminus A) = ((a,b) \cap (c,d)) \setminus A$$
If $B_1$ is of standard type $(a,b)$ and $B_2$ is of type two,  $B_2 = (c,d)\setminus A$ for some $c< d$, then note that if $x \in B_1 \cap B_2$, there are two subcases: a. $x \neq 0$, then $x \notin \overline{A}$ (closure in the standard topology, this holds as $\overline{A} = A \cup \{0\}$, which is standard closed. In that case we have $x \in (a,b) \cap (c,d) \cap (\mathbb{R}\setminus \overline{A})$ which is standard open (!) so there is some open interval (as these form a base for the standard topology!) $(e,f)$ with $$x \in (e,f) \subseteq (a,b) \cap (c,d) \cap (\mathbb{R}\setminus \overline{A}) \subseteq
B_1 \cap B_2$$ as required.
The other subcase is $x = 0$. Then $0 \in (a,b) \cap (c,d)$ which is an interval $I$ containing $0$ again, and then $x \in B_3:= I \setminus A \subseteq B_1 \cap B_2$ again.
So the condition checks out again.
Note that this topology could also have been defined by stating that
$\mathcal{S} = \{(a,b): a < b\} \cup \{\mathbb{R} \setminus A\}$ is a subbase for and then the finite intersections of members of $\mathcal{S}$ is exactly the collection $\mathcal{S}$, which is then a base by virtue of being a set of finite intersections from this family. If the set $\mathbb{R} \setminus A$ is not used in the intersection, we get open intervals, and if it is, we get an open interval minus $A$, i.e. type two.
It's clear that $A$ is not closed in the usual topology, but this topology is constructed by adding it as a new closed set, so it's strictly finer than the usual topology, as $\mathbb{R} \setminus A$ is open in it.

A: Let $\Bbb B_1=\{(a,b):a,b\in \Bbb R\}$ and $\Bbb B_2=\{\beta \setminus A: \beta \in \Bbb B_1\}$ and $\Bbb B=\Bbb B_1\cup \Bbb B_2.$
(I). The condition $$\forall b,b'\in \Bbb B\;\forall x\in b\cap b'\;\exists b''\in \Bbb B\;(x\in b''\subset b\cap b')$$ is satisfied IF $$\forall b,b'\in \Bbb B\;(b\cap b'\in \Bbb B)$$ is satisfied.
If  $b,b'  \in  \Bbb B$  let $b=c \setminus d$ and $b'= c'\setminus d'$ where $c,c'\in \Bbb B_1$ and each of $d,d'$ is either $\emptyset$ or $A.$ Observe that  $c\cap c'\in B_1$. And $d\cup d'\in \{\emptyset,A\}$. So $$b\cap b'=(c\cap c')\setminus (d\cup d')\in \{(c\cap c'),\; (c\cap c')\setminus A \}\subset \Bbb B.$$
(II). Let $T_{\Bbb B}$ be the topology generated by the base (basis) $\Bbb B.$ Then $A$ is closed with respect to $T_{\Bbb B}$ because $\Bbb R \setminus A $ is the union of  $$(-1,1)\setminus A$$ with $$\bigcup \{(n,n+1): 1\leq n\in \Bbb Z \lor -1\geq n\in \Bbb Z\}$$ so $\Bbb R \setminus A \in T_{\Bbb B}.$
But with respect to the "usual" topology on $\Bbb R$ the set $A$ is not closed.
Footnote. If $B$ is a family of subsets of a set $X$ then the conditions $\cup B=X$ and $\forall b,b'\in B\;(b\cap b'\in B)$ are sufficient for $B$ to be a base (basis) for a topology on $X.$

A: Let's look at Case 2. We let $x\in B_1\cap B_2$ be an arbitrary element of the intersection, where $B_1=(a,b)$ and $B_2=(c,d)\setminus A$. Note that since $x\in B_2$, we have that $x\not\in A$. Now consider the set $C=(max\{a,c\},min\{b,d\})\setminus A$. Because $a<x<b$, $c<x<d$, and $x\not\in A$, we can conclude that $x\in C$. It is easy to verify that $C\subset B_1\cap B_2$.
Case 3 is similar.
This topology is also introduced as "The K topology on $\mathbb{R}$" in Munkres Topology, and there are many examples using this topology in sections 12 through 19.


text:
Q: Getting a list of string values from this c# function: I have been trying to get my head around this but it hasn't been working:
I've gotten this function from http://fir3pho3nixx.blogspot.com/2011/01/recursion-cross-product-of-multiple.html where it returns a list but I can't seem to read the values within each object in the list.
Here is the function in question:
    private static List<object> GetCrossProduct(object[][] arrays)
    {
        var results = new List<object>();
        GetCrossProduct(results, arrays, 0, new object[arrays.Length]);
        return results;
    }

    private static void GetCrossProduct(ICollection<object> results, object[][] arrays, int depth, object[] current)
    {
        for (var i = 0; i < arrays[depth].Length; i++)
        {
            current[depth] = arrays[depth][i];
            if (depth < arrays.Length - 1)
                GetCrossProduct(results, arrays, depth + 1, current);
            else
                results.Add(current.ToList());
        }
    }

A: You are having problem because you are probably expecting a linear List, when it is actually a List of Lists.
To access elements within your result, you need to do something like this:
var resultingList = GetCrossProduct(blargh); // where blargh is the array you passed in
foreach (IList<object> innerList in resultingList)
{
    foreach (var listValue in innerList)
    {
        // listValues should be the individual strings, do whatever with them
        // e.g.
        Console.Out.WriteLine(listValue);
    }
}

The reason for this is because of the line:
results.Add(current.ToList());

Which creates a new list and adds it to the result list.


text:
Q: Show unit movable range within 1 turn? Is there any option to enable the display of unit movable range within 1 turn?
I watched one YouTube video and saw that it displayed on his game like this but somehow I cannot find this in the Game Options.

A: Hold right-click (movement button), IIRC.

A: In addition to holding down the right mouse button, the M key will toggle the single-move radius of a unit.
There's also a button on the unit command panel that looks like a bunch of hexes with an arrow overlaid, this will do the same thing.  (M is a shortcut for this command)
It's not shown in your screenshot, but pressing G will bring up the hex grid, which can be useful in determining how far apart things are.


text:
Q: jQuery UI Draggable-Droppable overflow:visible Sadly, I am unable to provide any JSFiddle for this issue, as I cant seem to reproduce it outside my project.
I have a container where there are some boxes, that can be arranged using drag and drop, by utilizing jQuery UI. The problem is, that the container is overflow:auto; but it needs to be overflow:visible;, but if I do that, jQuery UI malfunctions. When a box drag is initiated, it will immediatly jump up aproximately  400-500px.
This is how the draggable is created:
        $(".draggable").draggable({
            revert: 'invalid', // when not dropped, the item will revert back to its initial position
            containment: '#editContainer', // stick to demo-frame if present
            helper: 'original',
            cursor: 'move'
        });

Is this a bug with jQuery UI, or can this be fixed on my end?
I apologize for the lack of source code.


text:
Q: Build LLVM 16 (master) fail on libunwind I'm trying building LLVM master on Ubuntu 22.04. But there's an error of libunwind.
CMake Error at /home/hxf0223/tmp/llvm-project/libunwind/src/CMakeLists.txt:109 (message):
  Compiler doesn't support generation of unwind tables if exception support
  is disabled.  Building libunwind DSO with runtime dependency on C++ ABI
  library is not supported.

The build command is:
CC=clang CXX=clang++ cmake -GNinja -DCMAKE_BUILD_TYPE=Release -DLLVM_ENABLE_ASSERTIONS=ON  -DLLVM_ENABLE_PROJECTS="clang;clang-tools-extra;libclc;lld;lldb;mlir;polly;pstl" -DCOMPILER_RT_USE_BUILTINS_LIBRARY=ON -DLIBCXXABI_USE_COMPILER_RT=ON -DLIBCXXABI_USE_LLVM_UNWINDER=ON -DLIBCXX_USE_COMPILER_RT=ON -DLIBUNWIND_USE_COMPILER_RT=ON -DLLVM_ENABLE_EH=ON -DLLVM_ENABLE_RTTI=ON -DLLVM_ENABLE_RUNTIMES=all ../llvm

Does anyone have build success on the update master?
Thanks!

A: From libunwind/src/CMakeLists.txt:
if (LIBUNWIND_ENABLE_SHARED AND
    NOT (LIBUNWIND_SUPPORTS_FNO_EXCEPTIONS_FLAG AND
         LIBUNWIND_SUPPORTS_FUNWIND_TABLES_FLAG))
  message(FATAL_ERROR
          "Compiler doesn't support generation of unwind tables if exception "
          "support is disabled.  Building libunwind DSO with runtime dependency "
          "on C++ ABI library is not supported.")
endif()

It appears that the error appears when one (or both, I'm not an expert at this) of LIBUNWIND_SUPPORTS_FUNWIND_TABLES_FLAG or LIBUNWIND_SUPPORTS_FNO_EXCEPTIONS_FLAG is not set while LIBUNWIND_ENABLE_SHARED is enabled.
You can try setting them manually or use a different compiler.


text:
Q: fable documentation Pojo attribute Is there any documentation out there for what [<Pojo>] is supposed to do? I got the redux sample and figured it unwraps discriminated unions. The problem was that I have the action defined as a discriminated union but redux does not allow anything but a object literal to be passed as action so a discriminated union cannot be the action.
So the following type
[<Pojo>]
type TodoAction =
    | EditTodo of id:int * text:string
    | ClearCompleted

console.log(EditTodo(22,"Hello World"))
console.log(ClearCompleted)

compiles to:
console.log({
  type: "EditTodo",
  id: 22,
  text: "Hello World"
});
console.log({
  type: "ClearCompleted"
});

Is it a lucky "accident" that the object literal has a "type" property (you need this in redux).
Without Pojo it would be:
console.log(new TodoAction("EditTodo", [22, "Hello World"]));
console.log(new TodoAction("ClearCompleted", []));

That doesn't work if you try to store.dispatch that because an action can only be an object literal (that has a "type" property)
So trying to reverse engineer from a working example is fun but having a documentation that says how it's supposed to work is even more fun.
Is there such a thing?
Using grep in the root source directory got the the following file: ./src/fable/Fable.Core/Fable.Core.fs
with:
/// Compile a record as a JS object literals.
/// More info: http://fable.io/docs/interacting.html
type PojoAttribute() =
    inherit Attribute()

but docs interacting has no such thing as more information on what it does. I will try to play with it a little more and see if it's possible to use the value as a union or if it's already unwrapped.
If the creator/contributer of Fable happens to read this; thank you, this is a great idea and I'd love to contribute if needed.
So the question is: where is the documentation if there is no such thing then how do we create it? I'd love to write some but would only be guessing as to how most of the fable compiler works.
If you get the following error:

error FSHARP: The type 'Pojo' is not defined

Please make sure you import Fable.core.dll and open it:
#r "./node_modules/fable-core/Fable.Core.dll"
open Fable.Core

A: One of the best guides I recently discovered is F# Interop with Javascript in Fable: The Complete Guide by Zaid Ajaj.
Incidentally, the attribute, [< Pojo >], is applicable to F# records and ensures they compile to javascript object literals (Plain Old Javascript Object). Apparently, a translation to such an object is not the default behaviour for records, which seems weird.


text:
Q: Add zeroDateTimeBehavior variable to the Datasource without URL in jetty.xml I'm trying to connect to multiple data sources by a grails application. What I tried worked in a development environment correctly. Initially there was a timestamp error which got resolved with 'zeroDateTimeBehavior=convertToNull' adding to a url. But now in production environment, I don't understand how to add this variable.
My development environment code is,
dataSource_test {
            driverClassName = "com.mysql.jdbc.Driver"
            dialect = "org.hibernate.dialect.MySQL5InnoDBDialect"
            dbCreate = "validate" // one of 'create', 'create-drop', 'update', 'validate', ''
            url = "jdbc:mysql://localhost/test?useUnicode=yes&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull"
            username = "root"
            password = "root"
        }

And my production environment code is
dataSource_test{
            dbCreate = "validate"
            jndiName = "java:comp/env/jdbc/test"
        }

I've also added this datasource to jetty.xml as following,
 <New id="DS" class="org.eclipse.jetty.plus.jndi.Resource">
    <Arg><Ref refid="Server"/></Arg>
    <Arg>jdbc/test</Arg>
    <Arg>
      <New class="com.zaxxer.hikari.HikariDataSource">
        <Arg>
          <New class="com.zaxxer.hikari.HikariConfig">
        <Set name="minimumIdle"><Property name="db.min.conn" /></Set>
            <Set name="maximumPoolSize"><Property name="db.max.conn" /></Set>
            <Set name="dataSourceClassName">com.mysql.jdbc.jdbc2.optional.MysqlDataSource</Set>
            <Set name="username"><Property name="db.user" /></Set>
            <Set name="password"><Property name="db.pass" /></Set>
            <Call name="addDataSourceProperty">
              <Arg>url</Arg>
              <Arg>jdbc:mysql://<Property name="db.host" />/test</Arg>
            </Call>
            <Set name="leakDetectionThreshold">30000</Set>
          </New>
        </Arg>
      </New>
    </Arg>
  </New>

I don't understand where should I put "zeroDateTimeBehavior=convertToNull" ?

A: Its just a property on the mysql side of the DataSource.
Just set it (like you do the url)
This should work (like any other property for the mysql datasource)
<Call name="addDataSourceProperty">
  <Arg>zeroDateTimeBehavior</Arg>
  <Arg>convertToNull</Arg>
</Call>


text:
Q: Set mode to 777 when creating folders using File.mkdirs in Java I'm using the following Java code to create a file inside several folders:
Path pathOut = Paths.get("./", year, month, day, processId, "METADATA.txt");

File fileOut = pathOut.toFile();

boolean f = fileOut.getParentFile().mkdirs();

It works perfectly, but I'd need to set the permissions for each subfolder to '777'. Is it possible using mkdirs method or do I need to change the logic and use another approach?
Thanks!

A: Permission 777 is the same as rwxrwxrwx. Thus, you can set the required permission as follows:
Files.setPosixFilePermissions(path, PosixFilePermissions.fromString("rwxrwxrwx"))


text:
Q: Get the spreadsheet key that is in the URL. Not ss.getId() How to get the spreadsheet ID that is in the URL.
I know about using SpreadsheetApp.getActiveSpreadsheet().getId() and SpreadsheetApp.getActiveSpreadsheet().getUrl()
But getId()/getUrl()/getKey() now fails with Google-Drive-SDK. I am no longer able to
use this ID to open files with the Drive-SDK. It was working about 1 week ago, but the Drive-SDK now fails to open the file.
A workaround is to use the ID that is in the URL. The id after key=
https://docs.google.com/spreadsheet/ccc?key=0AkGlO9jJLGO8dHJrSE0wTEF2VXRSdGRlNVQaaVRad0E
But I want an automated way to get it, not
a manual process. As the spreadsheet is being created using a template, so I don't have a way to know the ID. Thoughts, is there a way to get it?
Note 1: stackoverflow.com/questions/18583885/ says Google Drive SDK issues should be posted to stackoverflow
Note 2: getUrl() and getKey() contains the same ID as getId() not the key in the URL. So it looks like access to the key has been removed, so am not holding out much hope.
Edit
The drive code, is Java rather than google-apps-script. version 1.15.0-rc
    Drive driveService = new Drive.Builder(TRANSPORT, JSON_FACTORY, credential).setApplicationName("CellMaster.com.au").build();
    File file = driveService.files().get(this.spreadsheetKey).execute();

I think it broke sometime in the last week or so. It fails with the execute(), it produces a 404 error. It gives the error when I use with the short spreadsheetKey that is produced by google apps script. But it still works fine when I use the browser URL key value.

A: You don't show the code that is not working for you, but the following works ok for me
function myFunction() {
// create a new spreadsheet workbook
var ss = SpreadsheetApp.create("Test");
var id = ss.getId();
Logger.log(id)
// get the ss file through Drive using spreadsheet id
var file = DriveApp.getFileById(id);
var driveid = file.getId();
Logger.log(driveid)
// open the spreadsheet using id of file
var ssfromdrive = SpreadsheetApp.openById(driveid);
Logger.log(ssfromdrive.getName())
 }

A: As David pointed out, the id of the same file is different in the Spreadsheet app and in the Drive app.
Getting the spreadsheet file from the Drive app, using the Spreadsheet id, and then getting the id of the Drive file, following the example, will solve your problem.


text:
Q: get the zdata with event from a orthoviewer of medical image I want get the zdata, from navigation toolbar, when I load a .nii file. I want do that with the event def _onclick(event):
import matplotlib
matplotlib.use('TkAgg')
from tkinter import filedialog
from tkinter import *
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from nibabel.loadsave import read_img_data
from nibabel.loadsave import load as load_nii
from viewers import OrthoSlicer3D
from matplotlib.figure import Figure
import numpy as np

import sys
if sys.version_info[0] < 3:
    import Tkinter as Tk
else:
    import tkinter as Tk

root = Tk.Tk()
root.wm_title("Orthoslicer3D for brain segmentation")

f = Figure()

sagital = f.add_subplot(221)
sagital.set_position([0,0,0.5,0.5])
sagital.set_axis_off()

coronal = f.add_subplot(222)
coronal.set_axis_off()
coronal.set_position([0,0.5,0.5,0.5])

axial = f.add_subplot(223)
axial.set_position([0.5,0.5,0.5,0.5])
axial.set_axis_off()

axes = (sagital, coronal, axial)

# a tk.DrawingArea
canvas = FigureCanvasTkAgg(f, master=root)
canvas.get_tk_widget().pack(side=Tk.RIGHT, fill=Tk.BOTH, expand=1)

toolbar = NavigationToolbar2TkAgg(canvas, root)
toolbar.update()
canvas._tkcanvas.pack(side=Tk.RIGHT, fill=Tk.BOTH, expand=0)

def _load():
    data = filedialog.askopenfilename(initialdir = "/", title = "Select file", filetypes = (("nii files","*.nii"),("gz files", "*.gz"),("all files","*.*")))
    data_load = load_nii(data)
    data_read = read_img_data(data_load)
    data_read = np.asanyarray(data_read)
    OrthoSlicer3D(data_read, axes=axes).show()

coords = []

def _onclick(event):
    coords.append((event.xdata, event.ydata, event.zdata))
    return coords

canvas.mpl_connect('button_press_event', _onclick)

buttonLoad = Tk.Button(master=root, text='Load', command=_load)
buttonLoad.pack(side=Tk.LEFT, expand = 1)

Tk.mainloop()

But the traceback is:
Traceback (most recent call last):
    File "C:\Users\migue\Documents\IM\TFG\venv\lib\site-packages\matplotlib\cbook\__init__.py", line 388, in process
        proxy(*args, **kwargs)
    File "C:\Users\migue\Documents\IM\TFG\venv\lib\site-packages\matplotlib\cbook\__init__.py", line 228, in __call__
        return mtd(*args, **kwargs)
    File "C:/Users/migue/Documents/IM/TFG/pruebsd.py", line 58, in _onclick
        coords.append((event.xdata, event.ydata, event.zdata))
    AttributeError: 'MouseEvent' object has no attribute 'zdata'


text:
Q: fatal error: unexpectedly found nil while unwrapping an Optional value in didDeselectRowAt I am absolutely new to IOS development and have got stuck on this one. I am trying a very simple thing here, I want that when I select a cell in my TableView it's background colour gets changed to grey and when I select another cell the background colour of the previous grey cell should be restored back to the default colour.
To achieve this I am using the following code:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
  let currentCell = tableView.cellForRow(at: indexPath) as! RoundTableViewCell
  currentCell.contentView.backgroundColor = Util.hexStringToUIColor(hex: "#d3d3d3")
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath)
{
  let currentCell = tableView.cellForRow(at: indexPath) as? RoundTableViewCell  // Error
  currentCell.contentView.backgroundColor = Util.hexStringToUIColor(hex: "#ffffff")
}

The above code works just fine but it crashes when I try to tap on a new cell while the previous selected cell is not visible in the table view as it is scrolled away. I can't understand what's happening here.
Edit
cellForRowAt :
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
   let cell: RoundTableViewCell = (tableView.dequeueReusableCell(withIdentifier: "cell")! as? RoundTableViewCell)!
   cell.contentView.backgroundColor = Util.hexStringToUIColor(hex: "#ffff
   return cell
}

A: You need to check if cell available or not
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath)
{
   if let currentCell = tableView.cellForRow(at: indexPath) as? RoundTableViewCell  {
         currentCell.contentView.backgroundColor = Util.hexStringToUIColor(hex: "#ffffff")
     }
}

A: public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    ....
    ....
    if cell.isSelected == true {
       currentCell.contentView.backgroundColor = Util.hexStringToUIColor(hex: "#d3d3d3")
    }
    else {
       currentCell.contentView.backgroundColor = Util.hexStringToUIColor(hex: "#ffffff")
    }
    ....
    ....
}

If you want multiple cell selection.
table.allowsMultipleSelection = true

App crash because when cell disappear from screen its dealloc from memory so you get nil value. so try this
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    if let currentCell = tableView.cellForRow(at: indexPath) as? RoundTableViewCell  {
         currentCell.contentView.backgroundColor = Util.hexStringToUIColor(hex: "#d3d3d3")
     }
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath)
{
   if let currentCell = tableView.cellForRow(at: indexPath) as? RoundTableViewCell  {
         currentCell.contentView.backgroundColor = Util.hexStringToUIColor(hex: "#ffffff")
     }
}

A: Use following code to get expected result.
 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell

        cell.selectedBackgroundView = UIImageView()
        cell.backgroundView=UIImageView()

        let selectedBackground : UIImageView = cell.selectedBackgroundView as! UIImageView
        selectedBackground.image = UIImage.init(named:"selected.png");

        let backGround : UIImageView = cell.backgroundView as! UIImageView
        backGround.image = UIImage.init(named:"defaultimage.png");

        return cell

    }


text:
Q: How to join two dataframes on 1 column in Python Here are two dataframes :
df1 = pd.DataFrame({'product_id': [65, 19, 7, 49, 66, 100],
                  'a': [4, 43, 16, 86, 90, 867],
                  'web_id': [6, 4, 69, 54, '', '']})

df2 = pd.DataFrame({'web_id': [4, 54, '', ''],
                  'b': [94, 36, 90, 5],
                  'c': [67, 98, 555, '']})

The goal is to join df1 and df2 on 'web_id' to get this result :
df3 = pd.DataFrame({'product_id': [65, 19, 7, 49, 66, 100],
                      'a': [4, 43, 16, 86, 90, 867],
                      'web_id': [6, 4, 69, 54, '', ''],
                      'b': [94, 36, 90, 5, '', ''],
                      'c': [67, 98, 555, '', '', '')})

Maybe you can help.

A: Let's try concat on axis=1, but first drop the shared column and reindex to scale df2 with '' as the fill_value:
df3 = pd.concat([
    df1,
    df2.drop('web_id', axis=1).reindex(df1.index, fill_value='')
], axis=1)

df3:
   product_id    a web_id   b    c
0          65    4      6  94   67
1          19   43      4  36   98
2           7   16     69  90  555
3          49   86     54   5
4          66   90
5         100  867

The alternative is to concat then fillna however the dtypes may convert with the temporary introduction of NaN:
df3 = pd.concat([df1, df2.drop('web_id', axis=1)], axis=1).fillna('')

df3:
Notice column b
   product_id    a web_id     b    c
0          65    4      6  94.0   67
1          19   43      4  36.0   98
2           7   16     69  90.0  555
3          49   86     54   5.0
4          66   90
5         100  867


text:
Q: Parametrization of a rotated ellipse I need to parametrize an ellipse centered at the origian in cartesian coordinates given by
$a x^2 + b xy + c y^2 = 1$
Now I dug up from old notes that this can be brought into normal form through a rotation $\tan 2 \theta = \frac {b}{a-c}$, which eliminates the $xy$ term in rotated coordinates $x' = x \cos \theta + y \sin \theta, y = - x \sin \theta + y \cos \theta$ and we get
$\left( \frac{a + c + \sqrt{(a-c)^2+b^2}}{2}\right) x'^2 + \left( \frac{a + c - \sqrt{(a-c)^2+b^2}}{2}\right)y'^2 = 1$
which can be expressed as a normal equation $\frac{x'^2}{\alpha^2} + \frac{y'^2}{\beta^2} = 1$ if $4ac > b^2$ and both of the coefficients above have positive signs (which we may assume). This is then parametrized in the standard way by
$x' = \alpha \cos t, y' = \beta \sin t$ for $0\le t < 2\pi$
in the rotated coordinates and by $x = x' \cos \theta - y' sin \theta, y = x' sin \theta + y' \cos \theta$ in the original coordinates. Now while the above works, it's been pointed out to me that I am making things more complicated than necessary. Are there better ways of achieving this? I was thinking of diagonalizing the matrix
$(x, y)' \begin{pmatrix} a & b/2 \\ b/2 & c \end{pmatrix} (x,y)=1$
but I dont think that would make things easier. Is there a direct parametrization of the ellipse in terms of $a,b,c$?

A: Rewriting equation is quicker : $4a^2x^2 + 4abxy + 4acy^2 = 4a$ (multiplying by $4a$) ; $(2ax + by)^2 - b^2y^2 + 4acy^2 = 4a$ (it is a trick removing the $xy$ term) ; $(2ax + by)^2 + (4ac - b^2)y^2 = 4a$,  then you can compare with equation $X^2/p + Y^2/q = 1$ of a conic (ellipse or hyperbola) for which you know a parametrization.


text:
Q: How to extract analytics from Adobe at URL filtered by channel using R I'm trying to extract URL level data in a filtered channel (organic search) using the Adobe Analytics API and it's failing. How do I make it work?
I've tried using the RSiteCatalyst in R using the following code:
  QueueDataWarehouse(my_rsid,
                     date.from = "2019-06-01",
                     date.to = "2019-06-30",
                     segment.id = "s300007365_5b366bb3f30aae698e8b0488",
                     elements = c("entrypage"),
                     metrics = c("uniquevisitors","averagetimespentonpage", "event123", "event38"),
                     enqueueOnly = F)

I expected a dataframe as defined in the code above and instead I get a dataframe that is NULL.
Please help.
PS While I'm here, is there another R package to work with the newer version of the API being 2.0?


text:
Q: Read JSON Data from URL (JavaScript) Attempt 2 to get my question right (please bear with me - I'm new).
I am trying to read data from a URL
http://test.fhir.org/r3/Patient?family=smith&given=peggy&_format=json
and want to use Javascript to reformat it to the screen as table but
(1) I can't get it to read and
(2) I can't format it to a table as in json2table.com
Can anyone help?  Here is the code I am trying.
    <!DOCTYPE html>

      <meta http-equiv="content-type" content="text/html; charset=UTF-8">
      <title>Playing with JSON</title>
      <meta name="viewport" content="width=device-width, initial-scale=1">

      <link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

In Development

            <button id="get-repos">JSON download trial!!</button>

A: In this example you are assuming jQuery is present by having bootstrap.js loaded. This is not the case and you either need to load jQuery before bootstrap OR move your script to the bottom of the page (right before the body is closed) and remove this $(window).load(function(){}).
<!DOCTYPE html>

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Playing with JSON</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

In Development

      <button id="get-repos">JSON download trial!!</button>

If you decide to use jQuery, your code can be simplified a lot:
<!DOCTYPE html>

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Playing with JSON</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

In Development

      <button id="get-repos">JSON download trial!!</button>


text:
Q: Android how to enable/disable auto sync programmatically I need to know how to toggle auto sync on and off programmatically.

A: I think what you want is the following:
ContentResolver.setSyncAutomatically(account, authority, true/false);

A: Code for Sync Accounts Programmatically:
Sync once:
public static void syncAllAccounts(Context contextAct) throws Exception {
    AccountManager manager = AccountManager.get(contextAct);
    Account[] accounts = manager.getAccountsByType("com.google");
    String accountName = "";
    String accountType = "";
    for (Account account : accounts) {
        accountName = account.name;
        accountType = account.type;
        break;
    }

    Account a = new Account(accountName, accountType);
    ContentResolver.requestSync(a, "com.android.calendar", new Bundle());
}

Sync on time interval automatically:
public static void syncAllAccountsPeriodically(Context contextAct, long seconds) throws Exception {
    AccountManager manager = AccountManager.get(contextAct);
    Account[] accounts = manager.getAccountsByType("com.google");
    String accountName = "";
    String accountType = "";
    for (Account account : accounts) {
        accountName = account.name;
        accountType = account.type;
        break;
    }

    Account a = new Account(accountName, accountType);
    ContentResolver.addPeriodicSync(a, "com.android.calendar", new Bundle(), seconds*1000);
}

If you want to sync accounts once, call first method and if you want to sync on some time of interval you have to call second method and pass seconds (Like 10 Seconds) as arguments in it.
Done

A: I think you are looking for
ContentResolver.setMasterSyncAutomatically(<boolean>);

What docs says:

Sets the master auto-sync setting that applies to all the providers
  and accounts. If this is false then the per-provider auto-sync setting
  is ignored.
This method requires the caller to hold the permission
  WRITE_SYNC_SETTINGS.

So don't forget to add permission into manifest.xml:
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />

This should disable / enable all the syncs.

@Sajmon: I updated this i think very useful answer (i'm using this in my personal project).

A: Ben is correct.
You need to use
ContentResolver.setSyncAutomatically(account, authority, true/false);

you will also need to add permission "WRITE_SYNC_SETTINGS"
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS"/>


text:
Q: How to make repeading 3D ball on Y coordinate in processing? I was making an animation on processing. Then, I confused about on a problem. I prepare a simple code for you. Also, I think the question can helpfull for the beginners.
PShape ball;
float ballSpeed = random(0.5, 1);
float ballSize = random(5, 10);
float x = 200, y = 300, z = 0;

void setup() {
  size(400, 400, P3D);
  noStroke();         // That's for "not see details on sphere"
  ball = createShape(SPHERE, ballSize);
}

void draw() {
  background(0);
  translate(x, y, z); // rotate the ball
  println(y);         // checking the y coordinates
  fill(255);
  shape(ball);
  y -= ballSpeed;     // the ball can go to top
}

So, I want to make a condition for if the ball reach the 100, the ball should return or start its first position and then again it should go to 100 again. I tried many if conditions but couldn't figure out it.
If you help me I will be happy.
Thanks.

A: Just invert ballSpeed, if the y coordinate of the ball is less or equal 100 respectively greater or equal 300:
y -= ballSpeed;
if (y <= 100 || y >= 300) {
    ballSpeed = -ballSpeed;
}

Note the ball is moving upwards. When the ball reaches 100, ballSpeed is inverted, the ball changes direction and moves downwards. If the ball reaches is original position (300), ballSpeed is inverted again and the ball changes the direction again.

If you want that the ball restarts at 300, when it reaches a y coordinate of 100, then it is sufficient to set y = 300:
y -= ballSpeed;
if (y <= 100) {
    y = 300;
}