text:
Q: Probability of Getting a Red Ball after Selecting from Three Bins I'm trying to calculate probabilities based on a random choice algorithm, and I'm a bit confused about some of the math. Here's the scenario:
Let's say I have three bins (could be any number, but let's say three), and each bin is filled with red, green, and blue balls.
The distribution of balls in the bins are:

*

*Bin 1

*

*Red: 5 (50%)

*Green: 5 (50%)

*Blue: 0 (0%)

*Bin 2

*

*Red: 8 (80%)

*Blue: 2 (20%)

*Bin 3

*

*Red: 4 (40%)

*Blue 6 (60%)

If you were to choose one ball from each bin in succession, I'm trying to figure out how likely it would be for you to have gotten a particular ball. In the above example, you would have chosen one ball per bin, for a total of three balls. So, with those three balls, what is the chance that you have a red ball, or the chance you have a green ball, or the chance you have a blue ball?
Based on a discussion here, it seems the best way to do this is multiply all the probabilities that I won't get what I want, and then just subtract that probability from 100%.
Based on that, I calculated these probabilities:
Probability of red ball: (1.0 - (0.5 * 0.2 * 0.6)) = 0.94 = 94%

Probability of green ball: (1.0 - (0.5 * 1 * 1)) = 0.5 = 50%

Probability of blue ball: (1.0 - (1 * 0.8 * 0.4)) = 0.68 = 68%

Are these results correct? I was a bit surprised by the outcomes. Are the total probabilities supposed to add to 100% in this scenario?

A: If you have to pick a ball from each bin, the probability to get e.g. one red ball is the following:
$P(\text{one red ball})=P(\text{one red ball in bin 1}, \text{no red balls in bin 1 or 2}) + P(\text{one red ball in bin 2}, \text{no red balls in bin 1 or 3}) + P(\text{one red ball in bin 3, no red balls in bin 1 or 3})$
As a pick in each bin does not influence the remaining two bins, you can e.g. calculate (due to independence):
$P(\text{one red ball in bin 1}, \text{no red balls in bin 1 or 2})
=
P(\text{one red ball in bin 1})\cdot P(\text{no red balls in bin 1})\cdot P(\text{no red balls in bin 2})
=
\frac{1}{2}\cdot\frac{1}{5}\cdot\frac{3}{5}
=
\frac{3}{50}
=
0{,}06.
$
All in all you would get:
$P(\text{one red ball})
=
0{,}06 + 0{,}24 + 0{,}04
=
0{,}34.
$
Similarly (and easier),
$P(\text{one blue ball})
=
0{,}56.
$
Similarly (and much easier),
$P(\text{one green ball})
=
0{,}5.
$
Note that the probability of the events do not add up to $1$ as the events do not form a disjoint partition of the possible outcomes.
You are instead computing the probability of at least one e.g. red ball. For the green ball, where you can at most have one, we arrive at the same probability. But for say the red ball, there is a high probability to obtain two or even three balls, which you do not take into account.
Mathematically, you are stating that
$P(\text{one red ball}) = 1 - P(\text{no red ball})
= 1 - P(\text{no red ball in bin 1}) \cdot P(\text{no red ball in bin 2}) \cdot P(\text{no red ball in bin 3}).
$
But the first equality is not true. We have $P(A) = 1 - P(A^c)$ where $A^c$ is the complement of $A$. The complement of $\text{one red ball}$ is not $\text{no red ball}$ but $\text{no red ball or two or three red balls}$.


text:
Q: Reading an attachment that gmail doesn't render I was recently sent an email attachment that Gmail doesn't render. It's very important that I get access to this attachment, but I can't for the life of me figure out how. I know that the attachment was sent because I looked at the plain text, and saw this:
--001636e0b0a2d5b97304a97d51d0
Content-Type: image/gif; name="image001.gif"
Content-Transfer-Encoding: base64
Content-ID: <image001.gif@01CC487A.BD9DFF00>
X-Attachment-Id: 8178a39d9dae1f7_0.1

R0lGODlhyADIAJH/AP//////zMzM/8zMzCwAAAAAyADIAEAC/4SPqcvtD6OctNqLnQDb9vMhAxAI

(Continues like above for some time)

UJcLcq+Jc5WnVxorp4tjJue42NYKmQ00ZcmuiGKcK1ZC7lQFiQAAOw==
--001636e0b0a2d5b97304a97d51d0--

Note, to cut down on the size of this, and to ensure some privacy for what was emailed, I've omitted what is around maybe 500 lines of similar looking text.
So, my question is, how can I recover this image? I'm sure there has to be a way, that I'm not the only user to ever face this problem, but I'm having problems figuring it out.

A: You could perhaps feed the text after X-Attachment-Id: 8178a39d9dae1f7_0.1 to a base64 decoder & save the recoded.. content as an image file?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to convert decimal number to binary number? How can I convert a decimal number to binary number in erlang, example:
convert(10) =  [0,1,0,1]

Thank you.

A: You can convert the integer to a string in arbitrary base using integer_to_list/2, then subtract $0 from each character to convert the characters to their integer value (will only work for bases < 10), and finally reverse it:
1> A = 10.
10
2> lists:reverse([N - $0 || N <- integer_to_list(A, 2)]).
[0,1,0,1]
3> B = 1234.
1234
4> lists:reverse([N - $0 || N <- integer_to_list(B, 2)]).
[0,1,0,0,1,0,1,1,0,0,1]


text:
Q: Who are the hidden team members on the GTA Online: The Diamond Casino Heist? On the new casino heist, there are some team members that appear with a "hidden" icon and can't be selected. Who are the hidden members? How can I unlock them?

A: The hidden/unlockable crew members are:
Gunmans
Charlie Reed
Requires purchase of a Hangar.
Chester McCoy
Requires purchase of a Bunker or Arena Workshop.
Patrick McReary
Requires completion of freemode event, where you steal a police vehicle with Packie on the back and drop him in the designated location after losing the cops.

Drivers
Zach Nelson
Requires purchase of the MC Clubhouse.
Chester McCoy
Requires purchase of a Bunker or Arena Workshop.

Hackers
Yohan Blair
Requires purchase of the Nightclub.
Paige Harris
Requires purchase of the Terrorbyte.
Avi Schwartzman
Requires the destruction of all 50 Signal Jammers around the map.


text:
Q: How to keep the Lived documents in MongoDB as per the TTL index? I know that the TTL index in MongoDB set a time to live for its documents. When they live for the specified time then those documents gets deleted. So what if I want to archive those documents without losing them. is there any way to do it?
I am sorry If I asked it in the wrong place.

A: You can use a change stream to capture documents inserted and archive them somewhere. See also this answer on stackoverflow.

A: At the start you have a document with "column" (timestamp) that is in the TTL index. To prevent its deletion, you can move that timestamp to the future, or remove that "column" from the document.


text:
Q: Create an SSH connection via wireless router I would like to create an SSH connection with a wireless router I got from BT. Any Idea how I can do this?. I want to use this SSH connection to connect to my home server.
I want to connect from outside my home to the wireless router that is connected to my home server with Linux based operating system.
Thanks in advance

A: I think you mean that you want to connect to the home server from outside your home, correct? You don't really connect via SSH to the router for this; you just tell the router to pass the connection on to the home server. If this is the case, read on. If not, clarify the question even more.
You will have to tell the router to pass incoming traffic on the SSH port on to your internal server. This is usually called "port forwarding" or similar. See Google or perhaps http://www.portforward.com/ for specific guides for your router on how to accomplish this. It is usually handled via some web interface that you see when you enter the routers internal IP address (usually 192.168.0.1 or 192.168.1.1) in a browser from within the home network.
Forward e.g. port 22 for the TCP protocol (the standard SSH port) from your router to your home server. After this is done, and you have an SSH server running on your server, you can just connect via SSH to your external IP (which is "owned" by the router), which will forward the connection to the server.


text:
Q: Yii URL Management HTTPS Im using a code to separate pages that is HTTPS and HTTP in my website
The problem is: When Im on HTTP, links to HTTPS no have WWW and vice versa.
I did not find the problem in the script.

public function createUrl($route, $params = array(), $ampersand = '&')
{
    $url = parent::createUrl($route, $params, $ampersand);

    // If already an absolute URL, return it directly
    if (strpos($url, 'http') === 0) {
        return $url;
    }

    // Check if the current protocol matches the expected protocol of the route
    // If not, prefix the generated URL with the correct host info.
    $secureRoute = $this->isSecureRoute($route);
    if (Yii::app()->request->isSecureConnection) {
        return $secureRoute ? $url : 'http://' . Yii::app()->request->serverName . $url;
    } else {
        return $secureRoute ? 'https://' . Yii::app()->request->serverName . $url : $url;
    }
}

public function parseUrl($request)
{
    $route = parent::parseUrl($request);

    // Perform a 301 redirection if the current protocol
    // does not match the expected protocol
    $secureRoute = $this->isSecureRoute($route);
    $sslRequest = $request->isSecureConnection;
    if ($secureRoute !== $sslRequest) {
        $hostInfo = $secureRoute ? 'https://' . Yii::app()->request->serverName : 'http://' . Yii::app()->request->serverName;
        if ((strpos($hostInfo, 'https') === 0) xor $sslRequest) {
            $request->redirect($hostInfo . $request->url, true, 301);
        }
    }
    return $route;
}

private $_secureMap;

/**
 * @param string the URL route to be checked
 * @return boolean if the give route should be serviced in SSL mode
 */
protected function isSecureRoute($route)
{
    if ($this->_secureMap === null) {
        foreach ($this->secureRoutes as $r) {
            $this->_secureMap[strtolower($r)] = true;
        }
    }
    $route = strtolower($route);
    if (isset($this->_secureMap[$route])) {
        return true;
    } else {
        return ($pos = strpos($route, '/')) !== false
            && isset($this->_secureMap[substr($route, 0, $pos)]);
    }
}

}
Code adapted from: http://www.yiiframework.com/wiki/407/url-management-for-websites-with-secure-and-nonsecure-pages/

A: It's better to manage this at the controller level using filters.
In your components directory setup 2 filters HttpsFilter and HttpFilter as follows:-
class HttpsFilter extends CFilter {

    protected function preFilter( $filterChain ) {
        if ( !Yii::app()->getRequest()->isSecureConnection ) {
            # Redirect to the secure version of the page.
            $url = 'https://' .
                Yii::app()->getRequest()->serverName .
                Yii::app()->getRequest()->requestUri;
                Yii::app()->request->redirect($url);
            return false;
        }
        return true;
    }

}

and
class HttpFilter extends CFilter {

    protected function preFilter( $filterChain ) {
        if ( Yii::app()->getRequest()->isSecureConnection ) {
            # Redirect to the secure version of the page.
                $url = 'http://' .
                Yii::app()->getRequest()->serverName .
                Yii::app()->getRequest()->requestUri;
                Yii::app()->request->redirect($url);
            return false;
        }
        return true;
    }
}

then in each controller force https using the filters, optionally by action:
class SiteController extends Controller {

    public function filters()
    {
        return array(
            'https +index', // Force https, but only on login page
        );
    }
}

Edit: if the filters() function above doesn't seem to work for you, instead try
return array(
           array('HttpsFilter +index'), // Force https, but only on login page
       );

See http://www.yiiframework.com/doc/guide/1.1/en/basics.controller#filter (and comments on it).


text:
Q: AS3 regex - how to match 2 consecutive matches multiple times? I have the following regex, which will match all the
 and
 tags in a string:
/
/gi

I actually want to match every set of two consecutive tags, with valid matches being:

(and all variations with a space before the slash)

Obviously I can just double up the expression to /

/gi, but is there a shorter way of taking the first expression and saying "this, but twice"?

A: Try this one:
/(
){2}/gi


text:
Q: Google Directory API always return 403 when using OAuth2.0 even after user consent I am working on a web app and struggling with Google Directory API.
The app is trying to get the list of the google groups user belongs to with the simple code as following:
from apiclient import discovery
from google.appengine.api import users
from oauth2client.appengine import OAuth2DecoratorFromClientSecrets

def decorator():
    ....(some scopes including admin.directory.group)
    return decorator

class MainHandler(webapp2.RequestHandler):
    @decorator.oauth_required
    def get(self):
        me = users.get_current_user()

        http = oauth_decorator.http()
        service = discovery.build('admin', 'directory_v1', http=http)
        grouplist = service.groups().list(userKey=me).execute()
        ....

This results in 403 Not Authorized to access this resource while Admin SDK is enabled. There are a lot of questions report similar problems but the major difference is I am trying to use OAuth2.0 instead of using service account, which means the user need explicitly consent and grant the authority I ask for.
So my guessing is for some reason, the request is not with the proper user authorization code, but I have no idea how I can prove my suspicion and how I can make it work. Any suggestions? Much thanks in advance!

A: I contacted Google and it turns out to be that I need to be domain administrator in order to use ANY Admin APIs listed.
Not quite feasible in my case, so I am trying to find ways around.

A: Since there is a scope defined for each API, the admin will need to grant a consent for it at the time of token generation.  If you are using OAuth2.0, once you generate a refresh token, you are good to go.


text:
Q: MySQL Allow User use of WHERE but deny SELECT I created a User that has privileges to Select the column username and the column ip. Also he has rights for INSERT and UPDATE for column ip.
My Problem is that he should be able to do the following:
[1] UPDATE table SET ip='localhost'  WHERE key = "XXXXXXXX"
but should be denied to do:
[2] SELECT key from table
If I give him SELECT rights for column key hey can do [2], if I revoke the rights I get:
SELECT command denied to user 'username'@'localhost' for column 'key' in table 'table'

Is there something I can do to fix that?

A: @MichaelBerowski Your tip with the stored procedure was great.
I created the following procedure and it works great.
I only had to give him rights to execute this procedure but he doesn't need Select,update,insert permissions anymore.
CREATE PROCEDURE update_ip(
IN p_ip varchar(15),
IN p_key varchar(50))
BEGIN
UPDATE table SET ip = p_ip WHERE key = p_key;
END


text:
Q: How to keep a message in console? (JS function) I have a JavaScript function which encrypts a text using the Caesar Cipher.
I also have an HTML form which sends data to PHP, the PHP uses echo to print it into div elements, and then, whe I press another button (not input), it calls the "Caesar Cipher" function (which receives the value of the divs with DOM).
The problem is that when the function does its job, it uses console.log to print it into the console - but when it prints, it only does for a half-a-second, after that the message disappears.
I think it has something to do with the page reloading or something, so if you could please explain me what to do to fix it, and why - I'd thank you very much!
HTML & PHP:
<form style="display: inline-block" method="get" action="index.php">
    <fieldset>
        <legend>Caesar Cipher</legend>
        <input type="text" name="text">
        <input type="number" name="shift">
        <input type="submit" name="submit">
        <button onclick="caesarCipher(1)">Encrypt</button>
            //the value 1 means that the function will encrypt, and not decrypt
    </fieldset>
</form>

<div id="text">
    <?php
        if(isset($_GET["submit"])) { //when the submit (input) button is pressed
            $text = $_GET["text"];
            echo htmlspecialchars($text);
                //set div (id="text") innerHTML (DOM) the value of the input field
        }
    ?>
</div>

JavaScript:
function caesarCipher(dir) {
    //the function takes a text, enters every letter into an array,
    //and then shifts it using the letters array (with their index)
    //it logs the array (array.join("")) into the console - here is the problem

    text = document.getElementById("text").innerHTML.trim().toLowerCase();
    shift = 3;
    var letters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
    var charArray = [];
    for(var i = 0; i < text.length; i++) {
        var letter = text.charAt(i);
        if(letter == " ")
            letter = " ";
        else {
            var index = letters.indexOf(letter);
            if(dir > 0)
                index = (index + shift) % 26;
            else {
                index -= shift;
                if(index < 0)
                    index += 26;
            }
        letter = letters[index];
        }
        charArray[i] = letter;
    }
    console.log(charArray.join(""));
}

A: In Google Chrome you can press F12 or Ctrl+Shift+J key to show sidebar as in the picture and check Preserve Log checkbox to preserve log messages.

Similar option exists in others browsers also.

A: Tick the Preserve Log checkbox.
Also,
<!-- This is how you comment in HTML -->

A: Why don't you use the localStorage?
localStorage.setItem('encString', charArray.join(""));
// whenever you want to see it, even after a window reload
console.log( localStorage.getItem('encString') );


text: Q: whitelist firebase functions in MSSQL? Have an API done in firebase functions where I'm trying to connect to MSSQL but the firewall on the server is using a whitelist which make it difficult. I can not find my firebase functions IP(to add to whitelist) and attempt to ping URL was unsuccessful as well (getting error "ping request could not find host"). Any suggestions?


text:
Q: How can I modify html from an ajax call before adding it into document? I'm performing an ajax call to grab an HTML page from the server;  ajax call looks like this:
function loadHtml() {
    $.ajax({
          type          :  'GET',
          async         :  false,
          url           :  'my.html',
          contentType   :  'text/html',
          dataType      :  'html',
          success       :  function(data) {
              loadedHtml = data; // the loadedHtml variable is global
          }
    });
}

Later, I'd like to display this html after modifying it somewhat.

Attempt 1
I tried this, but the resulting screen shows nothing at all (body contains no html).
var myContent = $(loadedHtml).find('#test1').text("Modified!");
$('body').html(myContent);

Attempt 2
I also tried this, but the resulting screen just shows the original content of loadedHtml.
var myContent = $(loadedHtml);
myContent.find('#test1').text("Modified!");
$('body').html(myContent);

Original Html
Here's the original content of loadedHtml from my.html

 Working!

What am I doing wrong?

UPDATES

*

*This is a simple example I'm trying to get to work before adding the complexity of what I really need to be doing.  So, using a simple string replace on the loadedHtml variable before inserting it into the DOM is not something that will work for me.

*I've updated my code to show the ajax call is synchronous.  the loadedHtml variable does in fact contain the html from the server by the time I get to the point I'm trying to modify it.

A: You misuse the find function:

Given a jQuery object that represents a set of DOM elements, the .find() method allows us to search through the descendants of these elements in the DOM tree and construct a new jQuery object from the matching elements. The .find() and .children() methods are similar, except that the latter only travels a single level down the DOM tree.

It search only descendants, In your case #test1 isn't a child...
so this:
$('
 Working!
').find('#test1')

Won't grab the test1 element, it's not a  descendant.

A: O.K.  If I "read" the question + comments right, Your code is outside the success function.
You guys have to remember. ajax is async!  move your code inside the success handler.
"The 'A' in AJAX stands for asynchronous."

But how can the response be used in context of a function? Consider this flawed example where we try to update some status information on the page:

function updateStatus() {
     var status;
     $.ajax({
         url: 'getStatus.php',
         success: function(response) {
             status = response;
         }
     });
     // update status element?  this will not work as expected
     $('#status').html(status);
}

The code above does not work as desired due to the nature of asynchronous programming. The provided success handler is not invoked immediately, but rather at some time in the future when the response is received from the server. So when we use the 'status' variable immediately after the $.ajax call, its value is still undefined. The next snippet shows how we can rewrite this function to behave as desired:

function updateStatus() {
     $.ajax({
         url: 'getStatus.php',
         success: function(response) {
             // update status element
             $('#status').html(response);
         }
     });
}

jQuery FAQ

A: Supposing you've already managed to print loadedHtml in the first place (and that there's nothing wrong with your AJAX call), try this...
loadedHtml.replace("test1","modified");

And print it out... ;-)


text:
Q: How to Link Windows credentials with Logged in User in Jenkins for running Powershell script I am trying to run some of the SQL SERVER command using Powershell script by enabling Integrate Security on (Expecting to connect SQL server using Winodows Access) and calling that powershell script into Jenkins Pipeline but its throwing me error as "Unable to connect to target server 'ABC\SQL17'. Please verify the connection information such as the server name, login credentials, and firewall"
I have followed following steps as try
 1. Created Jenkins Job as "Jenkins Pipeline"
 2. Called Groovy script under Pipeline script to call Powershell script.
 3. Added Credentials my windows login details as Global and linked this credentials with Jenkins logged in user.
 4. And scheduled job with same user.
I want Jenkins to use my windows credentials to run this powershell but that is not using the same which I have given and its throwing error as User do not have access
Following is sample script I have used to call powershell using batch file in groovy script
node {
    stage('Deploy Dacpac to SQL Server') {
        script{
        bat 'start cmd.exe /c D:\\Source\\Test.bat'
        }
    }
}

Please advise how can I use my credentials to run such script.
Thank you in advance for your responses !

A: After hunting few articles and blogs I got solution for this, I have changed project type from Pipeline to Free Style project and directly called power shell script under Build Step tab.
And Used Secret Key from build Environment and provided two variable to stored user name and password with encryption(Use Credential plugin for encryption and masked password ).
Snapshot for configuration
You can use script as below
$SrvPassword = ConvertTo-SecureString "$($ENV:SrvPassword)" -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential ("$ENV:SrvUser", $SrvPassword)
$SessionDetails = New-PSSession -ComputerName "ServerName" -Credential $Credential

Invoke-Command -Session $SessionDetails -Command {
C:\Test.ps1
}


text:
Q: Switching to Vertica from MySql, aggregate in where clause not working Recently we have switched to Vertica from MySQL. I am lost on how to re-create the <=30 check inside the where clause in the query below. This currently does not work in Vertica, but does in MySQL.
Essentially, a user owns cars and cars have parts. I want to total the amount of cars and car parts in a timeframe, but only for users who have less than or equal to 30 cars.
select
    count(distinct cr.id) as 'Cars',
    count(distinct cp.id) as 'Car Parts'
from
    users u
inner join
    user_emails ue on u.id = ue.user_id
inner join
    cars cr on cr.user_id = u.id
inner join
    car_parts cp on cp.car_id = cr.id
where
    (
        select count(*) from cars where cars.user_id=u.id
    ) <=30
and
    ue.is_real = true and ue.is_main = true
and
    cr.created_at >= '2017-01-01 00:00:00' and cr.created_at <= '2017-02-17 23:59:59'

Any help or guidance is greatly appreciated!
Before my mouse flies away and my monitors goes blank, I get this error:

ERROR: Correlated subquery with aggregate function COUNT is not supported

A: You would use a subquery this way.  You would use a window function:
select count(distinct cr.id) as Cars,
       count(distinct cp.id) as CarParts
from users u join
     user_emails ue
     on u.id = ue.user_id join
     (select cr.*, count(*) over (partition by user_id) as cnt
      from cars cr
     ) cr
     on cr.user_id = u.id join
     car_parts cp
     on cp.car_id = cr.id
where cr.cnt <= 30 and
      ue.is_real = true and ue.is_main = true
      cr.created_at >= '2017-01-01' and
      cr.created_at < '2017-02-18';

Notes:

*

*Don't enclose column aliases in single quotes.  That is a bug waiting to happen.  Only use single quotes for string and date constants.

*You can simplify the date logic.  Using < is better than <= to capture everything that happens on a particular day.


text:
Q: Is $C^1(A)$ a Banach space? Let $A \subset \mathbb R$ and consider the space $C^1(A)$. I am asked to prove that $( C^1(A), \Vert \cdot \Vert_{C^1(A)})$ is a Banach space, where
$$
\Vert f(x) \Vert_{C^1(A)} = \sup_{x \in A} \vert f(x) \vert + \sup_{x \in A} \vert f'(x) \vert
$$
First question: $A$ should be compact (or at least closed set), shouldn't it?
Secondly, how would you prove this? I've taken a Cauchy sequence, $(f_n)_{n \in \mathbb N} \subseteq C^1(A)$: if I fix $x \in A$, then I obtain two Cauchy sequences $(f_n(x))$ and $(f'_n(x))$  in $\mathbb R$ (?) so they converge to two numbers, $f(x)$ and $f'(x)$. The function $f$ that I obtain is the pointwise limit: how can I prove that this gives me exactly the $C^1(A)$ limit?
I've still one more question: is $( C^1(A), \Vert \cdot \Vert_{\infty})$ still a Banach space? I did not manage to find a counterexample...
Thanks for your help.

A: If you already know that $C^0$ is a Banach space, and if $f_n$ is Cauchy in $C^1$, then you already do know that $f_n$ and $D_i f_n$ converge uniformly to continuous functions $f, g_i, 1\le i\le n$. You then only have to show that in this case $f$ is differentiable and $D_i f = g_i$. Which theorems do you know about sequences of differentiable functions and the differentiability of the limit?
$(C^1, ||.||_\infty)$ is not a Banach space, consider a sequence of smooth functions converging to $x\mapsto |x|$ on $[-1,1]$ (e.g. polynomials, which are known to be dense in $C^0$).
Since this is homework I deliberately ignore your question about compactness of $A$ and suggest you check corresponing statements for $C^0$ and see whether they carry over. (Note, though, that you usually define differentiability on open sets).

A: I think I have found a counterexample which shows that $C^1([-a;a], \mathbb R)$ ($a \gt 0$) with the sup-norm is not a Banach space (at the endpoints I mean the one-sided derivatives).
Let's define $f_n \colon [-a,a] \to \mathbb R$ by
$$
f_n(x)=\vert x \vert^{1+\frac{1}{n}}
$$
By direct calculation, we can see that $f'_n(0)=0$ for every $n \in \mathbb N$. Therefore, we can say that $(f_n)_{n \in \mathbb N}$ is a sequence in $C^1([-a,a])$. The pointwise limit is clearly the function $f \colon x \mapsto \vert x \vert$.
Indeed, the limit is  also uniform: to prove this, we observe that $(f_n)_{n \in \mathbb N}$ is increasing. Since the limit function is continuous and the space $[-a,a]$ is compact then, by Dini's theorem, we can conclude that the convergence is uniform, i.e. sup-norm convergence. To conclude, just note that the limit function $f \notin C^1([-a,a])$.


text:
Q: How to store datatable data for Next button click using Angular Trying to push row data to the array for every click, like by default loading datatable contains 300 records, if we click on Next button again 300 records should push to the array and displaying 300+ 300 = 600 records in the table. Tried below code but unable to push the data to the array. In console.log im getting 600 records, but table loaded only 300 records. Pls suggest me.
loadTable(){

let params = new HttpParams()
 let self = this;
    this.dtOptions = {
      pagingType: "full_numbers",
      pageLength: 10,
       stateSave: true
    };
     dataUrl =
      "https://raw.githubusercontent.com/l-lin/angular-datatables/master/demo/src/data/data.json";

  this.http.get(dataUrl).subscribe(response => {
      this.persons = response.data;
      this.persons.forEach(f => (f.checked = false));
      this.dtTrigger.next();
    });
  }
  getAllrecords(){
    this.persons2 = this.persons;
    this.http.get(dataUrl).subscribe(response => {
    this.persons1 = response.data;
    this.persons3 = this.persons1.concat(this.persons2);
    this.persons = this.persons3;
    console.log(JSON.stringify(this.persons));
    this.dtTrigger.next();
  });

}
Demo

A: How I did this was with checking if we are at last page. then change next to load more. and on next click add new handler to load.
Here is sample implementation
DataTable = $('#tableId').DataTable({...})
DataTable.on('draw', function () {
            var info = ProductDataTable.page.info();
            if (info.page + 1 === info.pages) { // Checking if at last page
                $('#tableId_next').removeClass('disabled')
                $('#tableId_next').on('click', () => {
                    //fetch your data here
                    DataTable.rows.add(data).draw();
                 });

                })
                $('#productTable_next a').text("Load More");
            }
            $('#productTable_info').html('Showing ' + (info.page * info.length + 1) + '-' + ((info.page + 1) * info.length) + ` of ${info.recordsTotal} Entries.</span>' :''}`);
        });

after draw the (next) handler goes back to normal.


text:
Q: Why does Rust allow public access to a private module? I am a newbie in Rust and just started to read the programming book while doing rustling exercises. In the modules2.rs exercise, I am confused why the following code compiles:
mod delicious_snacks {
    pub use self::fruits::PEAR as fruit;
    pub use self::veggies::CUCUMBER as veggie;

    mod fruits {
        pub const PEAR: &'static str = "Pear";
        pub const APPLE: &'static str = "Apple";
    }

    mod veggies {
        pub const CUCUMBER: &'static str = "Cucumber";
        pub const CARROT: &'static str = "Carrot";
    }
}

fn main() {
    println!(
        "favorite snacks: {} and {}",
        delicious_snacks::fruit,
        delicious_snacks::veggie
    );
}

Specifically, I am wondering why it is OK for main to access private fruits and veggies modules just because their uses are marked pub? On the other hand, if we don't use pub use, then, without making fruits and veggies pub, one cannot access e.g., delicious_snacks::fruits::PEAR in main because fruits is not public. Similarly, if we don't use pub for const PEAR, even with pub use self::fruits::PEAR as fruit, we still cannot compile delicious_snacks::fruit. So what exactly is the rule here? Why is it OK to not mark pub for those modules?

A: The constants PEAR/APPLE/CUCUMBER/CARROT are marked as pub, which means they can be accessed from everywhere, even if they're in a private module.
This is a common technique, to implement something in a private module, and re-export only the things we want, e.g.
// actual implementation is here
mod foo_internal;

pub use foo_internal::{Foo, Bar};

This still maintains privacy/visibility, since Foo and Bar can't be re-exported if they're private.
You can also create a new module hierarchy for users of your library:
mod foo_internal;

pub mod foo {
    pub use foo_internal::Foo;
}

pub mod bar {
    pub use foo_internal::Bar;
}

This clearly separates the public interface from implementation details, so the implementation can be freely refactored without changing the public modules.


text:
Q: how to do a while loop on python the define x1, x2, x3, etc Hello I need to define a serie of data in python, like (x1=thing, x2=thing... to x100=thing) and I don't want to write all x(number). I tried with a loop like this
a=1
while(a<100):
    x'a'=thing
    a=a+1

but that doesn't work...
How do I do a loop that returns me this:
x1=thing
x2=thing
x3=thing
x4=thing
etc...

I don't need to print it, only to have de x(number) defined.
thanks people

A: You don't. That's not to say that you can't, but you DEFINITELY don't want to.
foo = []
for _ in range(100):  # do the following 100 times:
    foo.append("thing")
# or foo = ['thing' for _ in range(100)]
# or foo = ['thing'] * 100

This will give you a list named foo with the value "thing" in every element from 0 to 99.
foo[0]  # "thing"
foo[99] # "thing"
foo[100]  # throws an IndexError

The alternative would be to either directly manipulate the globals dict (which is a bad idea) or to play with exec (which is a VERY bad idea).
for num in range(1, 101):
    exec("x{} = 'thing'".format(num))
    # oh my God don't do this

for num in range(1, 101):
    globals()["x{}".format(num)] = "thing"
    # it's so ugly it burns!

That's not to say that exec is inherently bad, nor that directly manipulating the globals dict doesn't have its place. However if you're at the point of your education where you're still asking questions about Python on StackOverflow, you should not ever even consider using those approaches. At best it's an ugly hack where you should have done something else. At worst it will compromise your script and allow a malicious (or unwitting...read: yourself) user to do whatever it wants on your computer. That includes things like:
# WARNING, THIS CODE WILL TRASH YOUR COMPUTER
>>> exec(input("user input command> "))
user input command> import shutil; shutil.rmtree("C:/")
# DON'T COME CRYING TO ME WHEN YOUR SYSTEM WON'T BOOT

A: well thank you all!! turn out I didn't exactly knw how to use lists hahaha... this is what finally worked for me:
lina=[0,0]
linb=[0,0]
fig=plt.figure()
a=1
while(a<2):
   lina[a],=fig.add_subplot(111).plot(x,x, 'b^',markersize=20)
   linb[a],=fig.add_subplot(111).plot(x,x, 'rv',markersize=20)
   a=a+1


text:
Q: Solving the harmonic oscillator by using Hamilton-Jacobi formalism In order to solve the harmonic oscillator,
$$H=\frac{p^2}{2}+\frac{q^2}{2},$$
by using Hamilton-Jacobi theory we have to find a complete solution for the H-J equation,
$$\frac{1}{2}\left(\frac{\partial S}{\partial q}\right)^2+\frac{q^2}{2}+\frac{\partial S}{\partial t}=0.$$
We seek for a solution
$$S=W(q)+T(t),$$
which leads to the following ODE,
$$\frac{dT}{dt}=-\alpha t,$$
$$\frac{dW}{dq}=\sqrt{2\alpha-q^2}.\tag 1$$
It is easy to solve those equations and then write $S(q,\alpha,t)$, from which we can get
$$\beta=\frac{\partial S}{\partial \alpha}\Rightarrow q=\sqrt{2\alpha}\sin (t+\beta).$$
Now it comes my issue. When solving for momenta,
$$p=\frac{\partial S}{\partial q}=\frac{dW}{dq}=\sqrt{2\alpha-q^2},\tag 2$$
and using the solution found for $q$ we obtain
$$p=\sqrt{2\alpha}\sqrt{\cos^2(t+\beta)}=\sqrt{2\alpha}|\cos(t+\beta)|.$$
We know that the solution should be $p=\sqrt{2\alpha}\cos(t+\beta)$. I realize that even Eq. (2) is allowing only for positive momentum. So how to obtain the correct solution without forcing it by knowing the correct answer a priori?
Note that in obtaining (1) we actually should write
$$\frac{dW}{dq}=\pm\sqrt{2\alpha-q^2},$$
but yet there is an ambiguity with the plus or minus sign.

A: By making use of Hamilton's equation to the Hamiltonian given, yeilds: $\dot{q} = \frac{\partial H}{\partial p} = p$, which unambiguously implies $p = \sqrt{2 \alpha} \cos (t + \beta)$.


text:
Q: Creating a layout programatically using XML elements I've programmed one of my layouts programatically. And when I tried to implement it in XML I couldn't make it work. It crashes with NullPointerException and I really do not know why.
This is my XML layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".DisplayMessageActivity" >

<ImageView
    android:id="@+id/canal_1"
    android:contentDescription="@string/desc"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:onClick="canal1_Click"
    android:src="@drawable/pestanya_seleccionada" />

</RelativeLayout>

And what I'm trying is:
ImageView canal1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    /* layout prinicpal */
    RelativeLayout relativeLayout = new RelativeLayout(this);
    RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
    canal1 = (ImageView) findViewById(R.id.canal_1);
    relativeLayout.addView(canal1);
    setContentView(relativeLayout, rlp);
}

It crashes at relativeLayout.addView(canal1);
I don't why this fails. In my head everything should run fine.
Thanks for reading and hope you can help me ;)
Kind regards,
Raúl

A: You have not set content of the xml layout to the screen and you are finding the id of the ImageView. This is causing NPE.
 canal1 = (ImageView) findViewById(R.id.canal_1);

The above statement will cause nullpointerexception since you have not set the layout and your are trying to find the id form the defined in the xml file.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activty_main);
RelativeLayout rl = (RelativeLayout) findViewById(R.id.relativeLayout);
//add other ui elements to the root layout ie  RelativeLayout
}

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/relativeLayout"// relative layout id
android:orientation="vertical"
tools:context=".DisplayMessageActivity" >
<ImageView
android:id="@+id/canal_1"
android:contentDescription="@string/desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:onClick="canal1_Click"
android:src="@drawable/pestanya_seleccionada" />
</RelativeLayout>


text:
Q: How to use text/html in a BPMN documentation/textAnnotation element I am trying to create a custom format based on the BPMN 2.0 Interchange Format and I am wondering what BPMN tools are doing to support the textFormat attribute of the documentation and textAnnotation elements.
For example, I created a simple sample as follows:
<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL"
  id="Definitions_1" targetNamespace="sample">
  <process id="bpmn_65f0e673_475e_4776_a685_42be7e93cc8f" name="simple-1"
    isExecutable="false" processType="Private">
    <startEvent id="start" name="Start">
      <outgoing>criteria</outgoing>
    </startEvent>
    <sequenceFlow id="criteria" sourceRef="start" targetRef="treatment">
      <documentation id="doc_criteria" textFormat="text/html">

simple finding

      </documentation>
    </sequenceFlow>
    <task id="treatment">
      <documentation id="doc_treatment" textFormat="text/html">

simple treatment

      </documentation>
      <incoming>criteria</incoming>
      <outgoing>toEnd</outgoing>
    </task>
    <sequenceFlow id="toEnd" sourceRef="treatment" targetRef="end" />
    <endEvent id="end" name="End">
      <incoming>toEnd</incoming>
    </endEvent>
  </process>
</definitions>

Unfortunately, when I try to load this into the Eclipse BPMN tooling, it generates the following error:
FeatureNotFoundException: Feature 'p' not found. (platform:/resource/BPMN/model/simpler.bpmn, 11, 12)

Are there any examples of how text/html content should get encoded into BPMN?
Is it supported by any of the BPMN tooling?

A: I can't try it by myself, but you can give it a try:
use a CDATA marker for your html text
What does <![CDATA[]]> in XML mean?


text:
Q: ASP, C# & SQL complex parameter/query examples please I am building a webpage that has a few controls on it such as CheckBoxList and Listbox (with multi selection enabled). These controls will be linked to a sql database table, one for colors and one for sizes. What is the best way to design the query, primarily the 'where' statement to filter the shirts listed in a gridview that match the selected sizes and colors made by the user. For example, if the user checks red and blue from the colorsCheckBoxList and medium and large from the sizesListbox, then the gridview will display only shirts that are red and are in medium and large as well as shirts in blue that are in medium and large. I've done most of the work, I just can't figure the best way to design the 'where' clause. I can create it easily if I allow only one selection per control but I'd prefer to allow multi-selection.
This is an .aspx page with 'code behind' the page (C#). I've read using parameters is the best method for clean code and security but I'd like to hear what others think.
Please let me know any further details you may need and I greatly appreciate any time spent regarding this question.

A: Yes always use SQL Parameters to remove the risk of SQL Injection.  It's hard to tell what you need with out seeing a database schema.  Here is what I would do in your case.
SELECT shirtid, shirtname
FROM shirts
WHERE colorID IN (REDSHIRTID, BLUESHIRTID)

You would put your IDs from your selectbox as REDSHIRTID and BLUESHIRTID.

A: You can use Table-valued or XML parameters to pass in mutliple IDs for the size and color. I would opt in favor of Table-valued parameters, personally.

A: The selection will vary depending on the size and color multiple or single selection for both.You can workout with stored procedure.(Also it will be faster) While passing the parameter to the sp you can pass the selections for both as string with character seperation of comma e,g for size 'red,blue,green' if selected this three.Same for color.
In sp you can first seperate the parameter by splitting  ',', and querying as
//create sp name
//pass parameter color and size
//begin sp
//write for splitting paramter code maybe in for statement then
   SELECT col1, col2, col3 from shirts
   WHERE size IN (separated param list)  AND
   color IN (separated param list of colors)

// end sp


text:
Q: Spring boot ws starter changed default liquibase resource location I have in my maven pom:
    <dependency>
        <groupId>org.springframework.ws</groupId>
        <artifactId>spring-ws-core</artifactId>
    </dependency>

which works fine, but once added:
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-ws</artifactId>
    </dependency>

file, the project starts throw exception about
Cannot find changelog location: ServletContext resource [/db/changelog/db.changelog-master.xml] (please add changelog or check your Liquibase configuration)

Doing a bit of digging myself, I can see that after adding the start-ws dependency, the resource loading path at
@PostConstruct
    public void checkChangelogExists() {
        if (this.properties.isCheckChangeLogLocation()) {
            Resource resource = this.resourceLoader
                    .getResource(this.properties.getChangeLog());
            Assert.state(resource.exists(),
                    "Cannot find changelog location: " + resource
                            + " (please add changelog or check your Liquibase "
                            + "configuration)");
        }
        ServiceLocator serviceLocator = ServiceLocator.getInstance();
        serviceLocator.addPackageToScan(
                CommonsLoggingLiquibaseLogger.class.getPackage().getName());
    }

changed from
db/changelog/db.changelog-master.xml

to
/db/changelog/db.changelog-master.xml

which is causing the issue, can anyone suggest why this behaviour occurs or just how to fix it? thanks!


text:
Q: Go chi middleware to add item to response header My concept is simple, I would like to add the request ID (generated by chi middleware.RequestID to the response header).
My code below adds X-Request-Id but does not add the ID itself. I am not sure why, since surely it is available in the context because middleware.RequestID is higher up in the middleware chain ?
My router creation:
package rest

import (
    "time"

    "github.com/go-chi/chi/v5"
    "github.com/go-chi/chi/v5/middleware"
    "goWebAPI/pkg/database"
    "goWebAPI/pkg/rest/mw"
    "goWebAPI/pkg/rest/routes"
)

func GetRouter(db *database.Database) *chi.Mux {
    r := chi.NewRouter()
    r.Use(middleware.RequestID)
    r.Use(mw.SendRequestID)
    r.Use(middleware.RealIP)
    r.Use(middleware.Logger)
    r.Use(middleware.Recoverer)
    r.Use(middleware.Timeout(60 * time.Second))
    r.Get("/", routes.IndexRoute())
    return r
}

My custom middleware:
package mw

import (
    "context"
    "net/http"

    "github.com/go-chi/chi/v5/middleware"
)

const requestIDHeader = "X-Request-Id"

func SendRequestID(next http.Handler) http.Handler {
    fn := func(w http.ResponseWriter, r *http.Request) {
        ctx := r.Context()
        if w.Header().Get(requestIDHeader) == "" {
            w.Header().Add(
                requestIDHeader,
                middleware.GetReqID(context.Background()),
            )
        }
        next.ServeHTTP(w, r.WithContext(ctx))
    }
    return http.HandlerFunc(fn)
}

My Index Route:
package routes

import "net/http"

func IndexRoute() http.HandlerFunc {
    fn:= func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("welcome"))
    }
    return fn
}

A: I believe your issue is here:
middleware.GetReqID(context.Background())

This tries to get the request ID for a new, empty context, when what you need is the request ID for the current request, meaning it should be:
middleware.GetReqID(r.Context)

(Or, since you're already grabbing the request context in local ctx, you could also use that.)
This is documented in GetReqId (emphasis mine):

GetReqID returns a request ID from the given context if one is present. Returns the empty string if a request ID cannot be found.


text:
Q: Android looping through onlinedatabase When i'm trying to loop through the database, my activity hang up and nothing happen.
    final JSONArray jArray = new JSONArray(result);
    while (i < jArray.length()) {
        JSONObject json = jArray.getJSONObject(i);
        title.setText(json.getString("PhoneName"));
        price.setText("Price : " + json.getString("PhonePrice"));
        modelnumber.setText(json.getString("ModelNumber"));
        arrowfront.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                i++;
            }
        });
        arrowback.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                i--;
            }
        });
    }
} catch (Exception e) {
    Log.e("tag", e.toString());
}
}

i'm trying to connect to the database, at first the textviews display the firstitem, then when i click on arrow i want to display the second row of the table and so on.. But when the activity launch, it hangs up and nothing happens even that i don't receive error's in logcat
And in the logcat, "tag" doesn't appear. Any suggestion??

A: Ok, do it this way :
final JSONArray jArray = new JSONArray(result);
private ArrayList<HashMap<String,String>> resultList = new ArrayList<HashMap<String,String>>();
int position=0;

for (int i=0;i<jArray.length();i++) {
HashMap<String,String> hm= new HashMap<String,String>();
JSONObject json = jArray.getJSONObject(i);
hm.put("title",json.getString("PhoneName"));
hm.put("price","Price : " + json.getString("PhonePrice"));
hm.put("modelNumber",json.getString("ModelNumber"));
resultList.add(hm);
}

arrowfront.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                position++;
HashMap <String,String> frontHm = new HashMap <String,String>();
frontHm=resultList.get(position);
        title.setText(frontHM.get("title");
        price.setText(frontHM.get("price"));
        modelnumber.setText(frontHM.get("modelNumber"));
            }
        });

arrowback.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                position--;
HashMap <String,String> backHm = new HashMap <String,String>();
backHm=resultList.get(position);
        title.setText(backHM.get("title");
        price.setText(backHM.get("price"));
        modelnumber.setText(backHM.get("modelNumber"));
            }
        });

So idea is to keep tracking the position inside global "position" variable. Also I didn't add logic inside click listeners to check first and last position because you can not go out of bounds of arraylist, please do it yourself.


text:
Q: Java performance and memory: LinkedList & arrays I'm building an Android app (so machines with limited resources) and I want to know how picky I should be with LinkedLists.
I know that arrays are the lightest containers and are the best at random access, so they're obviously the ideal choice if you only consider performance. However, their rigidness is a pain when you don't know how big your list will be.
So here's my question: is it worth it to systematically use the following type of mechanism in classes who have one or more list of unpredictable size:
public class unpredictable
public Object[]realArray;
private LinkedList<Object> temp;

//what using classes will call to add items
public void add(Object item)
{
    temp.add( item );
}

//what the outer class calls when it knows there's nothing left to add
public void doneAdding()
{
    realArray = new Object[tmp.size()];
    transferAndRecycle();
}

private void transferAndRecycle()
{
    // copy items from linkedlist to array
}

So I guess I'm asking if it's worth it to take the extra steps to get rid of the extra space Java's LinkedList object takes?
Any input? Thanks

A: I think you are providing a lot of services that the ArrayList class already contains. The ArrayList gives you O(1) element access; with a linked list it's O(n).  The underlying mechanism of an ArrayList is an array. You can control the size of this array by manipulating the capacity.
Look closely at ArrayList -- you may avoid reinventing some wheels.
Additional thought:  Arrays and Generics don't play nicely. ArrayLists do.  That is a small item but could be important to you.

A: In addition to what ncmathsadist already said:
Your choice should also depend on which operation happens more often: adding/removing elements or accessing a single element directly. If it's the former, use a LinkedList. If it's the latter use an ArrayList.
Don't forget: when resizing the array (be it your own solution or Java's ArrayList) there is one point in time where twice the memory is allocated: once for the "old arry" and once for the "new array" right before the resize operation is finished.
So if memory is really your concern is something you should also think about.

A: ArrayList has better locality of reference and less memory references than LinkedList.  Generally unless you need a specific LinkedList trait (quick deletions in the middle, splicing etc) prefer ArrayList

A: If you take a look at the Java Docs, you can find methods provided by the class that already have the desired functions you would like in you problem. For example, this is a function that converts an arraylist to an array.
http://download.oracle.com/javase/1.5.0/docs/api/

 T[]
toArray(T[] a)
          Returns an array containing all of the elements in this list in the correct order; the runtime type of the returned array is that of the specified array.


text:
Q: ListLogPlot with Legends inside the plot frame I'm trying to do ListLogPlot for the two lists of points
data1 ={{100,7.10934*^-11},{600,1.24888*^-10},{1100,1.29967*^-10},{1600,1.27995*^-10},{2100,1.2981*^-10},{2600,1.28602*^-10},{3100,1.29418*^-10},{3600,1.28796*^-10},{4100,1.29849*^-10},{4600,1.30531*^-10},{5100,1.29887*^-10},{5600,1.29934*^-10},{6100,1.29995*^-10},{6600,1.29672*^-10},{7100,1.30384*^-10},{7600,1.30762*^-10},{8100,1.29467*^-10},{8600,1.31142*^-10},{9100,1.29211*^-10},{9600,1.31159*^-10},{10100,1.30197*^-10},{10600,1.30517*^-10},{11100,1.31164*^-10},{11600,1.30673*^-10},{12100,1.30693*^-10},{12600,1.30377*^-10},{13100,1.30544*^-10},{13600,1.307*^-10},{14100,1.30303*^-10},{14600,1.30998*^-10},{15100,1.30301*^-10}}

data2 = {{100,1.98064*^-13},{600,2.17826*^-13},{1100,4.43912*^-12},{1600,5.40457*^-13},{2100,1.00364*^-13},{2600,2.30926*^-14},{3100,5.70433*^-13},{3600,3.41061*^-13},{4100,4.24549*^-13},{4600,1.24345*^-14},{5100,5.46674*^-13},{5600,8.08242*^-14},{6100,9.32587*^-14},{6600,6.32827*^-14},{7100,4.22062*^-12},{7600,9.10383*^-15},{8100,1.83944},{8600,1.45008},{9100,2.62997},{9600,0.672708},{10100,1.3049},{10600,1.48962},{11100,2.52422},{11600,15.8863},{12100,21.6495},{12600,5.45485},{13100,0.156453},{13600,9.29483},{14100,2.28007},{14600,8.27705},{15100,7.95017}}

using the following instructions in order to place the plot legends inside the frame:
ErAnl2 = ListLogPlot[{data1,data2},Joined->True, PlotLegends->Placed[LineLegend[{"Gauss-Gram","Direct"},LegendFunction->"Frame",LegendMarkerSize->0.1],{Right,Bottom}], Frame->True, FrameStyle->Thick, FrameLabel->{"c",Error}, LabelStyle-> Bold]

I got the following output

where the legend box is placed badly.
Then I wanted to save the image by typing
CloudExport[ErAnl2,"PNG","ErAnl2", ImageResolution ->500]

but  I also got this strange one

Thank you for any hint.


text:
Q: Doctrine 2.2 ORM: After reverse-engineering from database MappingException is thrown I'm using Zend Framework boilerplate without the virtual machine.
My Application.ini, looks like this:
;resources.doctrine.orm.entityManagers.default.metadataDrivers.annotationRegistry.annotationFiles[]     = APPLICATION_PATH "/../library/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php"
resources.doctrine.orm.entityManagers.default.metadataDrivers.drivers.0.adapterClass          = "Doctrine\ORM\Mapping\Driver\XmlDriver"
resources.doctrine.orm.entityManagers.default.metadataDrivers.drivers.0.mappingNamespace      = "Square\Entity"
resources.doctrine.orm.entityManagers.default.metadataDrivers.drivers.0.mappingDirs[]         = APPLICATION_PATH "\..\library\Square\Entity"
;resources.doctrine.orm.entityManagers.default.metadataDrivers.drivers.0.annotationReaderClass = "Doctrine\Common\Annotations\AnnotationReader"
;resources.doctrine.orm.entityManagers.default.metadataDrivers.drivers.0.annotationReaderCache = default
;resources.doctrine.orm.entityManagers.default.metadataDrivers.drivers.0.annotationReaderNamespaces.Square = "Square\Entity"

I have runed the command in CLI as in the example from here :
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/tools.html#reverse-engineering
More specifically this one:
$ php doctrine orm:convert-mapping --from-database xml /path/to/mapping-path-converted-to-xml

And this generated my xml files with the following naming schema: {Entity}.dcm.xml
I have generated my Entity classes based on these XML files and then tried saving to the database with:
    try{
        $this->_em->persist($this->_apikey);
        $this->_em->flush();
    }catch (Exception $e){
        echo "Something went bad --> ".$e;
    }

Where $this->_apikey = new Square\Entity\Apikeys(); in the constructor method.
The Entity Manager throws up an exception:
exception 'Doctrine\ORM\Mapping\MappingException' with message 'No mapping file found'

Why is Doctrine asking for a mapping file if the Entity class was generated upon them?
Am I doing something wrong?

A: Doctrine 2.2 requires you keep the xml files even if it has it's PHP class reversed engineered from them.


text:
Q: how to hatch turtles that face closest neighbor of agentset doing the hatching I currently have one agentset(ports) hatching another agentset(ships).
The idea is to have the ships face the closest port to their current location.
[let target min-one-of ports [distance myself]
 face target].
Unfortunately this makes the ships face their current location since they are being hatched at a given port. If there is no way to exclude the port they hatch on- I have an index of the locations(ports) and could potentially set the target as the following item in the index however I am not sure how I would accomplish this. any suggestions?
full code example
breed [ships ship]
breed[ports port]

to setup

   let index 0
 create-ports 3
 [ let loc item index [ [459 -324] [670 -233] [677 -356] ]
   setxy (item 0 loc) (item 1 loc)
   set index index + 1
   set shape "circle"
   set size 5
   set color red - 1]

 ask ports
 [ hatch-ships 1
 [ set size 10
   set color red
   pen-down
   set pen-size 1
   let target min-one-of other ports [distance myself]
   face target] ]

 reset-ticks
end

A: You can assign the who value of hatching port to the ship as their current port and define their target port as the closes port which is not the current port.
breed [ships ship]
breed[ports port]
ships-own [currentPort targetPort]
to setup
clear-all
   let index 0
 create-ports 3
 [
 ; let loc item index [ [459 -324] [670 -233] [677 -356] ]

 let loc item index [ [4 -4] [ 9 5] [ -11 11] ]
   setxy (item 0 loc) (item 1 loc)
   set index index + 1
   set shape "circle"
   set size 5
   set color red - 1]

 ask ports
 [

   let s who
   set label ( word S "    Port    "  s )
   hatch-ships 1

 [ set currentPort s
   set shape "sailboat side"
   set size 10
   set color red
   pen-down
   set pen-size 1
   Set targetPort min-one-of ports with [ who != s] [distance myself]
   set heading towards targetport
   set label (word "target " targetport)

   ] ]

 reset-ticks
end


text:
Q: how to restore globals $1, $2, $3 while debugging? When I debug code with regular expressions:
m/(.)(.)(.)(.)(.)/;
my $x =  $1;
$DB::single = 1;
my $y =  $2 + $3;

and put break point at some line. I could run third party code.
And if that code uses call to regex then $2 and $3 will be broken.
Is there a way to restore $2, and $3 to theirs initial values by debugger when I continue script? ( c debugger command)

A: It happens automatically.
$ perl -e'
   "abc" =~ /(.)(.)(.)/;
   CORE::say "[$1$2$3]";
   {
      "def" =~ /(.)(.)(.)/;
      CORE::say "{$1$2$3}";
   }
   CORE::say "[$1$2$3]";
'
[abc]
{def}
[abc]

The regex capture vars are implicitly restored when the scope in which they are changed is exited. When you execute code from within the debugger, the regex capture vars are restored before even returning to the debugger.
$ perl -d -e'
   "abc" =~ /(.)(.)(.)/;
   CORE::say "[$1$2$3]";
   CORE::say "[$1$2$3]";
'
[snip]
main::(-e:2):      "abc" =~ /(.)(.)(.)/;
  DB<1> s
main::(-e:3):      CORE::say "[$1$2$3]";
  DB<1> s
[abc]
main::(-e:4):      CORE::say "[$1$2$3]";
  DB<1> p "{$1$2$3}"
{abc}                                              <-- Values from the program
  DB<2> x "def" =~ /(.)(.)(.)/; say "<$1$2$3>";
<def>                                              <-- Changed in called code
0  1
  DB<3> p "{$1$2$3}"
{abc}                                              <-- Already restored
  DB<4> r
[abc]                                              <-- Code has nothing to worry about
Debugged program terminated. [snip]
  DB<4> q

You do have to be careful about changing other variables, such as $!. If the code being debugged cares about the value of $! (for example) and you want to run code that clobbers $!, you'll need to back it up and restore it.
x local $!; clobbering_time();

At this time, the debugger protects $@, $!, $^E, $,, $/, $\ and $^W from being clobbered by the debugger itself, but not by code executed via x.

A: Can you stash the value in a variable?
m/(.)(.)(.)(.)(.)/;
my ($x, $two, $three) = ($1, $2, $3);
$DB::single = 1;
my $y =  $two + $three;


text:
Q: In Zig, how do you tell if a frame represents a fully executed function? In Zig (currently using 0.7.1), suppose for some reason you don't have any good way to design code which always has exactly one resume for every suspend. Is there any supported way to detect at runtime that a given frame has or has not been executed to completion?
// overly simplistic example designed to illustrate the problem
pub fn main() void {
    var frame = async amain(2);
    resume frame;
    resume frame;

    // panic/UB -- resume async function which already returned
    //
    // we would prefer to have some kind of check which could allow
    // us to detect at runtime that the following resumption is illegal
    resume frame;
}

fn amain(ubound: i32) void {
    var i: i32 = 0;
    while (i < ubound) : (i += 1) {
        suspend;
    }
}

If I log the raw bytes of those frame structs (which as far as I can tell are opaque and don't support field access? I'm a little new to Zig), then it seems pretty obvious that a portion of the frame is dedicated to marking whether it has returned:
[70, 3a, 23, 00, 00, 00, 00, 00, 02, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 02, 00, 00, 00, 00, 00, 00, 00]
[70, 3a, 23, 00, 00, 00, 00, 00, 02, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 02, 00, 00, 00, 01, 00, 00, 00]
[70, 3a, 23, 00, 00, 00, 00, 00, ff, ff, ff, ff, ff, ff, ff, ff, ff, ff, ff, ff, ff, ff, ff, ff, 02, 00, 00, 00, 02, 00, 00, 00]

Blindly reading that data seems a little reckless however, and I'd feel a lot more comfortable if I knew the struct layout were guaranteed or that there were some builtin way to uncover that information.
Edit::
In particular, the problem that I'm trying to solve is that when designing an event loop (e.g. when interfacing between JS and Zig/WASM) you seem to have to marry the implementation of an async function to the API of the event loop itself.
The built-in event loop, for example, has a yield() function precisely so that it can do the necessary bookkeeping to ensure that code has one resume per suspend, but as far as I can tell that's an unnecessary restriction since whether a frame has returned seems to be stored and readily accessible.
It's certainly possible that I'm misunderstanding the purpose of Zig's async/await, but I don't see any fundamental reason why a general purpose event loop capable of handling any async function (not just those adhering to a particular loop API) couldn't be written, but I'm struggling to see how that's possible without a little more runtime introspection than the docs indicate is available.

A: As of April 2022 there's an open proposal for implementing this feature in the language. A workaround till then might still be manually reading the async frame header.


text:
Q: Bar over letter but NOT math mode Every search I have done for this, the answer involves \bar or \overline but those are math mode and thus result in the math font being used, which often differs from the main text font.
Ēostre - note the E has a bar over it. A Pagan Goddess. If I use math mode then the upper case E is a different font than the ostre which is typographically wrong.
How, using TeXLive with pdflatex compiler, so I add a horizontal bar over a latin letter without using math mode?
Thank you for suggestions.

A: \=E is what I was looking for.


text:
Q: R forestplot() function fix section widths I want to generate multiple forest plots using the forestplot() function in R (from the package R/forestplot), and want to ensure that I can line up the text and graph sections in each so they can be usefully shown as a stacked plot, like this:

(taken from R forestplot package blank lines with section headings)
but with the possibility that there may be different scales in each subplot, lining up the zero effect line in each plot.
Which attributes need changing in the forestplot() call to ensure that this occurs?
EDIT: to provide a minimum code example

library(forestplot)
library(tidyr)

cohort <- data.frame(Age = c(43, 39, 34, 55, 70, 59, 44, 83, 76, 44,
                       75, 60, 62, 50, 44, 40, 41, 42, 37, 35, 55, 46),
               Status = structure(c(2L,
                                    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 1L,
                                    1L, 1L, 1L, 2L, 2L), levels = c("-", "+"), class = "factor"),
               Group = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
                                   1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), levels = c("1","2"), class = "factor"))

age.lm <- lm(Age ~ Group, data = cohort)
status.lm <- glm(Status ~ Group, data = cohort, family=binomial(link=logit))

age.data <- summary(age.lm)$coefficients[2,]
status.data <- summary(status.lm)$coefficients[2,]

age.data <- rbind(c(0,0,0,1,"Group 1", "n=15"),
                  c(age.data[1], age.data[1]-age.data[2]*1.95, age.data[1]+age.data[2]*1.95, age.data[4], "Group 2", "n=7"))
status.data <- rbind(c(0,0,0,1,"Group 1", "[+13,-2]"),
                     c(status.data[1], status.data[1]-status.data[2]*1.95, status.data[1]+status.data[2]*1.95, status.data[4], "Group 2", "[+2,-5]"))

colnames(age.data) <- c("mean","lower","upper","p-val","labeltext","numbers")
colnames(status.data) <- c("mean","lower","upper","p-val","labeltext","numbers")

age.data <- data.frame(age.data)
status.data <- data.frame(status.data)

age.data$mean <- as.numeric(age.data$mean)
age.data$lower <- as.numeric(age.data$lower)
age.data$upper <- as.numeric(age.data$upper)

status.data$mean <- exp(as.numeric(status.data$mean))
status.data$lower <- exp(as.numeric(status.data$lower))
status.data$upper <- exp(as.numeric(status.data$upper))

age.plot <- forestplot(age.data,
           labeltext = c(labeltext,numbers),
           boxsize = 0.1,
           xlog = FALSE,
           clip=c(-20,20),
           xticks=c(-20,-10,0,10,20),
           txt_gp = fpTxtGp(ticks=gpar(cex=1)),
           align=c("l","c","l"))

status.plot <- forestplot(status.data,
                          labeltext = c(labeltext,numbers),
                          boxsize = 0.1,
                          xlog = TRUE,
                          clip=c(1/100,100),
                          xticks=c(log(1e-2),log(1e-1),0,log(1e1),log(1e2)),
                          txt_gp = fpTxtGp(ticks=gpar(cex=1)),
                          align=c("l","c","l"))

Note that the age plot is a linear model and the status plot is a logistic model:

I want to be able to arrange the relative sizes of the text to the left and the plot to the right in order that the zero-effect lines (at 0 and at 1 respectively) line up so that the forest plots stack cleanly.

A: With the align argument you could left "l" align the parts of your plot, so the text can be left aligned. If you want to align your zero-effect lines you could use mar and play with the units to adjust one of the graphs. Here is a reproducible example:
library(forestplot)
library(tidyr)

age.plot <- forestplot(age.data,
                       labeltext = c(labeltext,numbers),
                       boxsize = 0.1,
                       xlog = FALSE,
                       clip=c(-20,20),
                       xticks=c(-20,-10,0,10,20),
                       txt_gp = fpTxtGp(ticks=gpar(cex=1)),
                       align=c("l","l","l")
                       )

status.plot <- forestplot(status.data,
                          labeltext = c(labeltext,numbers),
                          boxsize = 0.1,
                          xlog = TRUE,
                          clip=c(1/100,100),
                          xticks=c(log(1e-2),log(1e-1),0,log(1e1),log(1e2)),
                          txt_gp = fpTxtGp(ticks=gpar(cex=1)),
                          align=c("l","l","l"),
                          mar = unit(c(0,5,0,10.5), "mm")
                          )

library(grid)
grid.newpage()
pushViewport(viewport(layout = grid.layout(2, 1)))
pushViewport(viewport(layout.pos.row = 1))
plot(age.plot)
popViewport()
pushViewport(viewport(layout.pos.row = 2))
plot(status.plot)
popViewport(2)

Created on 2022-12-28 with reprex v2.0.2


text:
Q: decrypting a dvd and testing that it is decrypted and playing it locally with its menu? I have a DVD , it may be decrypted. How do I get it to hard drive decrypt it and see if it is decrypted?
I have got it to hard drive... I can get VOB files to play(does that mean it is not encrypted?) but I can't get it to play with the menu.
I can get the DVD itself to play with a menu.
I'd like to get the local copy to.
Also, I can play the first VOB file in VLC and MPC but not in mplayer. But that's a secondary thing.
I will use whatever player you suggest.  I have tried VLC, and mplayer, and media player classic.


text:
Q: Problem with initiating UITableViewCells based on indexPath.row I have the following method that should populate the cells of my UITableView with data from an array.  I want to get the data from the array using the row that the data is being loaded into as the index.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    cellComments=(FullCommentCell *)[tableView dequeueReusableCellWithIdentifier:FullCommentCell_ID];
    if(cellComments==nil)
    {
        [[NSBundle mainBundle]loadNibNamed:@"FullCommentCell" owner:self options:nil];
        NSLog([NSString stringWithFormat:@"%i",indexPath.row]);
        [cellComments loadFullComments:[latestFMLComments objectAtIndex:indexPath.row]];
    }
    //cellComments.userInteractionEnabled=NO;
    return cellComments;

}
This is not working as expected.  The table only ends up being populated with the first three elements of my array and then this data is reused until my table ends.  The table should be using all the data from my array.  Any idea why this is not working as expected?

A: You need to set the correct cell data each time you return a cell, whether it's new or reused.  As you scroll down, cells from the top of the table are removed and reused for the bottom of the table.  That's why you're seeing the first few data items repeated.
- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    cellComments = (FullCommentCell *)[tableView dequeueReusableCellWithIdentifier:FullCommentCell_ID];
    if (cellComments == nil) {
        [[NSBundle mainBundle]loadNibNamed:@"FullCommentCell" owner:self options:nil];

        // Do any one-time setup here, like adding subviews
    }

    // Set cell data for both new and reused cells here

    [cellComments loadFullComments:[latestFMLComments objectAtIndex:indexPath.row]];
    //cellComments.userInteractionEnabled=NO;

    return cellComments;
}

A: When you get the cellComments back from the dequeueReusableCellWithIdentifier call, you need to call loadFullCommnents again - cells are reused so you'll only have as many created as show up on screen.


text:
Q: Cocoa touch dimming background darker Hey! I am making an app with a slider which slides out from the bottom and I would like to make other parts of the app a bit darker to show that the picker is the active component, like when alertbox comes, the background darkens. How do archieve this?

A: Overlay the elements you want to darken with a view that has a semi-transparent dark background (e.g. a black background with an alpha value of 0.5).


text:
Q: Is 'show' a normal S4 generic function? I'm trying to create a method for my class, which inherits from data.frame. I was originally hoping just to inherit the 'show' method from data.frame as well, but I'm also fine with writing my own. I defined my class and 'show' method as follows:
setClass("SCvec", representation(auth = "character",
    dev = "character",
    sensor = "character",
    channel = "character",
    starttime = "character",
    endtime = "character"),
    contains="data.frame")
setMethod("show", signature(x="SCvec"), function(x) print(x))

when I type show in the R console, it prints out:
standardGeneric for "show" defined from package "methods"
function (object)
standardGeneric("show")
<bytecode: 0x0396bee8>
<environment: 0x0393ab60>
Methods may be defined for arguments: object
Use  showMethods("show")  for currently available ones.
(This generic function excludes non-simple inheritance; see ?setIs)

So it sure looks like I don't need to turn it into a generic using StandardGeneric() myself. but when I run my setMethod("show", signature(x="SCvec"), function(x) print(x)) line, I get the error
Error in match.call(definition, call, expand.dots) :
  unused argument(s) (x = c("SCvec", ""))

I've defined this method just like I would define any other one. Why does this method definition not work? Is 'show' different than other generic functions?

A: The function show takes an argument object, so you would need to define your signature and function definition with respect to that formal argument:
setMethod("show", signature(object="SCvec"), function(object) print(object))

You can also see other methods that are defined for show by typing in
showMethods(show)

And this shows you that all the other methods are defined in terms of the class of object as well.


text:
Q: Can telnet be used to set gps location on real android device connected through usb? Can adb be used to alter my android phone's gps location when it is connected through usb? I have installed MockGeoFix on my android phone and enabled it in the mock location setting. I opened a command prompt (Windows 10) and typed
telnet
open 192.168.0.65 5554

MockGeoFix: type 'help' for a list of commands
OK

auth
KO: Password is not required.

geo fix  40.7127837 -74.0059413
KO: argument is not a number

Also, I am wondering if adb can be used to set the gps location directly and if possible, what is the command I should use?

A: You can try this
geo fix 50 50


text:
Q: Positioning of JqueryUI datepicker: how to set its position relative to where it would automatically show up? I have a search page with a filter box on it. In this box are two date filters, Before and After. Each date filter uses the jquery ui-datepicker. The first one looks like this:

The second one looks like this:

I need the calendar for the Before Date box (image 2) to show up in the same place as the After Date box (image 1). I don't think I can hardcode the position for the second calendar though, because while that might work on my computer, wider or smaller screens would likely have it in the wrong place. I also can't set it to a relative value, because its position is already set using absolute value. How can I make the second calendar show up, say 200px to the left of where it would automatically show up?

A: I used atom.gregg's answer to come up with the solution:
$("#beforedate").datepicker({
    beforeShow: function(input, inst) {
        setTimeout(function () {
            var offsets = $("#afterdate").offset();
            var top = offsets.top + 25;
            inst.dpDiv.css({
                top: top,
                left: offsets.left,
            });
        });
    }
});

A: I initially thought you would need to wire into a 'onshow' event, so following that train of thought, I found this SO question: How to change jquery ui datepicker position?
In the event handler shown in the sample below from that post, you can then set the position correctly, ie. relative to the other control.
$("#datepicker").datepicker({
    beforeShow: function (input, inst) {
        setTimeout(function () {
            inst.dpDiv.css({
                top: 100,
                left: 200
            });
        }, 0);
    }
});


text:
Q: Как удалить все партиции старше заданной даты? Есть таблица, основанная на ежедневных партициях.
Можно удалить раздел с помощью следующего запроса:
ALTER TABLE MY_TABLE DROP PARTITION FOR (TO_DATE ('24-OCT-2021','dd-MON-yyy'))

А как можно удалить все партиции (несколько партициий) старше 7 дней?

Свободный перевод вопроса Drop multiple partitions based on date от участника @TomJava

A: С клаузой DROP PARTITION удалить несколько партиций нельзя (см. drop_table_partition).
Можно написать процедуру, которая определит партиции для удаления и удалит их в цикле:
create or replace procedure dropPartitions (tableName varchar2, daysOlder int) is
    deleteOlder constant date := trunc (sysdate) - daysOlder;
    dataDate date;
begin
    for r in (  select partition_name, high_value
                from user_tab_partitions
                where table_name = upper (tableName)) loop
        execute immediate 'begin :1 := '||r.high_value||'-1; end;' using out dataDate;
        if dataDate <= deleteOlder and r.partition_name like 'SYS%' then
            execute immediate 'ALTER TABLE '||tableName||' DROP PARTITION '||r.partition_name;
            dbms_output.put_line (' '||r.partition_name||' for '||dataDate||' droped.');
        end if;
    end loop;
end;
/

Тестовые данные и вызов (сег. 01.10, ожидаю, что будут удалены партиции старше 25.09):
create table t (
    id number primary key, created date)
partition by range (created) interval (numToDSInterval (1, 'day')) (
    partition def_part values less than (date'2000-01-01'))
/
insert into t
    select rownum, date'2021-10-01'-(rownum-1)/12
    from dual connect by level<=96;

exec dropPartitions ('t', 7)

SYS_P11045 for 2021-09-24 00:00:00 droped.
SYS_P11046 for 2021-09-23 00:00:00 droped.

PS: из оригинального ответа убран блок исключений, потому что он служит для удаления партиции по умоолчанию (первой), которая обычно служит для сбора ошибочных или экзотических записей. Эта партиция не может быть удалена для интервал партиционирования. Если всё таки возникнет потребность, то ее можно удалить вручную временно отключив интервал партиционирование:
alter table t set interval ()
/
alter table t drop partition def_part;
/
alter table t set interval (interval '1' day);

Свободный перевод ответа от участника @Wernfried Domscheit


text:
Q: How do you solve the Tower level 48 puzzle? This is the puzzle that involves using bombs to progress forward.  In the 1st part you have to light a torch, hold a bomb, and walk the orange speed pads.  The torch lights the bomb you're holding and causes it to blow up at a specific time to destroy a rock.
I'm stuck in the 2nd part where you're supposed to use the bomb to flip a red/blue switch in a similar manner up above.

A: Try this video:

If you look it up you will find other vids and articles on how to solve this level as well.
Hope this is helpful!


text:
Q: Random number game refresh Javascript I have a "guess a random number" game, where my code generates a random number between 1 and 100, and you try and guess the number. I'd like to have a reset button that refreshes the game by changing the variable with the random number in it. This is the relevant code I have.
var comparedNumber = RandomNumber();

function RandomNumber(){
var randomNumber = Math.floor(Math.random() * 100) + 1;
return randomNumber;
};

refresh.onclick = function(){
genComparedNumber();
};

Function Random Number runs on page load, but I can't seem to get comparedNumber to change.

A: Same logic as @juvian's answer

var Game = {
 comparedNumber : randomNumber(),
 refreshNumber : function(){
  this.comparedNumber = randomNumber();
        alert(this.comparedNumber);
 },
 refreshButton : document.querySelector("#refresh-button")
}

function randomNumber(){
 var randomNumber = Math.floor(Math.random() * 100) + 1;
 return randomNumber;
}

Game.refreshButton.addEventListener("click",Game.refreshNumber,false);
<button id="refresh-button">Refresh</button>


text:
Q: Google Form submit running unknown sheet app script I have a very strange problem.  I have a google form and an attached sheet.  That sheet has a script which seems to run OK (I just have it doing a betterlogger on form submit).  Here's the strange thing - throughout the day I have been creating forms and scripts bound in sheets.  Now, for some reason, one form I have is running a script that is not bound to it (well, it must be bound but I cannot see it when I edit the scripts).  No matter what I have tried, this sheet continues to run some mystery script of mine (I can tell because it too has betterlogger output that gets merged with the "correct" script attached to the sheet).  To summarize, I have a script bound to a sheet that runs correctly but in parallel, another one of my sheet scripts runs at the same time - I have no way to tell which other script it is since I have many.  This mystery script runs  even if the sheet has NO triggers defined for the sheet script!
Is there any way to see "all" bound scripts for a sheet or form?  Are there hidden ones that I can see or disconnect from?

A: It turns out this is a known bug in the google app script / sheets world.  It rarely occurs but there are references to it.  See here: https://plus.google.com/111635744893768700770/posts/SBeeu9KwWfL


text:
Q: Lazy single-threaded worker I have a thread that reads data in small chunks and puts it into ImmutableList<T>. I need to dump this list into a file. Originally I was dumping the list on every update but with time list grew and file size is now close to 200Mb so writing file takes too much time to keep it synchronous.
I've made file writing asynchronous and the code I currently have is:
public ImmutableList<T> Items { get; private set; }

public void Insert(IEnumerable<T> items)
{
    lock (_syncObj)
    {
        Items = Items.AddRange(items).Sort(_sortOrder);
        QueueSaving();
    }
}

void SavingThread()
{
    for (; ; )
    {
        var snapshot = Items;
        SaveItems(snapshot);

        lock (_syncObj)
        {
            if (snapshot == Items)
                Monitor.Wait(_syncObj);
        }
    }
}

void QueueSaving()
{
    lock (_syncObj)
        Monitor.Pulse(_syncObj);
}

I.e. if there were many updates since the last write then writer just saves the last version.
Obviously I now have to have a thread that is dedicated to saving and which sleeps when there are no updates.
What would be the cleanest code to avoid having a dedicated writer thread? I.e. run QueueSaving until file writer caught up with the list changes and finish, then start it on the next change?

A: As I understand from the comments, you're only looking to convert your logic into asynchronous code. Below is how this might be done without explicit separate threads (besides using Task.Run for the whole process).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication
{
    public class Worker
    {
        class Item
        {
            public string Data { get; set; }
        }

        const int SAVE_AFTER = 2;

        string _fileName;
        List<Item> _items;
        int _savedItemsCount = 0;

        CancellationToken _token;
        Task _processTask;

        Task _pendingSaveTask = null;

        // get next item
        async Task<Item> GetNextItemAsync()
        {
            await Task.Delay(500); // delay for testing
            return new Item { Data = "Item from " + DateTime.Now.ToString() };
        }

        // write
        async Task SaveItemsAsync(Item[] items)
        {
            if (_pendingSaveTask != null)
                await _pendingSaveTask; // await the previous save

            var text = items.Aggregate(String.Empty, (a, b) => a + b.Data + Environment.NewLine);

            using (var writer = new System.IO.StreamWriter(_fileName, append: false))
            {
                await writer.WriteAsync(text);
            }
        }

        // main process
        async Task ProcessAsync()
        {
            while (true)
            {
                _token.ThrowIfCancellationRequested();

                // start getting the next item
                var getNextItemTask = GetNextItemAsync();

                // save the snapshot if needed
                if (_items.Count >= _savedItemsCount + SAVE_AFTER)
                {
                    var snapshot = _items.ToArray();
                    _savedItemsCount = snapshot.Length;
                    _pendingSaveTask = SaveItemsAsync(snapshot);
                }

                // await the next item
                var item = await getNextItemTask;
                _items.Add(item);
            }
        }

        // start
        public void Start(CancellationToken token)
        {
            _token = token;
            _fileName = System.IO.Path.GetTempFileName();
            _items = new List<Item>();

            _processTask = Task.Run(new Func<Task>(ProcessAsync), _token);
        }

        // stop
        public void Stop()
        {
            if (_pendingSaveTask != null)
                _pendingSaveTask.Wait();

            try
            {
                _processTask.Wait(); // wait for the task to complete
            }
            catch (Exception ex)
            {
                // rethrow if anything but OperationCanceledException
                if (!(ex is OperationCanceledException))
                {
                    var aggEx = ex as AggregateException;
                    if (aggEx == null || !(aggEx.InnerException is OperationCanceledException))
                        throw;
                }
            }
        }
    }

    class Program
    {
        public static void Main()
        {
            var cts = new CancellationTokenSource();
            var worker = new Worker();

            Console.WriteLine("Start process");
            worker.Start(cts.Token);

            Thread.Sleep(10000);

            Console.WriteLine("Stop process");
            cts.Cancel();
            worker.Stop();

            Console.WriteLine("Press Enter to exit...");
            Console.ReadLine();
        }
    }
}

Note that if new items (GetNextItemAsync) arrive faster than SaveItemsAsync finishes saving the last snapshot, this implementation may end up with a growing chain of pending SaveItemsAsync calls. If this is a problem, you could deal with it by limiting SaveItemsAsync task to only one pending instance and using BlockingCollection to queue new snapshots.
[UPDATE] Here is a slightly improved version which eliminate redundant writes if updates are coming faster than saving. It doesn't use BlockingCollection but adds some extra cancellation logic to SaveItemsAsync instead. It's a console app, feel free to try it out to see what's going on. Try calling _saveTask = SaveItemsAsync(snapshot) a few times in a row.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication
{
    public class Worker
    {
        class Item
        {
            public string Data { get; set; }
        }

        const int SAVE_AFTER = 2;

        string _fileName;
        List<Item> _items;
        int _savedItemsCount = 0;

        CancellationToken _token;
        Task _processTask;

        Task _saveTask;
        CancellationTokenSource _saveTaskCts;

        // get next item
        async Task<Item> GetNextItemAsync()
        {
            Console.WriteLine("Enter GetNextItemAsync, thread: " + System.Threading.Thread.CurrentThread.ManagedThreadId);

            await Task.Delay(500); // delay for testing
            return new Item { Data = "Item from " + DateTime.Now.ToString() };
        }

        // save items
        async Task SaveItemsAsync(Item[] items)
        {
            // avoid multiple pending SaveItemsAsync tasks
            Console.WriteLine("Enter SaveItemsAsync, thread: " + System.Threading.Thread.CurrentThread.ManagedThreadId);

            var oldSaveTaskCts = _saveTaskCts;
            var oldSaveTask = _saveTask;

            var thisSaveTaskCts = CancellationTokenSource.CreateLinkedTokenSource(_token);

            _saveTaskCts = thisSaveTaskCts;
            _saveTask = null;

            // cancel the previous pending SaveItemsAsync, if any
            if (oldSaveTaskCts != null)
            {
                oldSaveTaskCts.Cancel();
                if (oldSaveTask != null)
                    await oldSaveTask.WaitObservingCancellationAsync();
            }

            // another SaveItemsAsync call should lead to cancelling this one
            thisSaveTaskCts.Token.ThrowIfCancellationRequested();

            // execute the save logic on a pool thread,
            // Task.Run automatically unwraps the nested Task<Task>
            await Task.Run(async () =>
            {
                // do the CPU-bound work: create textual representation of data
                var text = items.Aggregate(String.Empty, (agg, item) => agg + item.Data + Environment.NewLine);

                // write asynchronously
                Console.WriteLine("Write, thread: " + System.Threading.Thread.CurrentThread.ManagedThreadId);

                // StreamWriter doesn't support cancellation, so do it in two stages with MemoryStream
                using (var memoryStream = new MemoryStream())
                {
                    // write to a memory stream first
                    using (var writer = new StreamWriter(
                        memoryStream,
                        encoding: System.Text.Encoding.UTF8,
                        bufferSize: Environment.SystemPageSize,
                        leaveOpen: true))
                    {
                        await writer.WriteAsync(text);
                    }

                    thisSaveTaskCts.Token.ThrowIfCancellationRequested();

                    // copy the memory stream to the file
                    using (var fileStream = new FileStream(_fileName, FileMode.Create, FileAccess.Write))
                    {
                        // copy with possible cancellation
                        memoryStream.Seek(0, SeekOrigin.Begin);
                        await memoryStream.CopyToAsync(fileStream, Environment.SystemPageSize, thisSaveTaskCts.Token);
                    }
                }
            }, thisSaveTaskCts.Token);
        }

        // main process
        async Task ProcessAsync()
        {
            while (true)
            {
                // handle cancellation
                if (_token.IsCancellationRequested)
                {
                    // await the pending save if any, before throwing
                    if (_saveTask != null)
                        await _saveTask.WaitObservingCancellationAsync();
                    _token.ThrowIfCancellationRequested();
                }

                // handle last save errors if any
                if (_saveTask != null && _saveTask.IsFaulted)
                    await _saveTask.WaitObservingCancellationAsync();

                // start getting the next item
                var getNextItemTask = GetNextItemAsync();

                // save the snapshot if needed
                if (_items.Count >= _savedItemsCount + SAVE_AFTER)
                {
                    var snapshot = _items.ToArray();
                    _savedItemsCount = snapshot.Length;
                    _saveTask = SaveItemsAsync(snapshot);
                }

                // await the next item
                var item = await getNextItemTask;
                _items.Add(item);
            }
        }

        // start
        public void Start(CancellationToken token)
        {
            _token = token;
            _fileName = System.IO.Path.GetTempFileName();
            _items = new List<Item>();

            _processTask = Task.Run(new Func<Task>(ProcessAsync), _token);
        }

        // stop
        public void Stop()
        {
            _processTask.WaitObservingCancellation();
        }
    }

    // Main
    class Program
    {
        public static void Main()
        {
            var cts = new CancellationTokenSource();
            var worker = new Worker();

            Console.WriteLine("Start process");
            worker.Start(cts.Token);

            Thread.Sleep(10000);

            Console.WriteLine("Stop process");
            cts.Cancel();
            worker.Stop();

            Console.WriteLine("Press Enter to exit...");
            Console.ReadLine();
        }
    }

    // Useful extensions
    public static class Extras
    {
        // check if exception is OperationCanceledException
        public static bool IsOperationCanceledException(this Exception ex)
        {
            if (ex is OperationCanceledException)
                return true;

            var aggEx = ex as AggregateException;
            return aggEx != null && aggEx.InnerException is OperationCanceledException;
        }

        public static async Task WaitObservingCancellationAsync(this Task task)
        {
            try
            {
                await task; // await the task to complete
            }
            catch (Exception ex)
            {
                // rethrow if anything but OperationCanceledException
                if (!ex.IsOperationCanceledException())
                    throw;
            }
        }

        // a helper to wait for the task to complete and observe exceptions
        public static void WaitObservingCancellation(this Task task)
        {
            try
            {
                task.Wait(); // wait for the task to complete
            }
            catch (Exception ex)
            {
                // rethrow if anything but OperationCanceledException
                if (!ex.IsOperationCanceledException())
                    throw;
            }
        }
    }
}

A: Start a writer Task when the count of unsaved items in the list crosses a threshold. You can put that logic into Insert under the existing lock. That way a writer thread/Task is only in existence when there is work to do.
I implemented a similar thing recently where I used a Timer to start the persistence work at a certain schedule.

A: Here's what I ended up writing:
public ImmutableList<T> Items { get; private set; }

public void Insert(IEnumerable<T> items)
{
    lock (_syncObj)
    {
        Items = Items.AddRange(items).Sort(_sortOrder);
        StartSaving();
    }
}

Task _activeSavingTask;

void SavingThread()
{
    for (;;)
    {
        var snapshot = Items;
        SaveItems(snapshot);

        lock (_syncObj)
        {
            if (snapshot == Items)
            {
                _activeSavingTask = null;
                return;
            }
        }
    }
}

void StartSaving()
{
    lock (_syncObj)
        if (_activeSavingTask == null)
            _activeSavingTask = Task.Factory
                .StartNew(SavingThread, TaskCreationOptions.LongRunning);
}

A: class AsyncSaver<T> where T : class
{
    private readonly object _lock = new object();
    private readonly Func<T, Task> _save;
    private T _item;
    private bool _running;

    public AsyncSaver(Func<T, Task> save)
    {
        _save = save;
    }

    public void Enqueue(T item)
    {
        lock (_lock)
        {
            if (_running)
            {
                _item = item;
            }
            else
            {
                _running = true;
                Save(item);
            }
        }
    }

    private async void Save(T item)
    {
        await _save(item);

        lock (_lock)
        {
            if (_item != null)
            {
                var nextItem = _item;
                _item = null;
                Save(nextItem);
            }
            else
            {
                _running = false;
            }
        }
    }
}