text:
Q: How can I generate grid-based Fractals? Please let me know if there's a better site to ask a question like this.
I play a little indie game called Dwarf Fortress and a major part of the game involves building the titular Fortress for your Dwarves. Some of these tasks, however, quickly become so monotonous as to become tedious. Specifically, bedrooms. I find a great deal of the boredom in carving another dozen bedrooms out of the bedrock can be eliminated if I'm working with a pattern.
The ever-useful Dwarf Fortress Wiki contains examples of "Fractal" living arrangements that are especially aesthetically pleasing:

However, I'm interested in moving beyond these two pictures alone, seeking to generate my own Fractals and from them develop new bedroom designs!
I've searched around on the web, and though I've found several Fractal generators (in one form or another), none of the generators produce output that is readily adaptable to Dwarf Fortress' grid-based gameplay, filled with curves, and other hard-to-reproduce aspects.
I was hoping that there was some way to generate fractals that conform to a standard grid like the shapes outlined above, or otherwise limit the resultant shapes to those with 90* angles. Is there a mathematical way to create (or limit) a fractal to such a 2-d grid?

A: You can create grid based fractals by recursive replication a template density matrix. The following figure (from Ref. 1) illustrates the first recursion of such a generation procedure.
At each recursion, the output grid replicates itself multiplicatively over each element of the template matrix. Notice that this example produces a multifractal because not all non-zero elements are equal. Hence as you continue replicating you will create points with high mass accumulation. Whereas, if all non-zero elements would be equal there would be no variation and you would have monofractal.
Here is an example of a grid I created with the following template matrix. (I used my own Generic Fractal Generator, which you can find here).
\begin{bmatrix}1 & 1 & 0 & 1 & 1 \\0 & 1 & 0 & 1 & 0 \\0 & 0 & 1 & 0 & 0\\0 & 0 & 1 & 0 & 0\\1 & 1 & 0 & 1 & 1   \end{bmatrix}

References

*

*Kamer, Y., G. Ouillon, and D. Sornette (2013), Barycentric fixed-mass method for multifractal analysis, Phys. Rev. E, 88(2), 022922.


text:
Q: iReport pie chart hide month with 0 value Can someone help me on how to hide the 0 value in piechart in ireport? As u can see, only Nov and Dec have data, however other months dont have.
I'm using ireport 5.6

redpajama_set_name: RedPajamaStackExchange


text:
Q: Usage of conjunction 'and'
Where it becomes murkier is when using behavioural science and data
strays into manipulation.

In this sentence, a form of two verbs on both sides of 'and' in when claused are different.
A former is a -ing form(straying) and a latter is a Present tense verb (strays).
Could someone tell me how could it be possible grammatically, please?

A: Here, the phrase "using behavioural science and data" is what strays.  The word "using" here is a gerund: a form derived from a verb, but functions as a noun.


text:
Q: Typescript: Generic type that extends a generic type on another class Example
class BaseOptions {
    a: 1;
}

class OptionsA extends BaseOptions {
    b: 2;
}

class OptionsB extends BaseOptions {
    c: 3;
}

class Child<TOptions extends BaseOptions> {
    options: TOptions;
}

// Parent must use a child that supports TOptions
class Parent<TOptions extends BaseOptions, TChild extends Child<TOptions>> { }

// Supports OptionsA
class StrictChild extends Child<OptionsA> { }
// Supports OptionsA and OptionsB
class FlexibleChild extends Child<OptionsA | OptionsB> {
    doSomething() {
        if (this.options instanceof OptionsA) {
            const test1 = this.options.b;
        }
        // This should fail because no instanceof check
        const test2 = this.options.c;
    }
}

// Expected to fail because StrictChild can't have OptionsB
const parentA = new Parent<OptionsB, StrictChild>();
// Expected to pass because FlexibleChild can have OptionsA or OptionsB
// but fails because "OptionsA" is not assignable to "OptionsA | OptionsB"
const parentB = new Parent<OptionsB, FlexibleChild>();

I think the problem is
class Parent<TOptions extends BaseOptions, TChild extends Child<TOptions>> { }

specifically Child<TOptions> because I think it needs to be something like Child<TOptions extends Child<T>> but I have no idea how to do that.
Typescript playground

A: I think I have it working so long as I set a default generic on Child so that I can use TChild['options']
class Child<TOptions extends BaseOptions = BaseOptions> {
    options: TOptions;
}

// Parent must use a child that supports TOptions
class Parent<TOptions extends TChild['options'], TChild extends Child> { }

Typescript Playground
Edit
Alternatively you can just do
class Parent<TOptions extends TChild['options'], TChild extends Child<BaseOptions>> { }

A: You are looking for intersection types, not union types!
// Supports OptionsA and OptionsB
class FlexibleChild extends Child<OptionsA & OptionsB> { }

Now this is a perfectly valid statement:
const parentB = new Parent<OptionsB, FlexibleChild>();

Reference: https://www.typescriptlang.org/docs/handbook/advanced-types.html

An intersection type combines multiple types into one. This allows you to add together existing types to get a single type that has all the features you need. For example, Person & Serializable & Loggable is a Person and Serializable and Loggable. That means an object of this type will have all members of all three types.


text:
Q: Unescape unicode characters using PHP I am using an API which encodes some part of the content using JavaScript. That content is visible in the browser, but while I access it using curl in PHP I get plain JavaScript code as there is no JS engine on server. I would like to decode/unescape Unicode characters in PHP, as JavaScript does. Is that possible?
Please find a snippet of plain JavaScript I get as a response below:

eval(unescape("document.write('%u0039%u0032%u0039%u0032%u0034')"));

The snippet code should return 92924

A: Ok, I found a solution to that problem.
I am now parsing out the content string and then use json_decode function to unescape Unicode characters, but first %u has to be replaced with \u. Here is my code:
$string = "%u0039%u0032%u0039%u0032%u0034";
$unescaped = str_replace("%u","\u", $string);
echo json_decode('"'.$unescaped .'"');

This code would output: 92924


text:
Q: Portable way to make a thread sleep for a certain time or until woken up In my project I spawn a worker thread which deals with an information source. It needs to poll a source (to which it is subscribed) and, whenever needed, change the subscription (i.e. telling the source that the filter criteria for the information it needs have changed).
Polling the source happens at regular intervals, in the minutes range. Changes to the subscription need to be triggered immediately when the main thread identifies the condition for doing so. However, since the operation can be lengthy, it needs to run on the worker thread.
So the worker thread looks like this (in pseudo code—real code is in C):
while(true) {
    acquireWriteLock();
    if (subscriptionChangeNeeded) {
        changeSubscription();
        subscriptionChangeNeeded = false;
    }
    releaseWriteLock();
    pollSource();
    sleep(pollInterval);
}

Now, if the main thread sets subscriptionChangeNeeded right after the worker thread has completed one run of the loop and gone to sleep, the subscription change is going to be delayed by almost the duration of pollInterval.
Therefore, I need a way to wake the thread prematurely from its sleep—or, rather than tell it "sleep for X", "sleep until I wake you up, but no longer than X".
I do not need to explicitly tell the thread why it has come out of sleep—it can infer that from subscriptionChangeNeeded. Polling prematurely after changing the subscription is a desirable side effect.
Setting subscriptionChangeNeeded happens at a single location, hence I can easily incorporate a "wake up the worker thread" operation there.
Challenge: the code needs to run on Unix-like OSes as well as Windows. It solves that by implementing a thread abstraction wrapper around the respective APIs.
I am aware both platforms (pthread and Windows) support condition variables, but implementations vary somewhat. Among others, Windows protects the critical section with a critical section object, whereas pthread uses a mutex. Also, older Windows platforms (up to XP/2003) do not support condition variables at all. Finally, condition variables are more powerful than what I need—all I really need is a way to send a thread to sleep and allow it to be woken up by another thread.
What other constructs do the two platforms offer to acomplish that?

A: After some research, it seems events on WinAPI are closest to what I am trying to accomplish, and they have been around since at least Windows XP (I believe even earlier versions had it). On POSIX, the closest match really are conditional variables, though the mutex is not really necessary.
Since the project implements its own thread abstraction wrapper, this gives us some extra freedom.
We'll introduce a data type event. This is an opaque data structure. On Windows, this corresponds to an event (created as an auto-reset event); on POSIX, this is a struct holding a condition and a mutex.
When a thread goes to sleep, the POSIX implementation locks the mutex, calls pthread_cond_timedwait and unlocks the mutex as soon as it continues. The Windows implementation just calls WaitForSingleObject.
To wake up the sleeping thread, the POSIX implementation locks the mutex, calls pthread_cond_signal and unlocks the mutex again. The Windows implementation calls SetEvent.
On Windows, events can be auto-reset or not. An auto-reset event will be reset as soon as the first waiting thread is woken up (so it will never wake up more than one thread), but will remain set if that thread happens to be running at the time the event is signaled. Other events will remain in signaled state until explicitly reset, thus they can wake up any number of threads or even prevent them from going to sleep in the first place.
On POSIX, a condition can be signaled (waking up one waiting thread) or broadcast (waking up all waiting threads). As I understand it, it is reset after it fires, even if no thread got woken up.
Thus, as long as we never have more than one thread waiting on the same event, auto-reset events on Windows behave much like pthread_cond_signal on POSIX. The only difference is that we need to reset the event after handling it. Our thread abstraction wrapper needs to provide a function for that, which calls ResetEvent on Windows and is a no-op on POSIX.
Unlike conditions, this construct does not provide a mutex to provide synchronized access. Therefore, if the waiting and the signaling thread access a shared data structure, they must implement their own mechanism to synchronize access, e.g. using a mutex or lock.

A: You can use pthread_cond_wait() to wait for a signal from the main thread that the condition was met and the work can resume (ex. wait for the subscriptionChangeNeeded to change). This will remove the need to use sleep, however once the thread is suspended on this call, the only way to resume it is to call the pthread_cond_signal().
If your worker thread's loop has other tasks to do and you depend on periodical wake-ups,
you can use the pthread_cond_timedwait() to wait for the subscriptionChangeNeeded to change; or for a timeout to be reached; whatever happens first.
The main thread will have a task to identify the change in the condition and once it has identified that there is need for the update, main thread will call pthread_cond_signal() to inform the writer thread that he needs to wakeup. If the signal is not received in the time specified as a timeout, the thread will resume (wake up), even if the condition was met, so this is similar to sleep
Regardless on which one occurs first (the time-out or the condition change), the thread will be resumed and he can perform the changeSubscription();.
You can check more details and examples here
This are POSIX functions defined in pthread.h


text:
Q: Feeding SQS Queues available in two different AWS Accounts For putting messages to SQS Queues and getting a connection, we need to have a key for the account/user.
I want to feed messages to two queues which are available in two different AWS Accounts. How can I achieve that? As far as my understanding is, we can setup only one access/key credentials hence we cannot talk to two queues available in two different AWS Accounts.
Any help would be appreciated. Thanks!

A: You can use credentials from one account ("Account A") to make API calls to an Amazon SQS queue in a different account ("Account B").
Simply add a policy to the SQS queue in the target account (Account B). Here is a sample policy from the Using Identity-Based Policies (IAM) Policies for Amazon SQS documentation:

The following example policy grants AWS account number 111122223333 the SendMessage permission for the queue named 444455556666/queue1 in the US East (Ohio) region.

{
  "Version": "2012-10-17",
  "Id": "Queue1_Policy_UUID",
  "Statement": [
    {
      "Sid":"Queue1_SendMessage",
      "Effect": "Allow",
      "Principal": {
        "AWS": "111122223333"
      },
      "Action": "sqs:SendMessage",
      "Resource": "arn:aws:sqs:us-east-2:444455556666:queue1"
    }
  ]
}


text:
Q: Pass page scope attributes to a JSP using pagecontext.include for use in JSTL? We're using this JSP template solution almost verbatim at work:
http://java.sun.com/developer/technicalArticles/javaserverpages/jsp_templates/
When it gets JSP pages to be included, it uses pageContext.include, which leaves us with one problem, and that is that we have a lot of scriplet code that gets initialized in the JSP itself (tag soup). My thought was to modify the template tag with an additional attribute that is a package path reference to a class with an init or execute method. That execute would get called first, and would add page context attributes before including the JSP. We would then use JSTL to access those attributes. However, I was told this wouldn't work because of how pageContext.include works, and the inability to pass through attributes scoped to the page. Is that true, and are there workarounds? I'm so-so on knowing all my scoping rules.

A: Correct, the problem is that the PageContext is literally that, a Page Context. When you run the include, that resource (assuming it's a JSP) get's its own PageContext, and that is lost upon return.
JSP has 4 scopes: Application, Session, Request, and Page. Each of those has its own lifecycle, which should be self explanatory.
The use of the Request scope here is the right idea.
If you look at the template code that you linked to, that's exactly what the Insert tag is doing. In this case, it's putting Hashtables on to a Stack that is maintained in the Request.
Then it uses the "put" and "get" tags to put/get items on and off that current "stack".
A simple thing that you can do is before the PageContext.include, invoke your "execute" method as appropriate. Have that method simply return a Map of name/value pairs. Then you can take that Map and populate the existing (or soon to be existing) Hashtable on the Stack.
Basically your Init class is logic that's similar to calling a lot of the "put" tags.
Other than that your template tags work the same.
Or you can merge the results straight in to the Request, for use by the JSTL. Or you can keep the "stack" nature, pushing your own "context" in to the Request.

A: You can pass an attribute scoped to the request:
<c:set var="myAttribute" value="myValue" scope="request" />

or
<% request.setAttribute("myAttribute", "myValue"); %>

And then on your included page:
<c:out value="${myAttribute}" />


text:
Q: AngularJs save user data into session after authentication I'm new to AngularJS, and now I'm trying to build my first system with authentication. Everything works, except, when a user refreshes the page, all the user info is gone...
I followed this tutorial:
http://www.sitepoint.com/implementing-authentication-angular-applications/
Now this is how I tend to make sure the user data stays where its supposed to be:
When a user logs in, my API returns his/hers details in JSON, which then is dropped into both a $rootScope variable for use in the site, and also in a session. Next to that, I have a variable in the rootscope that returns true when signed in, and false when not, like this:
$rootScope.loggedin = true;
$rootScope.user = data;
$window.sessionStorage["info"] = data;
// console.log($window.sessionStorage["info"]);

This all happens in the Authentication factory.
Then when a user refreshes, and that same factory is ran once again, the following function will start to work:
function init() {
    if ($window.sessionStorage["info"]) {
        $rootScope.loggedin = true;
        $rootScope.user = $window.sessionStorage["info"];
        info = $window.sessionStorage["info"];
    }
}
init();

(I think this will work because that article and various other sources on the web said so.)
Then in my HTML, I use the loggedin variable to determine if a user is logged in:

    Log in
    Registreer

            {{user.username}}

Some log-in only stuff

Now all of this works nicely when I log myself in, but when I refresh the page, it detects that I'm logged in, but my name just stays blank, since I guess that $rootScope.user is undefined.
Why is this, and how do I fix it?
Thanks.

A: I recommend you switch to something like ngStorage instead: https://github.com/gsklee/ngStorage
$window.sessionStorage will not persist across new tabs or windows, and depending on your browser, may not even across a page refresh.   So at least, you should be using localStorage (which doesn't have to be called as as a method of $window/window unless you expect it to be overrided in your scope, btw).
Also, typically, getter and setter methods on sessionStorage  are used (getItem and setItem): https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage - you may not be able to use that object["key"] syntax to achieve that desired effect, although I believe they can.

A: I wrote a much cleaner object to store data in Local Storage.
  var LocalStorageManager = {
    setValue: function(key, value) {
        window.localStorage.setItem(key, JSON.stringify(value));
    },
    getValue: function(key) {
        try {
            return JSON.parse(window.localStorage.getItem(key));
        } catch (e) {

        }
    }
};

To save data to local storage:
LocalStorageManager.setValue("key",data);

To retrieve that data:
LocalStorageManager.getValue("key");


text:
Q: Splunk query for time difference between 2 log statements I have 2 methods that logs message ID. The first method is JMS producer and the second method is JMS consumer. When messages are in the queue for a long time, then I need to print the message ID that were in the queue for more than 20 seconds.
 Log statements:

JMSProducer: MessageId=123
JMSProducer: MessageId=456

JMSConsumer: MessageId=123
JMSConsumer: MessageId=456

Using the timestamp at which they get logged, I need to run a report to give me the timestamp difference greater than 20 seconds.
How do I write a Splunk query for it?
The output should be message ID and timestamp difference in milliseconds or seconds.

A: Use transaction to tie the two log messages together, and it will give you a duration field.
search here | transaction MessageId | where duration > 20 | other operations here such as stats


text:
Q: is it possible to see how many/who has signed up for open beta? I have set up my app and prepared open beta using the Android Developer Console, but now I want to know how many have signed up for the beta. Is it possible to:

*

*See how many signed up for open beta?

*See who (by email) signed up for open beta?

I tried a google search, but all that appeared was information about alpha/beta testing and how to use it. There was nothing on seeing who/how many signed up for it.
Is this possible?

A: Yes, you can see how many users have enrolled to be beta testers. You need to go under the "Beta testing" tab in the "APK" section. See screenshot:

You can't see the user email though.

A: With recent changes, you can check number of beta testers using Release Management option.

Select your app -> Release -> Testing -> Open testing

A: Statistics > Devices > Install base
View by: App version
The button "+ App version" gives you a select that has the exact number of installs for every version.
This way you can determine how many people run your latest beta build.

A: Update (August 2022)
There's an additional option if you go to Statistics. Configure the report by "Users -> Installed audience -> All Users" OR "Device -> Install base -> All devices" (note, you can click "Select another metric" to view both). Then click "View By" and select "App version". Use the filter chips to display your version. Scroll to the bottom to see the data table, the latest date row can show you exactly how many users/devices have your app with that version.

Update (December 2021): As commented by @alexislg, the testers count isn't there any longer. If you open "Open Testing" (or another track), and if you have testers, the count will show up in the summary toward the top.
Original answer (2020): With the update to the redesign (as of Oct. 12 2020), just go to the Releases section and click Releases overview. You'll see how many testers are currently enrolled for each track.


text:
Q: Building Analysis Service Queries(MDX) With Filters In Reporting Service I'm having problem building MDX Queries in reporting service. I've searched through internet a lot about it and despite getting clear examples of MDX query and how to build it, I'm getting syntax error all the time. so here is the thing:
What I want to do is quite simple. I want to filter the data and only include rows that have equal values in corresponding columns and parameters. The original query generated by query builder is:
SELECT NON EMPTY { [Measures].[Value] } ON COLUMNS,
 NON EMPTY {
([Net Object Hierarchy].[Central Telecom Center].[Central Telecom Center].ALLMEMBERS *
[Net Object Hierarchy].[Province].[Province].ALLMEMBERS *
[Net Object Hierarchy].[County].[County].ALLMEMBERS *
[Net Object Hierarchy].[District].[District].ALLMEMBERS *
[Net Object Hierarchy].[Rural].[Rural].ALLMEMBERS *
[Net Object Hierarchy].[Village].[Village].ALLMEMBERS *
[Net Object Hierarchy].[Telecom Center].[Telecom Center].ALLMEMBERS *
[Net Object Hierarchy].[Switch].[Switch].ALLMEMBERS *
[Net Object Hierarchy].[Prefix].[Prefix].ALLMEMBERS *
[Measure].[Measure ID].[Measure ID].ALLMEMBERS *
DESCENDANTS([Date To].[Parent Date Key].[Level 02].ALLMEMBERS) ) } ON ROWS
FROM [Irtel Planning Statistics]

The parameters to filter the data include: "paramCentralTelecomCenter", "paramProvince", "paramCounty", "paramDistrict", ..., "paramPrefix".
For instance, if the value of the parameter paramProvince is set to "CA", I just need to retrieve those records with the value of [Net Object Hierarchy].[Province].[Province]="CA". This should be very simple but I'm completely lost.
Can anyone help me with that please? Thanks in advance.

A: You need to use a WHERE clause in your SELECT. This goes at the end, after the FROM.
For example, the following will restrict your query to those elements where Province is set to 'CA':
WHERE [Net Object Hierarchy].[Province].[Province].[CA]


text:
Q: IIS Rewrite loses path in Angular application upon refresh So I've been struggling with my Angular.js application and IIS rewrite. I have my site sitting in http://server/jwb/ folder. I have it rewriting to the index.html file in /jwb/ and I have a  inside of the index.html. The problem is that when I navigate to http://server/jwb/parties/12345, it appears fine when done through angular, but when I hit refresh on the browser I lose the CSS and javascript. I look in the console and they are being rewritten to http://server/jwb/parties/js/nameoffile.js, etc. What I want to do is tell IIS rewrite to always see the js, css and img files where they really reside which is at http://server/jwb/js, http://server/jwb/css and http://server/jwb/img, etc.
What is the rewrite rule that will accomplish this for me? Is there a better way than using a rewrite rule?
I currently have this in my web.config:
<rules>
    <rule name="Imported Rule 1" stopProcessing="true">
        <match url="^index\.html" ignoreCase="false" />
        <action type="None" />
    </rule>
    <rule name="Imported Rule 2" stopProcessing="true">
        <match url="." ignoreCase="false" />
        <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        </conditions>
        <action type="Rewrite" url="index.html" />
    </rule>
</rules>

However, this still does weird things. I even did some tests with the relative paths and here is what I found:
We have now tested the following ways of referencing the files:
<link rel="stylesheet" href="css/bootstrap.css" />

OR
<link rel="stylesheet" href="/css/bootstrap.css" />

OR
<link rel="stylesheet" href="./css/bootstrap.css" />

OR
<link rel="stylesheet" href="../css/bootstrap.css" />

And none of them work. The following shows what happens when we use each file in reference to a path for our application. For sake of argument, our paths are as follows:
index --> http://10.34.34.46/jbvdev/calendar
documents --> http://10.34.34.46/jbvdev/documents/BC498484
caseNotes --> http://10.34.34.46/jbvdev/casenotes/CV/LA%20/2081/BC498484

A: I had exactly the same issue... and after doing all the adding base ref and stuff which is suggested elsewhere still had the exact the same issue.
So yes, do add a base ref "/" in you index.html or whatever page is the base for your angular app. Then you need to revert to good ol' regex...
I played for a while to get the right bits in the right places, and capturing the right parts.... so you'll need to tweek it for yours...
For me my paths were

*

*/Content/blah.whatever for the html files and css and

*/Scripts/some.js etc for my javascript

What was happening was ON REFRESH ONLY the app route was getting inserted before the /Content or /Scripts... below is the set of rules that finally fixed it for me...
<rewrite>
  <rules>
    <rule name="Removevesseldetailsscripts" stopProcessing="true">
      <match url="^(.*[/])Scripts/(.*)$" />
      <conditions>
      </conditions>
      <action type="Redirect" url="Scripts/{R:2}" />
    </rule>
    <rule name="Removevesseldetailscontent" stopProcessing="true">
      <match url="^(.*[/])Content/(.*)$" />
      <conditions>
      </conditions>
      <action type="Redirect" url="Content/{R:2}" />
    </rule>
    <rule name="Main Rule" stopProcessing="true">
      <match url=".*" />
      <conditions logicalGrouping="MatchAll">
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
      </conditions>
      <action type="Rewrite" url="/" />
    </rule>
  </rules>
</rewrite>

The R:2 bit is to put the angular route back in the url in the right place, obviously there is R:1 as well which captured the root of the actual path...
Have a play and let me know if I can be of any more help!! Good luck!!!


text:
Q: How to dynamically update select source data I have two select inputs, the first one has a list of options and based on what's selected, the 2nd select will change it's data.  Initially, the 2nd select will have no values but it will dynamically change as the user selects values from the 1st select.
var sounds = {
                0:[{'id':0, 'text':'woof'}, {'id':1, 'text':'bark'}],
                1:[{'id':0, 'text':'meow'}, {'id':1, 'text':'purr'}],
                2:[{'id':0, 'text':'moo'}, {'id':1, 'text':'bellow'}]
             };
$('#select1').select2({
    data: [
               {'id':0, 'text':'DOG'},
               {'id':1, 'text':'CAT'},
               {'id':2, 'text':'COW'}
          ]
});
var select2_data = []
$('#select2').select2({
    data: select2_data
});

$('#select1').on("change", function(e) {
    data = $(this).select2('data');
    // Why doesn't this change data: in select2
    select2_data = sounds[data.id]
    $.each(select2_data, function(i, val) {
        console.log(val)
    });
});

In order to change select2's data, I assign the new list which data: is pointing to, but this doesn't work.  I am still seeing empty values.  What's going on?

A: Hope this would solve this problem.
http://jsfiddle.net/r7dhxt8e/6/
The only way to dynamically update to select2 is update select element options, select2 will listen for the changes and it will update it automatically.
    $(function() {
    var select1, select2, sounds, select2data = [];
    select1 = $("#select1"), select2 = $("#select2");
    sounds = { 0:[{'id':0, 'text':'woof'}, {'id':1, 'text':'bark'}],
              1:[{'id':0, 'text':'meow'}, {'id':1, 'text':'purr'}],
              2:[{'id':0, 'text':'moo'}, {'id':1, 'text':'bellow'}]
    };

    select1.select2({
        data:[
               {'id':0, 'text':'DOG'},
               {'id':1, 'text':'CAT'},
               {'id':2, 'text':'COW'}
          ],
        width:"200px"
    });
    select2.select2({
        data:select2data,
        width: "200px"
    });

    select1.on("change", function(e) {
       var data = $(this).select2('data');
       select2data = data && sounds[data[0].id];
       setSelect2Options(select2data);
    });

    function setSelect2Options(data) {
       if(!data) return;
       var i, l, html, opt;
       for(i = 0, l = data.length; i < l; i++) {
           opt = data[i];
           html += "<option value='"+ opt.id+"'>"+ opt.text + "</option>";
       }
       if(html) {
           select2.html(html);
       }
       select2.trigger('change');
    }
});


text: Q: Error while creating new project on Visual Studio I have installed Visual Studio 2010 successfully. Whenever I try to create a new project from Visual Studio I am getting error. Please check this screenshot.


text:
Q: MATLAB - stretching histogram algorithm I need to stretch histogram of two images, but using my own algorithm. This is my current code:
img_gray = imread('hist_gray.jpg');
img_couple = imread('hist_couple.bmp');

img_gray_mod = rozciaganie(img_gray);
img_couple_mod = rozciaganie(img_couple);

subplot(4,2,1);
imshow(img_gray);
title("Obraz oryginalny");

subplot(4,2,2);
imhist(img_gray);
title("Histogram");

subplot(4,2,3);
imshow(img_gray_mod);
title("Obraz po modyfikacji");

subplot(4,2,4);
imhist(img_gray_mod);
title("Histogram");

subplot(4,2,5);
imshow(img_couple);
title("Obraz oryginalny");

subplot(4,2,6);
imhist(img_couple);
title("Histogram");

subplot(4,2,7);
imshow(img_couple_mod);
title("Obraz po modyfikacji");

subplot(4,2,8);
imhist(img_couple_mod);
title("Histogram");

function r = rozciaganie(img);
mn = min(min(img));
mx = max(max(img));
r = 255*((img-mn)/(mx-mn));
end

That's what I get as output images and their histograms. Can anyone help me with this?

A: The problem you have is that your image is of type uint8. The following line:
r = 255*((img-mn)/(mx-mn));

does computations using 8-bit integers. img-mn should be fine, but then you divide by mx-mn, causing all your pixels to be either 0 or 1 (any non-integer value is rounded down). Finally, multiplying by 255 leads to values of 0 or 255 for all your pixels.
The simplest solution is to perform the operations using floating-point operations:
function r = rozciaganie(img);
img = double(img); % convert to double so all arithmetic is floating-point arithmetic
mn = min(img(:));  % better than min(min(img))
mx = max(img(:));
r = 255*((img-mn)/(mx-mn));
r = uint8(r); % convert back to uint8 so the display works as expected
end

Simply reordering the integer arithmetic doesn't work as expected either, for example (255*(img-mn))/(mx-mn) overflows values in the multiplication, results larger than 255 all become 255. The division after that will not recover those values. (img-mn)*(255/double(mx-mn)) is the best approximation, but might lead to some rounding artifacts. You could try it, though, to see if the results are good enough.


text:
Q: Existance of inverse of an operator I was studying abstract inverse source problem of an abstract heat equation in approach of semi group theory. There I am unable to find the reason of existence of inverse of an operator that i have described below.

Let $X$ be a Banach space  $\lbrace {T(t)}\rbrace _{t\geq 0}$ be a $C_0$ semi group of contraction of bounded linear operator on $X$ generated by a dissipative operator $A:D(A)\rightarrow X $ , where $D(A)\subset X$ and dense in $X$ . Let $t_0$ is a fixed positive real number. Then $(T(t_0)-I)^{-1}$   exists.

How do i prove the existence? I tried as follows.
As ${T(t)}$ is a $C_0$ semi group of contraction, $||T(t)||\leq \exp(wt)$ for some $w\geq {0}$.
Then $||T(t_0)x-x||\leq |\exp(wt_0)-1|*||x||$ for all $x$ in $ X$. Now if I can able to prove that range of $(T(t_0)-I) $  is $X$, then the operator $(T(t_0)-I)$ is invertible.


text:
Q: Total number of users at end of each week for last 6 months I am trying to find the total number of users at the end of each week for the last 26 weeks.
For example,

*

*Beginning of week 26 there are 100 users and 20 new users sign up that week so end of week 26 there are 120

*Beginning of week 25 there are 120 users and 20 new users sign up that week so end of week 25 there are 140

*Beginning of week 24 there are 140 users and 0 new users sign up and 10 delete their accounts that week so end of week 24 there are 130

*Beginning of week 23 there are 130 users and 10 new users sign up that week so end of week 24 there are 140

and so on
I can find the number of new users each week but how can I get it to show me the total (i.e. new this week + all those prior to this week) and so on without having to create 26 seperate selects? Is it possible?
I found Grouping total active users for each of the previous 8 weeks but it is for SQL Server and I don't think it does quite what I need.
I am using this to get the new each week:
select count(id) as total
    from users
    where join_date>='$sixmonths'
    group by WEEK(join_date)
    order by WEEK(join_date) desc
    limit 26

A: Query:
select count(u.id) as total,
       (SELECT COUNT(u.id)
        FROM users u2
        WHERE WEEK(u2.join_date) <=
              WEEK(u.join_date)
        AND u2.id = u.id) AS Total_count
from users u
where u.join_date>='$sixmonths'
group by WEEK(u.join_date)
order by WEEK(u.join_date) desc
limit 26

For Query to work between years:
select count(u.id) as total,
       (SELECT COUNT(u.id)
        FROM users u2
        WHERE YEARWEEK(u2.join_date) <=
              YEARWEEK(u.join_date)
        AND u2.id = u.id) AS Total_count
from users u
where u.join_date>='$sixmonths'
group by YEARWEEK(u.join_date)
order by YEARWEEK(u.join_date) desc
limit 26


text:
Q: Custom image size without stretching using Intervation Image? I want to make a thumb from an orginal image with size 263x385, the problem is that the image always stretches. Any suggestion on how I can accomplish this?
I'm currently using this code:
$image->resize(263, 385, function ($c) {
    $c->upsize();
})->save($article_image_path . '/article_' . $article->id . '/thumbs/263x385/' . $filename);

A: Check out fit() method.

Combine cropping and resizing to format image in a smart way. The method will find the best fitting aspect ratio of your given width and height on the current image automatically, cut it out and resize it to the given dimension.


text:
Q: Improve Performance of drawBitmap and Frame rate of game thread (android) I have  a game thread which draws on surface view. It processes game variables and then draws on canvas.  board is a bitmap which would be drawn on canvas of the view. callDrawHelper re-draws on  board, first simple background image (same size as board). Then clusters list has set of images to be drawn on canvas based on game variable data. This entire process executes each frame.
callDrawHelper takes close to 80 milliseconds, which is highest components of thread processing. This really lowers the frame rate as well.   How can I improve performance this code segment.
protected void callDrawHelper() {

    Canvas gfx = drawJustBackground();
        for (int i = 0; i < clusters.size(); i++) {

            PieceCluster cluster = clusters.get(i);
            if (cluster.isVisible) {
                gfx.drawBitmap(cluster.Picture, cluster.BoardLocation.left,
                        cluster.BoardLocation.top, null);
            }
        }

}

 protected Canvas drawJustBackground() {
    Canvas gfx = new Canvas(board);
    gfx.drawBitmap(background, 0, 0, null);
    return gfx;
}

A: It's hard to say what's the problem without further investigation. I would start with using Traceview to analyze CPU usage as suggested here: Android drawBitmap Performance For Lots of Bitmaps? Also make sure that your images are already scaled as suggested here: Improve performance of Canvas.drawBitmap() on android.


text:
Q: Simple Rewrite not working I've been staring at this for far too long. To cope with a Wordpress URL structure change, I need a URL rewrite to cope with old links that are floating around the net. The rule I've created is
RewriteRule [0-9]+/[0-9]+/[0-9]+/(.+)$ /$1 [R=301,L]

To match posts with URLs like
/2013/02/05/Some-wonderful-article

supposedly redirecting to
/Some-wonderful-article

Apache seems to be ignoring this, though, and happily sticks with the original URL. Can anyone see why? Am I forgetting some quirk of Apache's implementation of regex? I've already wasted some time playing with \d instead of [0-9] ...

A: Try this rule:
RewriteEngine on
RewriteBase /
RewriteRule ^/?[0-9]+/[0-9]+/[0-9]+/(.+)$ /$1 [R=301,L]

I added the command to activate the rewrite engine and also a line which defines a base for the RewriteRules.


text:
Q: Obtener Fecha y hora para enviar a una variable tipo struct en c++ Saludos cordiales, tengo una consulta agradezco su gentil apoyo:
using namespace std;

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

//Fecha basado en el sistema actual de Sistema operativo
time_t now= time(0); // captura fecga y hora actual

tm *time =localtime(&now); //ceamo el puntero time y se referencia objeto time y se guarda en var now
cout << "Dia de la semana:" << time->tm_wday << endl;  //accedemos al objeto time y miemto

system("Pause");
return 0;
}

la pregunta es como envío la fecha y hora a una variable en c++

A: Esta es la definicion de la estructura tm:
struct tm {
    int tm_sec;         /* seconds */
    int tm_min;         /* minutes */
    int tm_hour;        /* hours */
    int tm_mday;        /* day of the month */
    int tm_mon;         /* month */
    int tm_year;        /* year */
    int tm_wday;        /* day of the week */
    int tm_yday;        /* day in the year */
    int tm_isdst;       /* daylight saving time */
};

Puedes leer los datos y almacenarlos en una variable o una estructura, pero si lo que quieres es un número único entonces solo usa now que es el numero de segundos transcurridos desde el primero de enero de 1970.

A:
¿Cómo envío la fecha y hora a una variable en C++?

Entiendo que por "enviar" la fecha y hora a una variable te refieres a guardar el dato. Si te refieres a eso ya lo has hecho:
tm *time =localtime(&now);
//  ~~~~ <-- fecha y hora guardadas en la variable time

Pero esta no es la manera C++ de hacerlo, la estructura tm pertenece a los tipos de datos de C. Para hacerlo en C++ debe usarse la cabecera <chrono>.
La cabecera <chrono> da acceso a diferentes relojes (reloj de sistema, reloj estable, reloj de alta resolución) y a varias utilidades para trabajar con medidas de tiempo. Para obtener la hora actual tan sólo escribe:
auto ahora = std::chrono::system_clock::now();
//   ~~~~~ <-- fecha y hora guardadas en la variable ahora

La llamada a system_clock::now() devuelve un objeto de tipo time_point que puede ser usado con otras variables del mismo tipo para hacer operaciones (restar o sumar tiempo, comparar tiempos...).


text:
Q: base::plot -- can I retrieve the as-plotted aspect ratio? I know I can specify the aspect ratio when plotting, e.g. plot(x,y,asp=5) . Is there any way to retrieve the aspect ratio after allowing autoscale (as in plot(x,y)) ?  The reason I ask is that I was playing with text(x,y,'mystring',srt=local_slope) , where I calculate the local_slope based on the underlying curve and the x value of interest.  Trouble is, for asp!=1 this rotates the text at a different angle from the displayed slope of my plotted data set.   Sample:
x<- -10:10
y<- x^2
plot(x,y,t='l',asp=0.1)
# the slope at x=1 is 2 but the default plot aspect ratio is far from 1:1
text(1,1,'foo',srt= 180/pi*atan(2) )  #ugly-looking
text(-1,1,'bar',srt= (180/pi*atan(2/10))) #better

A: x<- -10:10
y<- x^2
plot(x,y,t='l',asp=0.1)
### the slope at x=1 is 2 but the default plot aspect ratio is far from 1:1
text(1,1,'foo',srt= 180/pi*atan(2) )  #ugly-looking
text(-1,1,'bar',srt= (180/pi*atan(2/10))) #better

Get width and height of plotting region in inches ...
ff <- par("pin")
ff[2]/ff[1]  ## 1.00299

Now resize the plot manually ...
ff <- par("pin")
ff[2]/ff[1]  ## 0.38

You can also use par("usr") to sort out the aspect ratio
in user units, but I haven't figured out quite the right
set of ratios ...  the guts of MASS::eqscplot might be enlightening too.


text:
Q: Why does my lua 'class' report an attempt to index global object error? The following code is in a file named object.lua:
function object:new()
  local instance = {}
  setmetatable(instance, self)
  self.__index = self
  return instance
end

In a main file I have:
local object = require("object")
local obj = object:new()

The error reported is:
lua ./object.lua:1: attempt to index global 'object' (a nil value)
Line #1 is the first line with 'function object:new()'
In main it's the first line (with require).
Code created from:
http://www.lua.org/pil/16.1.html
Edit:
Please see this page:
http://www.coronalabs.com/blog/2011/09/29/tutorial-modular-classes-in-corona/
Then search for 'james' it will be the first comment post and you can see what I'm trying to do.

A: This works for me:
main.lua
require("object")
local obj = object:new()

object.lua
object = {}

function object:new()
    local instance = {}
    setmetatable(instance, self)
    self.__index = self
    return instance
end

You are declaring a global "object" in object.lua, not returning it, so you just need to do require("object")

A: The issue here is that when the code in object.lua is run and you attempt to create the object:new function there is no object table to create it in.
Dogbert's solution works fine in that object.lua creates the object table before using it. However, it does so by explicitly creating a global and then expecting callers to have found that which is not the best solution. The amended solution provided by Nicol Bolas... that of creating a local object in object.lua and returning it is the more generally agreed upon pattern for this sort of task.


text:
Q: Powershell script- Configure Permission to Access CRM API I have a Powershell that can Register an application in Azure Active Directory. But I am unable to find script for configuring this app to access CRM APIs. I am referring to this link
 Any pointers are welcome. Thanks!

A: You could use New-AzureADApplication to grant permission. Like below:
$myApp = New-AzureADApplication -DisplayName $appName -IdentifierUris $appURI -Homepage $appHomePageUrl -ReplyUrls $appReplyURLs -PasswordCredentials $PasswordCredential -RequiredResourceAccess $reqGraph

This blog will be helpful.
You also could give permission on Azure Portal.

Please refer to this link.


text:
Q: Link error in converting qmake to cmake I have a simple project in Qt Creator (based on Qt 5.8) using RTI DDS Libraries. My project is successfully built and linked in Qt by qmake as the tool build.
Now I want to build my project with cmake build tool. So I write the below CmakeLists.txt. But I get the link error to RTI libraries. I have brought both qmake and cmake file. Please tell me what I am doing wrong;
qmake (.pro file):
QT += core
QT -= gui

DEFINES += "_GLIBCXX_USE_CXX11_ABI=0"
QMAKE_CXXFLAGS+=-std=c++11

TARGET = untitled
CONFIG += console
CONFIG -= app_bundle

TEMPLATE = app

SOURCES += main.cpp \
    datawriter.cpp \
    ../../../Repositories/tests/r.karimi/Publisher/data/IDLs/myIDL/myIDL.cxx \
    ../../../Repositories/tests/r.karimi/Publisher/data/IDLs/myIDL/myIDLImpl.cxx \
    ../../../Repositories/tests/r.karimi/Publisher/data/IDLs/myIDL/myIDLImplPlugin.cxx

HEADERS += \
    datawriter.h \
    ../../../Repositories/tests/r.karimi/Publisher/data/IDLs/myIDL/myIDL.hpp \
    ../../../Repositories/tests/r.karimi/Publisher/data/IDLs/myIDL/myIDLImpl.h \
    ../../../Repositories/tests/r.karimi/Publisher/data/IDLs/myIDL/myIDLImplPlugin.h

QMAKE_CXXFLAGS += -DRTI_UNIX
QMAKE_CXXFLAGS += -DRTI_LINUX
QMAKE_CXXFLAGS += -DRTI_64BIT

unix:LIBS += -L$$(NDDSHOME)/lib/x64Linux3gcc4.8.2 -lnddscd -lnddscored -lnddscpp2d -lrtidlcppd -lrtirsinfrastructured
INCLUDEPATH += .. \
                $$(NDDSHOME)/include/ndds/hpp \
                $$(NDDSHOME)/include \
                $$(NDDSHOME)/include/ndds \
                $$(NDDSHOME)/include/persistence \
                ../../../Repositories/tests/r.karimi/Publisher/data/IDLs/myIDL \

CMakeLists.txt
cmake_minimum_required(VERSION 3.7)
project(Publisher)

set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
add_definitions(-D_GLIBCXX_USE_CXX11_ABI=0)

# Add RTI flags:
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DRTI_UNIX")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DRTI_LINUX")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DRTI_64BIT")

macro(add_idl_files LIBNAME)
    include_directories($ENV{HOME}/tests/r.karimi/Publisher/data/IDLs/${LIBNAME})
    list(APPEND SOURCE_FILES $ENV{HOME}/tests/r.karimi/Publisher/data/IDLs/${LIBNAME}/${LIBNAME}.cxx)
    list(APPEND SOURCE_FILES $ENV{HOME}/tests/r.karimi/Publisher/data/IDLs/${LIBNAME}/${LIBNAME}Impl.cxx)
    list(APPEND SOURCE_FILES $ENV{HOME}/tests/r.karimi/Publisher/data/IDLs/${LIBNAME}/${LIBNAME}ImplPlugin.cxx)
    list(APPEND HEADER_FILES $ENV{HOME}/tests/r.karimi/Publisher/data/IDLs/${LIBNAME}/${LIBNAME}.hpp)
    list(APPEND HEADER_FILES $ENV{HOME}/tests/r.karimi/Publisher/data/IDLs/${LIBNAME}/${LIBNAME}Impl.h)
    list(APPEND HEADER_FILES $ENV{HOME}/tests/r.karimi/Publisher/data/IDLs/${LIBNAME}/${LIBNAME}ImplPlugin.h)
endmacro()

set(SOURCE_FILES src/main.cpp src/DataWriter.cpp)
set(HEADER_FILES include/DataWriter.h)

include_directories(
        include
        # RTI
        $ENV{NDDSHOME}/include
        $ENV{NDDSHOME}/include/ndds
        $ENV{NDDSHOME}/include/ndds/hpp
        $ENV{NDDSHOME}/include/persistence
)

# Add DDS Libs
add_idl_files(myIDL)

set(
        LIBS
        #RTI
        nddscd
        nddscored
        nddscpp2d
        rtidlcppd
        rtirsinfrastructured
)

link_directories(
        $ENV{NDDSHOME}/lib/x64Linux3gcc4.8.2
)
set(CMAKE_VERBOSE_MAKEFILE ON)

add_executable(${PROJECT_NAME} ${SOURCE_FILES} ${HEADER_FILES})
target_link_libraries(${PROJECT_NAME} ${LIBS})

Link errors:
.../libnddscored.so: undefined reference to `dlopen'
.../libnddscored.so: undefined reference to `dlclose'
.../libnddscored.so: undefined reference to `dlerror'
.../libnddscored.so: undefined reference to `dlsym'

Thanks in advance for your help.
Reza

A: .../libnddscored.so: undefined reference to `dlopen'
.../libnddscored.so: undefined reference to `dlclose'
.../libnddscored.so: undefined reference to `dlerror'
.../libnddscored.so: undefined reference to `dlsym'

These symbols are defined in -ldl. Simply add ${CMAKE_DL_LIBS} to target_link_libraries().


text:
Q: Getting no response back from jquery.ajax cross-domain I am brand new to jQuery.ajax so please bear with me. I am trying to create a form that validates addresses against a public api, data.citycofchicago.org. If I hit the URL (http://data.cityofchicago.org/api/views/i6bp-fvbx/rows/1478.json) directly, I see the json formatted page. However, I don't seem to be getting a response using ajax. Here is my code:
<script LANGUAGE="JavaScript" SRC="/scripts/jquery-1.7.1.js"></script>
<script type="text/javascript">
$('document').ready(function(){
    $('#button').click(function(){
        $.ajax({
            type: 'get',
            url: 'http://data.cityofchicago.org/api/views/i6bp-fvbx/rows/1478.json',
            success: function() {
                    alert('Got a response!');
                }
        });
    });
});

If I change the URL to an internal page on my site, I see the alert box. When I use this URL, I get no response box. I've tried setting the datatype to json and jsonp but nothing. Any ideas?
Thanks.

A: You can't just specify dataType: jsonp and expect everything to work. What that does is makes jQuery take care of the client-side portion of the AJAX call, but you'll still need to adjust the server-side portion to accomodate JSONP.
Basically, when you specify JSONP, jQuery automatically sends a callback parameter with a randomly generated value such as "jQuery4857439875349_489437589374." What you need to do in your server-side code is wrap the returned data in the specified callback, like this:
echo $_GET['callback']."(".json_encode($arr).")";

A: Ajax Cross Domain requests are not supported by browsers in order to stop XSS, or malicious scripting on your website. You can only use Ajax on internal pages. This applies to separate subdomains as well. Hope that helps.


text:
Q: Preserving column types when applying ifelse() across columns of different types in R This seems to be a fairly simple task, but I couldn't figure it out after studying the documentation of ifelse(), dplyr::if_else() and several similar posts on SO about applying ifelse() to multiple columns in a data frame.
My goal: I have the following data frame with columns of different data types. On each row, I want to reset the values in the first 3 columns to NA, if Column "valid" indicates false.
The problem: I used dplyr::across() and ifelse() to change the values as I wanted, but the date Column date and factor Column team were coerced to numeric (as shown in the reprex below), which wasn't desirable. I know that dplyr::if_else() preserves data types, but it doesn't work across columns of different data types, either.
I know tdf[tdf$valid == FALSE, !grepl("valid", names(tdf))] <- NA could achieve my goal, but I prefer a tidyverse approach, which I could use in my data cleaning pipeline. Many thanks in advance!
library(dplyr)

tdf <- tibble(
  date = c(as.Date("2021-12-10"), as.Date("2021-12-11")),
  team = factor(1:2, labels = c("T1", "T2")),
  score = 3:4,
  valid = c(TRUE, FALSE)
)

tdf
#> # A tibble: 2 x 4
#>   date       team  score valid
#>   <date>     <fct> <int> <lgl>
#> 1 2021-12-10 T1        3 TRUE
#> 2 2021-12-11 T2        4 FALSE

tdf %>% mutate(across(-valid, ~ ifelse(valid, ., NA)))
#> # A tibble: 2 x 4
#>    date  team score valid
#>   <dbl> <int> <int> <lgl>
#> 1 18971     1     3 TRUE
#> 2    NA    NA    NA FALSE

Created on 2021-12-10 by the reprex package (v2.0.1)

A: Make use of the default (TRUE) option in case_when which returns the NA based on the type
library(dplyr)
tdf %>%
    mutate(across(-valid, ~ case_when(valid ~ .)))

-output
# A tibble: 2 × 4
  date       team  score valid
  <date>     <fct> <int> <lgl>
1 2021-12-10 T1        3 TRUE
2 NA         <NA>     NA FALSE

Or another option is replace
tdf %>%
   mutate(across(-valid, ~ replace(., !valid, NA)))
# A tibble: 2 × 4
  date       team  score valid
  <date>     <fct> <int> <lgl>
1 2021-12-10 T1        3 TRUE
2 NA         <NA>     NA FALSE

According to ?ifelse

The mode of the result may depend on the value of test (see the examples), and the class attribute (see oldClass) of the result is taken from test and may be inappropriate for the values selected from yes and no.

Sometimes it is better to use a construction such as

(tmp <- yes; tmp[!test] <- no[!test]; tmp)

, possibly extended to handle missing values in test.

A: This is a not solved issue:
@akrun gives a very good explanation and how you could solve your specific problem!
But in case if you want to keep ifelse:
The only working solution (with dates and factors) in your specific case is provided by Fabian Werner in 2015 using a custom safe.ifelse
How to prevent ifelse() from turning Date objects into numeric objects
safe.ifelse <- function(cond, yes, no) {
  class.y <- class(yes)
  if (class.y == "factor") {
    levels.y = levels(yes)
  }
  X <- ifelse(cond,yes,no)
  if (class.y == "factor") {
    X = as.factor(X)
    levels(X) = levels.y
  } else {
    class(X) <- class.y
  }
  return(X)
}

tdf %>% mutate(across(-valid, ~ safe.ifelse(valid, ., NA)))

  date       team  score valid
  <date>     <fct> <int> <lgl>
1 2021-12-10 T1        3 TRUE
2 NA         NA       NA FALSE


text:
Q: Pop up blocker problem I have the following html
<form action="http://www.google.com" method="post" name="first" target="_blank" id="first">
    <img src="loader.gif"  id="icon"/>
</form>
</body>
<script type="text/javascript">
$("#icon").click(function(){
document.first.submit();
})
//setTimeout("document.first.submit()", 1 * 500);

In this, while clicking the image, it will submit the form and new tab will open with 'http://www.google.com'
When i do the same functionality, on setTimeout  or in page load, it will produce popup bloker, how can we avoid the pop up blocker

A: You can't. Popup blockers work by blocking popups that haven't been triggered by a users action. That is why it is working on click.
Unfortunately, you won't be able to get it to work without user interaction unless you get the users to explicitly allow popups from your site which I imagine would be quite difficult to convince them.


text:
Q: Prior for Bayesian multiple logistic regression I was wondering how I could incorporate a prior to form a posterior distribution for multiple logistic regression.
More specifically, I am working with basketball data, where the response variable is binary (whether a player made the shot or not) and the explanatory variables are the distance from the basket and the defensive ratings of the opposing 5 players. I am able to generate multiple seasons worth of these shot logs for each player from the past, and wanted to know how I could take previous seasons of data into account when I also have a current season's worth of data.

A: This article discusses Bayesian logistic regression nicely. Basically, you have the flexibility to parametrize estimation however you see fit, but using a model which is linear on the log odds scale makes sense for many reasons. Furthermore, using a normal prior for log odds ratios should give you very approximately normal posteriors.
To do the sequential analysis, estimate the "prior" for this season by doing a first-pass Bayesian logistic regression for past seasons using a non-informative normal prior for that model.


text:
Q: Jsoup image tag extraction  i need to extract an image tag using jsoup from this html

i need to extract the src of this img tag ...
i am using this code i am getting null value
Element masthead2 = doc.select("div.picture").first();
String linkText = masthead2.outerHtml();
Document doc1 = Jsoup.parse(linkText);
Element masthead3 = doc1.select("img[src]").first();
String linkText1 = masthead3.html();

A: Here's an example to get the image source attribute:
public static void main(String... args) {
    Document doc = Jsoup.parse("

");
    Element img = doc.select("div.picture img").first();
    String imgSrc = img.attr("src");
    System.out.println("Img source: " + imgSrc);
}

The div.picture img selector finds the image element under the div.
The main extract methods on an element are:

*

*attr(name), which gets the value of an element's attribute,

*text(), which gets the text content of an element (e.g.  in
Hello
, text() is "Hello"),

*html(), which gets an element's inner HTML (

 html() = ), and

*outerHtml(), which gets an elements full HTML (

 html() =

)

You don't need to reparse the HTML like in your current example, either select the correct element in the first place using a more specific selector, or hit the element.select(string) method to winnow down.

A: With the following code I can extract the image correctly:
    Document doc = Jsoup.parse("

");

    Element elem = doc.select("div.picture img").first();

    System.out.println("elem: " + elem.attr("src"));

I'm using jsoup release 1.2.2, the latest one.
Maybe you're trying to print the inner html of an empty tag like img.
From the documentation: "html() - Retrieves the element's inner HTML".
For the second portion of html you can use:
    Document doc2 = Jsoup.parse("
  CAST: 	  Jay, Shazahn Padamsee
");
    Elements trElems = doc2.select("tr");
    if (trElems != null) {
        for (Element element : trElems) {
            Element secondTd = element.select("td").get(1);

            System.out.println("name: " + secondTd.text());
        }
    }

which prints "Jay, Shazahn Padamsee".

A:
  CAST: 	  Jay, Shazahn Padamsee

You can use:
Document doc = Jsoup.parse(...);
Elements els = doc.select("td[class=blackNoLine]");
Element el= els.get(1);
String castName = el.text();


text:
Q: How to fill boost::fusion::vector at runtime? Firstly, apologies for the similarity to my previous question here, but I don't think I asked the right thing.
I have a method:
template <typename T>
void some_method( T &t)
{...}

which takes a type fusion::vector<T1, T2, T3, ..., Tn> to be determined at runtime - e.g. vector<int, double> in one call and vector<int, double, int> in another.
I want to fill this vector dynamically with something like:
int blah = 5;
for(int i = 0; i<size(t); i++){
at_c<i>(t) = blah;
}

This doesn't work since at_c expects a const.
I've tried other stuff (see the previous question) but still can't work out how to achieve this.
Any help much appreciated!
Thanks.

A: As @Mankarse specified correctly, you can't use fusion containers in a for loop and that's because fusion containers are all about tuple and each element may have different type from other elements, all functions that iterate through a fusion container are actually a couple of functions and usually implemented as template or overloaded functions. So in order to initialize a fusion container from a vector you should have multiple functions (or simply a template that will be compiled to multiple classes or functions) that all have access to that vector(or at least an iterator from the vector and an state variable that can increased for each call). So you have 2 options:
1) Use boost::fusion::fold:
template< class StdIteratorT >
struct initialize_fusion_container_from_std_iterator {
    typedef StdIteratorT    result_type;

    template< class T >
    StdIteratorT operator()( StdIteratorT i, T& val ) {
        val = *i;
        return ++i;
    }
};
void use_fold_demo() {
    int p1[] = {4, 5, 6};
    fusion::vector<int, double, int> fv;
    std::vector<int> sv2( p1, p1 + _countof(p1) );
    fusion::fold( fv, sv2.begin(),
    initialize_fusion_container_from_std_iterator<std::vector<int>::iterator>() );
}

2) Write a function that recursively call itself with next item of the container(remember syntax of this function is like recursive functions but it is not recursive at all):
// this will be called when we reach end of the fusion container(FIBeginT==FIEndT)
template< class FIBeginT, class FIEndT, class StdIteratorT >
void set_fusion_iterator( FIBeginT b, FIEndT e, StdIteratorT i, boost::mpl::true_ )
{
}
// this will be called when FIBeginT != FIEndT
template< class FIBeginT, class FIEndT, class StdIteratorT >
void set_fusion_iterator( FIBeginT b, FIEndT e, StdIteratorT i, boost::mpl::false_ )
{
    *b = *i;
    set_fusion_iterator( fusion::next(b), e, ++i,
        fusion::result_of::equal_to<
            typename fusion::result_of::next<FIBeginT>::type, FIEndT >() );
}

void recursive_function_demo() {
    typedef fusion::vector<int, double, int>    my_fusion_vector;

    int p1[] = {1, 2, 3};
    std::vector<int> sv1( p1, p1 + _countof(p1) );
    fusion::vector<int, double, int> fv;
    set_fusion_iterator( fusion::begin(fv), fusion::end(fv), sv1.begin(),
        fusion::result_of::equal_to<
            typename fusion::result_of::end<my_fusion_vector>::type,
            typename fusion::result_of::begin<my_fusion_vector>::type>() );
}

As you see second case is much more complicated, but if you understand its logic you can use it to do anything with fusion containers, so the choice is all yours!!

A: You could use boost::fusion::for_each:
#include <boost/fusion/algorithm.hpp>
#include <boost/fusion/container.hpp>

struct F {
    F(int blah): blah(blah){}
    template <typename T>
    void operator()(T& t) const {
        t = blah;
    }
    int blah;
};

template <typename T>
void some_method(T &t)
{
    boost::fusion::for_each(t, F(6));
}

int main() {
    boost::fusion::vector<int, double, int> idi;
    some_method(idi);
    boost::fusion::vector<int, double> id;
    some_method(id);
}

In an attempt to demystify the for_each, here is some mostly equivalent code that uses numerical indices instead:
#include <boost/fusion/algorithm.hpp>
#include <boost/fusion/container.hpp>
#include <boost/fusion/sequence.hpp>

template<typename T, int N, int End>
struct some_method_impl {
    void operator()(T& t) const {
        int blah = 6;
        boost::fusion::at_c<N>(t) = blah;
        some_method_impl<T, N+1, End>()(t);
    }
};

template<typename T, int N>
struct some_method_impl<T,N,N> {
    void operator()(T& t) const {}
};

template <typename T>
void some_method(T &t)
{
    some_method_impl<T,0,boost::fusion::result_of::size<T>::type::value>()(t);
}

int main() {
    boost::fusion::vector<int, double, int> idi;
    some_method(idi);
    boost::fusion::vector<int, double> id;
    some_method(id);
}

A: How about this?
This is similar to the above case using
     boost::fusion::for_each
.
But faster when i < size(t)  than the above.
usage
main(){
  boost::fusion::vector<int,double,std::string,char> vec(9 ,2.2 ,"aaa" ,'b');
  std::cout << at_n_dynamic<double>(vec, 1) << std::endl; //=> 2.2
}

body
#include <boost/fusion/include/vector.hpp>
template<typename V>
struct fusion_at_n_functor
{
   mutable int i;
   int n;
   mutable V value;
   fusion_at_n_functor(int _n):i(0),n(_n){}
   void operator()(const V & t) const
   { if(i==n){value=t;} i++;}
   template<typename T>
   void operator()(const T & t) const
   { i++;}
};

template <typename First,typename Last,typename AtN > void
at_n_dynamic_fusion_impl(First i,Last last,AtN &atn,boost::mpl::true_ ){}
template <typename First,typename Last,typename AtN > void
at_n_dynamic_fusion_impl(First i,Last last,AtN &atn,boost::mpl::false_ ){
  if(atn.i == atn.n ){atn(boost::fusion::deref(i));}
  else{
    atn(boost::fusion::deref(i));
    at_n_dynamic_fusion_impl(boost::fusion::next(i),last,atn,
           boost::fusion::result_of::equal_to<
             typename boost::fusion::result_of::next<First>::type,Last>  ());}
}

template <typename Ret,typename Sequence>  Ret
 at_n_dynamic(Sequence & seq, int n){
   fusion_at_n_functor<Ret> atn(n);
#if 0
  // enabling this if is same to the above case of boost::fusion::for_each
   boost::fusion::for_each(seq, atn);
#else
  // this recursion loop stop at n. but boost::fusion::for_each stop at last
   at_n_dynamic_fusion_impl(boost::fusion::begin(seq),boost::fusion::end(seq) ,atn,
         boost::fusion::result_of::equal_to<
           typename boost::fusion::result_of::begin<Sequence>::type,
           typename boost::fusion::result_of::end<Sequence>::type>());
#endif
    return atn.value;}

This is
 copy of boost-users ML my post
http://lists.boost.org/boost-users/2012/08/75493.php
http://d.hatena.ne.jp/niitsuma/20120803/1343979718


text:
Q: Java Match string format So I want to match a string to a simple mask but I would like to avoid using regex because my client have access to this mask and can change it.
Is it possible to have a string matches something like #####-000?
Or I have no choice but to convert my simple mask to regex ?
Thank you.

A: If I get your question (and the comments) the right way, you could do the following:

*

*Split your string at '-'

*Check if string before '-' has length 5 and is numeric (StringUtils.isNumeric(...))

*Check if the string after '-' equals '000'


text:
Q: Raspberry Pi - C program not writing to text file I am new to programming with linux/raspbian and I am trying to make a program that extracts the Pi system time and writes it to a text file whenever pin 23 goes high. Pin 23 is connected to an S-R Latch and pin 24 sends out a reset signal to reset the latch.
The problem I am having is that it doesn't seem to write anything to the text file that is created. The program creates the file fine but doesn't write anything to it. Here is my code:
using namespace std;
FILE *f;
struct timeval curTime;

int main(int argc, char *argv[]){
char dateiname[256] = "";
int i=0;
int milli;
int seconds_in_day;

wiringPiSetupGpio();

time_t t = time(0);
struct tm * now = localtime(&t);

//Create and open file
sprintf(dateiname, "/home/raspbian/Desktop/%02d%02d%02d_%02d_%02d.txt",
                       now -> tm_year+1900,
                       now -> tm_mon+1,
                       now -> tm_mday,
                       now -> tm_hour,
                       now -> tm_min);

f = fopen(dateiname, "w");
//write heading to file before loop
fprintf(f, "Picture, system time\n");

//Set 23 & 24 as input/ output
pinMode(23, INPUT);
pullUpDnControl(23, PUD_DOWN);
pinMode(24, OUTPUT);

while(1){
if(digitalRead(23)){ //If 23 is high
   i=i+1;
   gettimeofday(&curTime, NULL);
   milli = curTime.tv_usec / 1000; //Get time in milliseconds
   seconds_in_day = curTime.tv_sec % 86400; //Get seconds since midnight
   fprintf(f, "&d &d.%d\n", i, seconds_in_day, milli); //Write to file

   //send out reset signal
   digitalWrite(24, HIGH);
   //pause for 1 second
   delay(1000);
}
}
fclose(f);
return(0);
}

Does anyone see any obvious errors here? I am also running the program in the terminal through
sudo /home/raspbian/Desktop/program

and just quitting the program by exiting the terminal window. Thanks

A: It's probably buffering the output. The buffer isn't certain to be written until the fclose executes, which is never.
If you want the file updated once per second with a single line when pin 23 is high, put the file fopen and fclose inside the loop.  If you want to add a line every second, then add fflush(f); after the fprintf.

A: I suspect the output on pin 24 needs to be a 'short' period of 'high' to cause the latch to reset, followed by a return to 'low' in preparation for the next time the latch needs to be reset.
the lines like: while( !digitalRead(23) ); will burn a lot of CPU cycles, so may want to put some 'delay()' or yield() into a body for each of those loops
using namespace std;
FILE *f;
struct timeval curTime;

int main(int argc, char *argv[]){
    char dateiname[256] = "";
    int i=0;
    int milli;
    int seconds_in_day;

    wiringPiSetupGpio();

    time_t t = time(0);
    struct tm * now = localtime(&t);

    //Create and open file
    sprintf(dateiname, "/home/raspbian/Desktop/%02d%02d%02d_%02d_%02d.txt",
                           now -> tm_year+1900,
                           now -> tm_mon+1,
                           now -> tm_mday,
                           now -> tm_hour,
                           now -> tm_min);

    if( NULL == (f = fopen(dateiname, "w") )
    { // then fopen failed
        perror( "fopen failed for output file");
        exit(EXIT_FAILURE);
    }

    // implied else, fopen successful

    //write heading to file before loop
    fprintf(f, "Picture, system time\n");
    fflush( f );

    //Set 23 & 24 as input/ output
    pinMode(23, INPUT);
    pullUpDnControl(23, PUD_DOWN);
    pinMode(24, OUTPUT);

    // assure latch is reset
    digitalWrite(24, LOW);
    digitalWrite(24, HIGH);
    digitalWrite(24, LOW);

    while(1)
    {
        // wait while pin23 is low
        while( !digitalRead(23));

        // 23 is high
        i=i+1;
        gettimeofday(&curTime, NULL);
        milli = curTime.tv_usec / 1000; //Get time in milliseconds
        seconds_in_day = curTime.tv_sec % 86400; //Get seconds since midnight
        fprintf(f, "&d &d.%d\n", i, seconds_in_day, milli); //Write to file
        fflush( f );

        // if a latch 'set' signal is received during the following
        // three instructions, then could get locked into
        // the while pin23 high loop

        // reset latch
        digitalWrite(24, HIGH);
        digitalWrite(24, LOW);

        // wait for pin 23 to be low
        while( digitalRead(23) );
    } // end while

    fclose(f);
    return(0);
}


text:
Q: how to add footer in center using css class I am trying to set a footer in center but not work

        CopyRight@CCX.Com

I am using html with css class
I want to footer in center
Edit:
after adding text-align: center;  not set the footer in center see below image

A: This will do the trick.

        CopyRight@CCX.Com


text:
Q: How to write Vault LDAP Auth Configuration from a json config file? In my hashicorp vault container. I want to use the the ldap auth method to allows authentication
https://www.vaultproject.io/docs/auth/ldap.html
I'm writing a shell script that should write vault ldap configuration from a json file. My vault ldap configuration with the connection parameters is stored in the same directory and is named as parameters.json. What is the correct syntax to load LDAP connection parameters from an external file?
vault auth enable ldap
vault write auth/ldap/config config=@parameters.json

The above command does not overwrite the values from this file.

A: Made it work by replacing it with a text value with key value pair (key1=value 1 .... key n..value n)
vault write auth/ldap/config binddn=@binddn bindpass=@bindpass url =@url

Apparently, the ldap connection properties need to be specified one after the another and it's not possible to import a json file to parse

A: If curl is available, you can POST the data with a JSON file as the source like this:
curl -k --header "X-Vault-Token: $VAULT_TOKEN" --request POST --data @parameters.json https://127.0.0.1:8200/v1/auth/ldap/config

Note, that in the example TLS verification is disabled using the -k argument. This should not be done in production deployments were TLS can be verified correctly.


text:
Q: Ajax Call to append a div not working I'm actually new to ajax and jquery, and I've started working on it only a few days ago. I have a jsp code like this :
    Choose the type of procedure you want :
    <select id="proc-type" name="proc-type">
    <option value="selection">Select</option>
    <option value="with-param">With parameters</option>
    <option value="without-param">Without parameters</option>
    </select>

     Select Procedure (with parameters) :
     <select id="combobox" name="combobox">
     <option>Proc1</option
      <option>Proc2</option>
       ...
       ...
    </select>

     Select Procedure (without parameters) :
     <select id="combobox2" name="combobox2">
     <option>Proc a</option
      <option>Proc b</option>
       ...
       ...
    </select>

Now, these values are sent to a servlet and a html response is generated. The ajax call I used is :
if first dropdown changes :
document.getElementById("combobox").onchange = function(){
          var proc_type = document.getElementById("proc-type").value ;
          var username = document.getElementById("combo").value ;
          var proc_name1 = document.getElementById("combobox").value ;
          var proc_name2 = document.getElementById("combobox2").value ;
         console.log("before calling servlet ");
            $.ajax({
           url : "DBConnectServlet?user="+username+"&proc-type="+proc_type+"&combobox="+proc_name1+"&combobox2="+proc_name2,
           type : "GET",
           dataType:"text/html",
           success: function (data) {
               console.log("in ajax "+ data);
                  $('#response').html(data);
               }
      });
      };

if second dropdown changes :
document.getElementById("combobox2").onchange = function(){
              var proc_type = document.getElementById("proc-type").value ;
              var username = document.getElementById("combo").value ;
              var proc_name1 = document.getElementById("combobox").value ;
              var proc_name2 = document.getElementById("combobox2").value ;
             console.log("before calling servlet ");
                $.ajax({
               url : "DBConnectServlet?user="+username+"&proc-type="+proc_type+"&combobox="+proc_name1+"&combobox2="+proc_name2,
               type : "GET",
               dataType:"text/html",
               success: function(data) {
                   console.log("in ajax "+ data);
                      $('#response').html(data);
                   }
          });
          };

But problem is, the response is generated fine, but the div is not getting appended. Can anybody help ?
Even if there is some other way to do it, please suggest.

A: Try changing dataType to "text" or "html".There is no "text/html" in jquery manual about ajax on dataType.Good luck.


text:
Q: How to iterate over a array using a pointer and length unknown? I've been given a c api to work with and the minimum docs.
Developer is not around at the moment and his code is returning unexpected values (arrays not of expected length)
Im having problems with methods that return pointers to arrays and was wondering am I iterating over them correctly.
Q:does the following always return the correct len of an array?
int len=sizeof(sampleState)/sizeof(short);
int len=sizeof(samplePosition)/sizeof(int);

 typedef unsigned char byte;
 int len=sizeof(volume)/sizeof(byte);

And I iterate over the array using the pointer and pointer arithmetic (am I doing it correctly for all types below)
And last example below is multidimensional array? Whats the best way to iterate over this?
thanks
//property sampleState returns short[] as short*

    short* sampleState = mixerState->sampleState;
    if(sampleState != NULL){
        int len=sizeof(sampleState)/sizeof(short);
        printf("length of short* sampleState=%d\n", len);//OK

        for(int j=0;j<len;j++) {
            printf("    sampleState[%d]=%u\n",j, *(sampleState+j));
        }
    }else{
        printf("    sampleState is NULL\n");
    }

//same with int[] returned as  int*

    int* samplePosition = mixerState->samplePosition;
    if(samplePosition != NULL){
        int len=sizeof(samplePosition)/sizeof(int);
        printf("length of int* samplePosition=%d\n", len);//OK

        for(int j=0;j<len;j++) {
            printf("    samplePosition[%d]=%d\n",j, *(samplePosition+j));
        }
    }else{
        printf("    samplePosition is NULL\n");
    }

Here byte is type def to
typedef unsigned char byte;

so I used %u
    //--------------
    byte* volume    = mixerState->volume;

    if(volume != NULL){
        int len=sizeof(volume)/sizeof(byte);
        printf("length of [byte* volume = mixerState->volume]=%d\n", len);//OK

        for(int j=0;j<len;j++) {
            printf("    volume[%d]=%u\n",j, *(volume+j));
        }
    }else{
        printf("    volume is NULL\n");
    }

Here is int[][] soundFXStatus.
do I just use same method above and have 2 loops?
    //--------------
    int** soundFXStatus         = mixerState->soundFXStatus;

A: sizeof(sampleState)/sizeof(short);

This will only give the length of an array if sampleState is declared as an array, not a pointer:
short array[42];
sizeof(array)/sizeof(short);    // GOOD: gives the size of the array
sizeof(array)/sizeof(array[0]); // BETTER: still correct if the type changes

short * pointer = whatever();
sizeof(pointer)/sizeof(short);  // BAD: gives a useless value

Also, beware that a function argument is actually pointer even if it looks like an array:
void f(short pointer[]) // equivalent to "short * pointer"
{
    sizeof(pointer)/sizeof(short); // BAD: gives a useless value
}

In your code, sampleState is a pointer; there is no way to determine the length of an array given only a pointer to it. Presumably the API provides some way to get the length (since otherwise it would be unusable), and you'll need to use that.
In C++, this is one reason why you would prefer std::vector or std::array to a manually allocated array; although that doesn't help you since, despite the question tags, you are using C here.

A: The sizeof(array)/sizeof(element) trick only works if you have an actual array, not a pointer. There's no way to know the size of an array if all you have is a pointer; you must pass an array length into a function.
Or better use a vector, which has a size function.

A: int len=sizeof(sampleState)/sizeof(short);
int len=sizeof(samplePosition)/sizeof(int);

sizeof is done at compile time, so this approach doesnt work if the length of the arrays are not known at compile time (for example the memory is reserved using a malloc).

A: ok ignore the method I used above it was all wrong - though you do need to know the length of the array which I finally got from the API developer.


text:
Q: How to apply fundamental theorem of calculus to multiple integrals I have the following problem at hand:
$$\lim_{\epsilon \to 0}\dfrac{1}{4\epsilon^2}\int_{z-\epsilon}^{z+\epsilon}f(e_1,y) \int_{\frac{z+y}{2}-\epsilon}^{\frac{z+y}{2}+\epsilon}g(e_2,x) dx dy$$
$f$ and $g$ are well behaving, continuous functions. I have the following intuitive thought but I can't show it rigorously: I shift $1/2\epsilon$ inside the first integral. Then we have:
$$\lim_{\epsilon \to 0}\dfrac{1}{2\epsilon}\int_{z-\epsilon}^{z+\epsilon}f(e_1,y) \dfrac{1}{2\epsilon}\int_{\frac{z+y}{2}-\epsilon}^{\frac{z+y}{2}+\epsilon}g(e_2,x) dx dy$$
If it would be valid to apply Fundamental theorem of calculus both for inner and outer integrals, we would have obtain $f(e_1,z)g(e_2,z)$ as the result. But I have no idea how to show to in a proper way. What should be done in this case?

A: I don't know how to apply fundamental theorem of calculus here. But I would use bounding values of the functions.
You can restrict the analysis to $0 \le \epsilon \le 1$ which leads to a compact subset for the integral domain. As the functions are supposed to be continuous, those are also uniformly continuous on that compact domain.
Therefore for $\alpha > 0$, there exists $\epsilon >0$ such that $\vert g(e_2,u) - g(e_2,v) \vert \le \alpha$ for $\vert u - v \vert \le \epsilon$. In particular, you get:
$$\left\vert g(e_2,x) - g(e_2,\frac{z+y}{2}) \right\vert \le \alpha$$ for $x \in [\frac{z+y}{2} - \epsilon, \frac{z+y}{2} + \epsilon]$, hence:
$$\left\vert \int_{\frac{z+y}{2} - \epsilon}^{\frac{z+y}{2} + \epsilon} g(e_2,x) dx - 2 \epsilon g(e_2,\frac{z+y}{2}) \right\vert  \le 2 \alpha \epsilon$$ or
$$- 2 \alpha \epsilon + 2 \epsilon g(e_2,\frac{z+y}{2}) \le \int_{\frac{z+y}{2} - \epsilon}^{\frac{z+y}{2} + \epsilon} g(e_2,x) dx \le  2 \alpha \epsilon + 2 \epsilon g(e_2,\frac{z+y}{2})$$
You can multiply the inequalities by $f(e_1,y)$ and integrate on the domain $[z-\epsilon,z+\epsilon]$. Your double integral is then bounded lower and upper by a single integral. Now you can apply the Fundamental theorem of calculus to the continuous map $y \mapsto f(e_1,y)g(e_2,\frac{z+y}{2})$ to upper and lower bound your double integral by $f(e_1,z)g(e_2,z)$ plus a quantity that can be as small as desired leading to the result you were looking for.
Jean-Pierre (Math Counterexamples).

A: We may as well take $z=0.$ Suppose $h(x,y)$ is continuous in a neighborhood of $(0,0).$ Claim:
$$ (1)\,\,\,\,\frac{1}{4\epsilon^2}\lim_{\epsilon\to 0}\int_{-\epsilon}^\epsilon\int_{y/2-\epsilon}^{y/2+\epsilon}h(x,y)\,dx\,dy = h(0,0).$$
Proof: The linear transformation $T(u,v) = (u+v/2,v)$ maps $[-\epsilon,\epsilon]\times [-\epsilon,\epsilon]$ onto the region of integration in (1). We have $\det J_T = 1,$ where $J_T$ is the Jacobian matrix of $T.$ Thus the expression in (1) equals
$$\frac{1}{4\epsilon^2}\int_{-\epsilon}^{\epsilon} \int_{-\epsilon}^{\epsilon} h(u+v/2,v)\,du\,dv.$$
So we are looking at averages of a continuous function over squares centered at $(0,0).$ As these squares shrink in size, the averages converge to $h(0,0).$ This proves the claim, and also shows the OP's guess at the answer was right.

A: Since $g$ is continuous, by the Mean Value Theorem for integral, we have
$$\frac1{2\epsilon}\int_{\frac{z+y}{2}-\epsilon}^{\frac{z+y}{2}+\epsilon}g(e_2,x)dx=\frac1{2\epsilon}\int_{-\epsilon}^{\epsilon}g(e_2,\frac{z+y}{2}+x)dx=g(e_2,\frac{z+y}{2}+a\epsilon)$$
for $a\in(-1,1)$ independent of $\frac{y+z}{2}$. Then
$$\dfrac{1}{2\epsilon}\int_{z-\epsilon}^{z+\epsilon}f(e_1,y) \dfrac{1}{2\epsilon}\int_{\frac{z+y}{2}-\epsilon}^{\frac{z+y}{2}+\epsilon}g(e_2,x) dx dy=\dfrac{1}{2\epsilon}\int_{z-\epsilon}^{z+\epsilon}f(e_1,y)g(e_2,\frac{z+y}{2}+a\epsilon)dy.$$
Since $f$ and $g$ are continuous, by the Mean Value Theorem for integral again, we have
$$\dfrac{1}{2\epsilon}\int_{z-\epsilon}^{z+\epsilon}f(e_1,y)g(e_2,\frac{z+y}{2}+a\epsilon)dy=f(e_1,z+b\epsilon)g(e_2,\frac{2z+b\epsilon}{2}+a\epsilon)$$
for some $b\in(-1,1)$.
So
$$\lim_{\epsilon \to 0}\dfrac{1}{2\epsilon}\int_{z-\epsilon}^{z+\epsilon}f(e_1,y) \dfrac{1}{2\epsilon}\int_{\frac{z+y}{2}-\epsilon}^{\frac{z+y}{2}+\epsilon}g(e_2,x) dx dy=\lim_{\epsilon \to 0}f(e_1,z+b\epsilon)g(e_2,\frac{2z+b\epsilon}{2}+a\epsilon)=f(e_1,z)g(e_2,z).$$


text:
Q: chrome packaged app not loading xhr images on android ever since cca 0.0.9 When I updated my cca from 0.0.7 to the latest my app stopped loading all external images only when running on android specifically.
My app allows users to specify avatars from other sites by pasting or sharing an image url, and I had been resizing the image in javascript and storing it in chrome local storage.   However I recently upgraded my cca and the external images no longer loaded on android.  Oddly enough, the chrome extension and the packaged ios version of the app load the external images fine.
By trying different versions of cca, I found that the behavior change is introduced in version 0.0.9 specifically.  Is anyone aware of a major change in cca 0.0.9 that has changed how xhr loaded resources or images are processed in android specifically?  I've gone through the release notes for cca and it has some notes about host permission changes but I can't tell if that is specifically the problem.  Just wondering if other people have encountered the same issue and if there are any known workarounds, or even a way to identify the problem more specifically so I can escalate it to the cca developers.

A: So I've tracked this down to a problem with the way that CCA apps try to fix the hostname on HTMLAnchorElement.href attributes.
We added this code specifically for AngularJS on Android KitKat, to deal with chrome-extension:// URLs, but it is failing in your specific case because you're converting the image into a data:// URL, and the code in CCA is throwing an exception when the regular expression fails to match it.
I've just now created an issue for this, and it will be fixed in the next release of cca (probably 0.1.2, hopefully RealSoonNow)


text:
Q: Transfer cookie from one domain to another on different servers
Possible Duplicate:
How do I use cookies across two different domains?

Can you please tell me what is the easiest way to transfer cookies from one domain to another on different servers?
I have a website and a forum on different servers and different domains. I've already created the bridge between them regarding users.
Thanks.

A: You could do a an Ajax call from one server to the other, and rebuilding the session on the other server.
To use cross domain you need to use JsonP. Take a look here: http://api.jquery.com/jQuery.ajax/
This way, the site does do a request as the user, so the cookie/session does exists on the other server, and therefore you can set a new one.

A: Basicly: You can't.
Actually, this constitutes two problems:

*

*The split domain issue. If you have different subdomains (i.e. blog.example.net and www.example.net) you can set the domain to example.net for the cookie. If it is entirely different domains, please refer to the solution found on How do I use cookies across two different domains?

*The split server issue. For this, you need to write your own session management which can be distributed over several servers, i.e. via a separate database server. Please refer to the php docs on this matter.


text:
Q: Static variable messing everything up Probably a very basic Java problem but I have two variables in a entity class:
public class Entity {

int posX;
int posY;

public Entity(int posX, int posY){
    this.posX = posX;
    this.posY = posY;
}

public void update(){

}

public void draw(Graphics2D g2d){

}

}
My player and enemy class extend it and then render off of the two variables. Like so:
public void draw(Graphics2D g2d) {
    g2d.drawImage(getPlayerImg(), posX, posY, null);
    if (showBounds == true) {
        g2d.draw(getBounds());
    }
}

I need to access these variables like this (This is in my enemy class):
public static void moveFemale(){
    if(posX <= Player.posX){
        //do AI code
    }
}

posX And Player.posX throw an error saying I need to change the modifier of posX in Entity.java to static. But when I change it to static, my renderer for the enemy class stops working and the enemies no longer show up on screen. How could I go about creating a variable that allowed me to do this:
public static void moveFemale(){
    if(posX <= Player.posX){
        //do AI code
    }
}

And still render my enemies? Sorry for the wall of text and any answers would help a lot!

A: The moveFemale method is static so it needs to know which female to move. Either pass in a reference to the palyer or find a may to make the move methods non-static member methods of the player.

A: I think, you should remove modifier static from method moveFemale
 public void moveFemale(){
    if(posX <= Player.posX){
        //do AI code
    }
  }


text:
Q: How to wrap a div vertically only? As the title says, I want to wrap a div vertically around an image, but I want the width to remain fluid and changeable:
|_________________|
|     |XXXXXX|    |
|     |XXXXXX|    |
|     |XXXXXX|    |
|     |XXXXXX|    |
|     |XXXXXX|    |
|     |XXXXXX|    |
|-----------------|

Where the box is the container and the content is the block of characters. The bottom and top sides should meet with the content block, I want the content to center (margin: 0 auto;).

A: This is what you want? DEMO
Try resize the output section in the fiddle and you will see that the content will always be in the center.
Here's the CSS:
.container {
    height: 300px;
    text-align: center;
    background: #CCC;
}

.inner {
    height: 100%;
    width: 300px;
    display: inline-block;
    border: 1px solid black;
}


text:
Q: Service account secret is not listed. How to fix it? I have used kubectl create serviceaccount sa1 to create service account. Then I used kubectl get serviceaccount sa1 -oyaml command to get service account info. But it returns as below.
apiVersion: v1
kind: ServiceAccount
metadata:
  creationTimestamp: "2022-05-16T08:03:50Z"
  name: sa1
  namespace: default
  resourceVersion: "19651"
  uid: fdddacba-be9d-4e77-a849-95ca243781cc

I need to get,
secrets:
- name: <secret>

part. but it doesn't return secrets. How to fix it?

A: In Kubernetes 1.24, ServiceAccount token secrets are no longer automatically generated.  See "Urgent Upgrade Notes" in the 1.24 changelog file:

The LegacyServiceAccountTokenNoAutoGeneration feature gate is beta, and enabled by default. When enabled, Secret API objects containing service account tokens are no longer auto-generated for every ServiceAccount. Use the TokenRequest API to acquire service account tokens, or if a non-expiring token is required, create a Secret API object for the token controller to populate with a service account token by following this guide. (#108309, @zshihang)

This means, in Kubernetes 1.24, you need to manually create the Secret; the token key in the data field will be automatically set for you.
apiVersion: v1
kind: Secret
metadata:
  name: sa1-token
  annotations:
    kubernetes.io/service-account.name: sa1
type: kubernetes.io/service-account-token

Since you're manually creating the Secret, you know its name: and don't need to look it up in the ServiceAccount object.
This approach should work fine in earlier versions of Kubernetes too.


text:
Q: WCF app.config for release and for test For example in Web.config it is possible to have Web.Release.config
where is some database connection defined like:
<connectionStrings>
   <!-- live db connection -->
</connectionStrings>

and Web.Test.config with:
<connectionStrings>
   <!-- test db connection -->
</connectionStrings>

Question: is is possible to make the similar construction for app.config to consume different Services depending on build target?
Background information: if I use Add Service Reference... in Visual Studion than some URL is used and it generate
endpoints:
<endpoint address />

To switch to other endpoint I have to change app.config manually or generate new Service Reference

A: Yes, there is a plugin to visual studio called SlowCheetah that add config transform capabilities to app.config files, just the same way as it works for web.config. It's very useful - I don't understand why it isn't included as default functionality in Visual Studio.


text:
Q: r is undefined, obtain all roles user has I am trying to make when the user posts the command, they are able to swap between roles at will. The roles are simply colors for the server I am making it for. The part that is having issues is the first part before the "var args" part. Basically, the part that finds all roles the user is currently in and removes them before moving onto adding the new role is where the problem is.
I got the bot working to add roles. Then I knew I needed to remove all old roles in order for the new color (which might be lower in hierarchy) might not show up.
The error to the code below is "(node:181764) UnhandledPromiseRejectionWarning: ReferenceError: r is not defined." I took that part right off anidiotsguide. I am learning js as is. Figured this small project would be simple to give me a little experience with discord.js. Apologies if I look like a complete novice. I am. lol Appreciate the help in advance.

bot.on('message', async (message) => {

  if(message.content.toLowerCase().startsWith("!colorme"))
  if(message.member.roles.some(r => ["blue", "red", "yellow"].includes(r.name)))
  await(message.member.removeRole(r.name));

  {
    var args = message.content.toLowerCase().split(" ");
    console.log(args);
    if(args[1] === "blue")
  {
      var role = message.guild.roles.find('name', 'blue');
      console.log("Role found!");
      message.member.addRole(role.id);
      message.channel.send('Role successfully added!');
  }
  else if(args[1] === 'red')
  {
    addUserRole('red', message);
    message.channel.send('Role successfully added!');
}
else if(args[1] === 'yellow')
  {
    addUserRole('yellow', message);
    message.channel.send('Role successfully added!');

    }
  };
});

function addUserRole(roleName, message)
{
  var role = message.guild.roles.find('name', roleName);
  message.member.addRole(role.id);
  return;
}

A: You used the .some method not correctly. Take a look at it here.
I used .array for your roles collection of the guildmember, it's the same as the .some method of discord.js (Proof: https://i.imgur.com/5aXu1wj.png)
Try the following code:
bot.on('message', async (message) => {

    if(message.content.toLowerCase().startsWith("!colorme"))
    message.member.roles.array().some(r => {
        if (["blue", "red", "yellow"].includes(r.name)) {
            message.member.removeRole(r);
        }
    })

    {
      var args = message.content.toLowerCase().split(" ");
      console.log(args);
      if(args[1] === "blue")
    {
        var role = message.guild.roles.find('name', 'blue');
        console.log("Role found!");
        message.member.addRole(role.id);
        message.channel.send('Role successfully added!');
    }
    else if(args[1] === 'red')
    {
      addUserRole('red', message);
      message.channel.send('Role successfully added!');
  }
  else if(args[1] === 'yellow')
    {
      addUserRole('yel', message);
      message.channel.send('Role successfully added!');

      }
    };
  });

  function addUserRole(roleName, message)
  {
    var role = message.guild.roles.find('name', roleName);
    message.member.addRole(role.id);
    return;


text:
Q: How to get google sheets script working on mobile app? I've perused the forum and haven't found any definitive answers (other than to write an Android script, but I have an iPhone). From what I've read on this wonderful forum, the onEdit and onChange triggers should work on the mobile app.
My script works fine when I use the desktop app. However, when I use the Google Sheets mobile app, the scripts do not run. How can I get them to run?
This solution was to create an Android add-on, but I have an iPhone. Maybe this is a stupid question, but can I run an Android add-on on my iPhone Google Sheets mobile app? I'd assume no since the OSs are incompatible, but weirder things have happened.
This solution says to change the simple onEdit trigger to an installable one. What is an installable trigger?
This solution says to create a web-app using Google's Execution API. Not sure how to do this.. I thought I already did. Within script editor> Publish > Deploy as web app. I've also done Publish > Deploy as API executable. Am I doing something wrong?
Does this mean scripts just don't work on the iOS Google Sheets mobile app?
My script:
function onEdit(){
  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("pss");
  var lr = ss.getLastRow();
  var range = ss.getRange("A2:J" + lr);
  var vlst = range.getValues();

  range.setValues(vlst);
  var i,j,a,find,repl;
   for (var i = 0; i < vlst.length; i++){
    for (var j = 0; j < vlst[i].length; j++){
      a = vlst[i][j];
      if (a == find) vlst[i][j] = repl;
    find ="sun";
    repl ="sunshine";
    }
  }

A: Not sure what I did, but now my onEdit trigger works on mobile! Might have been activating Deploy as API executable with delayed activation? Not sure what happened, but now the onEdit trigger works and I'm getting emails from Google Sheets with fail reports. Not sure why Google Sheets is sending me fail reports when the trigger is successful, but I'm not going to complain now that it works!
What also might be the solution was that I added the installation code:
function createTriggers() {
  ScriptApp.newTrigger('onMyEdit')
    .forSpreadsheet(SpreadsheetApp.getActive())
    .onEdit()
    .create();
}

If your triggers aren't working on the iPhone Google Sheets app, then try activating Deploy as API executable. It's found within the Script Editor under Publish and also add the installation code to your script


text:
Q: How to apply a custom option to all products in Magento I'm having problem with my new magento site, I want to apply a custom option to all the products on my site. Basically I want to add the custom pricing option for large sizes (my site is about motorcycle leather jackets etc), so if someone chooses a size that requires extra amount, there should be an option for that. I can apply this option to one product at a time. Does somebody know how to apply this to all products at one? Here's the link for my site: http://www.lopeholt.com
Thanks in advance.

A: There's no simple hack to do this.
However, there is a free extension to copy custom options to multiple products which could help you to save lots of work:
http://www.magentocommerce.com/magento-connect/medma-copy-delete-custom-options-on-multiple-products.html
Update: extension isn't free anymore.

A: If you want to add custom options to multiple products,same functionality is provided by following extension which could help to save your time to assign custom options to multiple products.
You can also set custom option for different sizes(large sizes).
http://www.magentocommerce.com/magento-connect/custom-option-manger.html

A: If you want to do this completely for free without relying on extensions you can use Magmi. It takes a little while to get used to but it allows you to import almost anything for your product database - here's the link to the Magmi tutorial:
https://understandinge.com/course/importing-products-magento/
Link to the Custom Options upload instructions:
http://wiki.magmi.org/index.php?title=Custom_Options#File_to_upload_field