text:
Q: How to make the whole div clickable? I have a div with contents in it:

    ...

I set up a JavaScript Event Listener when someone clicks on the div:
document.body.addEventListener("click", function(e) {
    if (e.target.tagName === 'DIV' && e.target.classList.contains("block")){
        (code)
    }
}

It works when I click on the area of the div that has no content. But it doesn't works, when I click to the image or to the text.
How can I get this at the whole div working?

A: The event.target is the element you clicked on. If you do not directly click on the div then your code will not match your tests because you are clicking on a child element.
So when you are using event delegation and you want to know if an element or one of its children is clicked on, you need to walk up the tree to see if it is that element. You can do that with closest

document.body.addEventListener("click", function(e) {
    if (e.target.closest('div.block')) {
      console.log('clicked', Date.now());
    }
});

Example

    foo bar kitten

A: welcome to SO. You can add the event listener on the div itself and then perform whatever code you like. The reason it doesn't work in your case is because you are adding the event listener to the whole body and thus as the event handler is called, it doesn't recognize the elements you are clicking on even if they are inside the div.
Try this instead:
document.querySelector('div#block').addEventListener("click", function(e) {
  // code...
});

A: Try to give an id to div and add your event listener to that.

    // your content goes here

And in javascript
const myDiv = document.getElementById("myDiv");
myDiv.addEventListener("click", (event) => {
   // your function goes here
})

A: There are many ways you can do it. But In my opinion the best way is to make anything clickable in JS is use onClick() function. You can simply use onClick=functionName()

function changeBackground(){
  let block =  document.getElementsByClassName('block');
  block[0].style.backgroundColor = "green";
}
.block{
  height: 50px;
  border : 1px solid;
}


text:
Q: How to use log4j's FileAppenders asynchronously? I work on a low-latency trading application. We'd like to increase the amount of lof4j logging that we write to file, whilst minimising the impact on our end-to-end processing time.
What is the recommended way of doing this? I think FileAppender.append is synchronous, so we need to do something a bit smarter than that....

A: Yes, the appenders are synchronous. You want something like this:
http://www.spartanjava.com/2009/asynchronous-logging-with-log4j/

A: bear in mind that AsyncAppender adds a thread per appender & that increasing the amount of logging you do may mean a substantial increase in the amount of string concatentation going on which often means a substantial amount of string processing/munging/formatting which can be pretty expensive (relative to the latency involved in a low latency trading app anyway).

A: If you need to log from a multithreaded application slf4j and its implementation logback are much better choice.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to rename rows with pattern in chunk using dplyr I have the following data frame (tibble):
library(tidyverse)
lines<-"
A,foo,9394981
B,bar,6826405
C,qux,1074885
D,gop,1493691
A,foo,100
B,bar,200
C,qux,300
D,gop,400
"
con <- textConnection(lines)
dat <- read.csv(con,header=FALSE)
close(con)
dat <- as.tibble(dat)
dat

The values in V2 comes in the chunk of four, i.e. always in foo, bar, qux, gop:
> dat
# A tibble: 8 × 3
      V1     V2      V3
  <fctr> <fctr>   <dbl>
1      A    foo 9394981
2      B    bar 6826405
3      C    qux 1074885
4      D    gop 1493691
5      A    foo     100
6      B    bar     200
7      C    qux     300
8      D    gop     400

How can I rename the row in V2 so that it becomes like this:
  A    foo.w 9394981
  B    bar.x 6826405
  C    qux.y 1074885
  D    gop.z 1493691
  A    foo.w     100
  B    bar.x     200
  C    qux.y     300
  D    gop.z     400

A: # If V2 is in the order of foo, bar, qux, gop
dat %>% mutate(V2=paste(V2, c("w", "x", "y", "z"), sep="."))
# A tibble: 8 × 3
      V1    V2      V3
  <fctr> <chr>   <dbl>
1      A foo.w 9394981
2      B bar.x 6826405
3      C qux.y 1074885
4      D gop.z 1493691
5      A foo.w     100
6      B bar.x     200
7      C qux.y     300
8      D gop.z     400

# If not, create a lookup
lookup <- c("foo"="foo.w", "bar"="bar.x", "qux"="qux.y", "gop"="gop.z")
dat %>% mutate(V2=lookup[as.character(V2)])
# A tibble: 8 × 3
      V1    V2      V3
  <fctr> <chr>   <dbl>
1      A foo.w 9394981
2      B bar.x 6826405
3      C qux.y 1074885
4      D gop.z 1493691
5      A foo.w     100
6      B bar.x     200
7      C qux.y     300
8      D gop.z     400


text:
Q: Calculate Kafka topic partitions I have an n node Kafka cluster with just 2 topics
I have replicated the topics across all n nodes
I 'think' I have just a single consumer in the form of a mirrormaker consuming all topics although I intend to increase that from 1 to n mirror makers
How many partitions should my topics use ? 1 then later n?

A: The number of nodes in your cluster (what you call "n") should be independent of the number of partitions in a topic (let's call that "p"). The max number of consumers in a consumer group (Mirror Maker or any other single group) will be p, but the number you actually need will be entirely driven by your throughput performance and message ordering requirements.


text:
Q: Change background color of drop down menu on select How to change colour of drop down menu. Like if i have a drop down menu with 5 options, when ever i click an option i want that option to change colour so that i can keep track which options i have already selected. ( 5 here is hypothetical, i have bigger list with IP`s and ports as field so cannot remember all the fields i have checked).
Lets just assume my drop down is
<select>
    <option val="">Please choose</option>
    <option val="1">Option 1</option>
    <option val="2">Option 2</option>
    <option val="3">Option 3</option>
    <option val="4">Option 4</option>
    <option val="5">Option 5</option>
</select>

A:

var select = document.getElementById('select');
select.onchange = function() {
  select.options[select.selectedIndex].style.backgroundColor = 'red';
}

var clean = document.getElementById('clean');
clean.onclick = function() {
    for(var i = 0; i < select.options.length; i++) {
      select.options[i].style.backgroundColor = '';
    }
}
<select id="select">
    <option val="">Please choose</option>
    <option val="1">Option 1</option>
    <option val="2">Option 2</option>
    <option val="3">Option 3</option>
    <option val="4">Option 4</option>
    <option val="5">Option 5</option>
</select>

<button type="button" id="clean">Clean</div>

A: Try this
 $('yourdropdownid option:selected').css('background-color', 'red');

A: Here you go:  DEMO
$('select option').click(function(){
    $(this).css('background','yellow');
});


text:
Q: Virtual Environment not activated after restarting VScode I installed the python extension for VSCode, and then created a new virtualenv .venv in my project directory.
If I press CTRL+SHIFT+P and select my environment, then open a new Terminal session, the new environment is automatically activated. However if I close VSCode and re-open it, then open a new Terminal session, the new environment isn't automatically activated. I can again manually activate it, however I would like it to activate automatically every time I open my project.
In my settings.json, I have tried using the following which was automatically filled by the extension:
"python.pythonPath": ".venv\\Scripts\\python.exe"

as well as
"python.pythonPath": "${workspaceFolder}/.venv/Scripts/python.exe"

Additionally, launching python and running the following indicates that it is using my root installation and no virtual environment:
>> import sys
>> sys.prefix
'C:\\Python37'

How can I get VSCode to automatically activate my environment after launch?

A: If you open the terminal before the Python extension has finished loading -- e.g. immediately after a restart -- then the terminal won't be activated because the extension isn't running yet to tell VS Code to run the command. Once you view a Python file then the extension will be triggered to load, and then once it's done -- you can tell as the message in the status bar about the loading will be gone -- then the terminal will automatically activate the virtual environment.


text:
Q: Django NameError When trying Access Data Here is the Code:
    from django.db import models

import datetime
from django.utils import timezone

class data_model(models.Field):
    description = "return and create data objects for visulaizations"

    def __init__(self, days, action):
        self.days = days
        self.action = action

        if(self.action == ""):
            self.action = "inspections"

        getVioPoints(self.action, self.days)
    #end init

    def getVioPoints(self):
        #get points
        if(self.action == "violations"):
            apendQuery = "where osha_violation_indicator is true"
        elif(self.action == "inspections"):
            apendQuery = "where osha_violation_indicator is false"
        else:
            apendQuery = ""

        from django.db import connections
        conn = connections['opengov_db'].cursor()

        conn.execute("""
            select distinct a.estab_name, b.latitude, b.longitude, a.site_address, a.site_city, a.site_state, a.site_zip
            from osha_inspection a
            join latitude_longitude_lookup b on cast(a.activity_nr as text)= b.source_data_id
            """,apendQuery,"""
            and close_case_date >= now() - interval """,self.days,""" days'
            and b.latitude is not null; """)

        row = conn.fetchone()
        print row

I am getting this error:
Unhandled exception in thread started by <function wrapper at 0x9d9656c>
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 93, in wrapper
    fn(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 101, in inner_run
    self.validate(display_num_errors=True)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 310, in validate
    num_errors = get_validation_errors(s, app)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/validation.py", line 34, in get_validation_errors
    for (app_name, error) in get_app_errors().items():
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/loading.py", line 196, in get_app_errors
    self._populate()
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/loading.py", line 75, in _populate
    self.load_app(app_name, True)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/loading.py", line 99, in load_app
    models = import_module('%s.models' % app_name)
  File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py", line 40, in import_module
    __import__(name)
  File "/var/www/opengov/mapPrototypePY/opengov/map/models.py", line 6, in <module>
    class data_model(models.Field):
  File "/var/www/opengov/mapPrototypePY/opengov/map/models.py", line 39, in data_model
    row = conn.fetchone()
NameError: name 'conn' is not defined

And I have no idea why. I know that the query is working. But, this seems to be ignoring conn on line containing row = conn.fetchone(). I have Googled around and found nothing of note. Any ideas?
Thanks

A: As mentioned in the comments, it was an indentation error.
The reason why you didn't get an actual IndentationError on run is because the code was still syntactically valid. Probably what happened was that the code was interpreted as being at the same level as the method definitions, at class level: it's perfectly possible to have code that that level, such as setting class-level variables, and the compiler (IndentationError is a compile-time exception) doesn't know that conn isn't in scope at that point.


text:
Q: Setting all the values of the objects to double type in R session How can one set all the objects/outputs' values to a double in R session.
Suppose a is a vector , it should return the double values even if the elements are integers.
After that suppose if I define a matrix, say mm then all the elements in the matrix should appear as double.
E.g.
Suppose mm is the matrix
mm=matrix(1:10, nrow=2)
> mm
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    3    5    7    9
[2,]    2    4    6    8   10

my desired output is:
> mm
         [,1]   [,2]    [,3]  [,4]   [,5]
    [1,]    1.0    3.0    5.0    7.0    9.0
    [2,]    2.0    4.0    6.0    8.0   10.0

Can anyone answer this?
Thank you very much.

A: Try: mm <- matrix(as.double(1:10), nrow=2)
then check via typeof(mm)
# "double"


text:
Q: How to calculate median absolute deviation in a cross validation scenario? In a cross validation scenario "leave one out" I want to measure how the estimated continuous variable fits with the observed variable. I learned from Wikipedia that the Median absolute deviation (MAD) could by used.
My question: How is the MAD to be calculated in this scenario? I have two ideas. The first is inspired from the definition of MAD where the center is the median of all deviations:

*

*Set the deviation $D_i = E_i - O_i$ for each corresponding estimated and observed outcome

*Calculate the median $M = \underset{i}{arg\;median}({D_i})$

*Set $MAD = \underset{i}{arg\;median}({|M-D_i|})$

The second one seems more appropriated to me in the context of cross validation:

*

*Set the deviation $D_i = E_i - O_i$ for each corresponding estimated and observed outcome

*Set $MAD = \underset{i}{arg\;median}{(|D_i|})$.

The last is the median of the absolute deviation between estimated and observed value, literally. However, it seems not to confirm to the definition given by Wikipedia.
What is the best solution in my scenario?
BTW: In the wikipedia article about the Mean absolute error I found an interesting comment about this issue:

The mean absolute error is a common measure of forecast error in time series analysis, where the terms "mean absolute deviation" is sometimes used in confusion with the more standard definition of mean absolute deviation. The same confusion exists more generally.

A: Wikipedia (emphasis mine):

For a univariate data set X1, X2, ..., Xn, the MAD is defined as the
  median of the absolute deviations from the data's median

Since you have observed values in your scenario, you are likely looking for something along the lines of Mean Absolute Error or Root Mean Square Error.
EDIT: (additional clarification from comments below)
For a univariate data set, MAD is a measure of the variability (i.e. what is the "average" deviation from the "average" value, using the median function to determine averages).
So as you compute it the first way, it tells you the variability among your errors, which isn't necessarily meaningful as a measure of how well your model fits.
In the latter way, you are computing something very close to MAE, but using median instead of the mean. This is a valid way to determine your goodness of fit, but I don't know why you wouldn't use the more common measures of MAE or RMSE.


text:
Q: POST array being deleted when page loads I'm having an issue guys, I POST data from a form to another page and do the following in relation to the code:
<?php
/*
 * Confirm Registration Page
 *
*/
    $course = $_POST['course_title'];
    $location = $_POST['course_location'];
    $date   = $_POST['course_date'];
    $qty    = $_POST['attendlist'];

    $_POST = array(); <------- Need to clear the POST array so handler is not
                               called first time user is on page.

    if (!empty($_POST)){
    $processOrder = register_course_handler(); <--- Handler
    }
?>
<?php get_header(); ?>
    <?php while ( have_posts() ) : the_post(); ?>

<?= $course . " " . $date ?>

<?= $location ?>

        <? the_content() ?>

        <form action="#" method="POST">

            Name
            Email
            Phone
            <? for($i = 0; $i < $qty; $i++):?>

Guest <?= $i + 1?>
                <input type="text" id="name" name="name">
                <input type="text" id="email" name="email"/>
                <input type="text" id="phone" name="phone"/>
                <input type="hidden" name="course_id" value="<?= the_ID() ?>"/>
                <input type="hidden" name="course_title" value="<?= the_title() ?>"/>
                <input type="hidden" name="course_date" value="<?= date("d-m-Y", strtotime(get_sub_field('date'))) ?>"/>
                <input type="hidden" name="course_location" value="<? the_sub_field('venue') ?>"/>
                <input type="hidden" name="course_applicant" value="<?= $user_ID ?>"/>

            <? endfor; ?>

        <input type="submit" value="Confirm Registration"/>
        </form>

    <?php endwhile; // end of the loop. ?>

<?php include 'order_panel.php'?>
<?php get_footer(); ?>

I would like the form to resubmit to the current page. I then have a handler in another file which will handle the submission. Currently the problem is that the handler never gets called because the POST array is cleared every time the page loads. The reason I tried clearing it was because if I did not then the handler would be called the first time the user is brought to the page.
Any advice on how I might fix this issue?
array (size=9)
  'name' => string '' (length=0)     <------- These fields are blank....
  'email' => string '' (length=0)
  'phone' => string '' (length=0)
  'course_id' => string '1063' (length=4)
  'course_title' => string 'Energy use in Mushroom Units' (length=28)
  'formSend2' => string '1' (length=1)
  'course_date' => string '23-07-2014' (length=10)
  'course_location' => string 'Teagasc, Thurles' (length=16)
  'course_applicant' => string '1' (length=1)

My HTML for the blank fields. I enter in values in browser but blank
<input type="text" id="name" name="name">
                <input type="text" id="email" name="email"/>
                <input type="text" id="phone" name="phone"/>

A: Send a hidden value:
<input type="hidden" name="formSend" value="1" />

Change the check from if (!empty($_POST)){ to
if (isset($_POST['formSend'])){

Don't do $_POST = array();.


text:
Q: What exactly are limits? So as far as I know, a limit of a function is the $y$ value that we get as $x$ gets closer and closer to the limit but remains distinct from the limit.
Also, limit when approached from right should be the same as limit when approached from left or else the limit does not exist.
The problem I have is with limits involving complex functions. I was watching a video on this and the presenter said that if we were to make a circle of radius $1$ around the $x$ value we input into the function,   the $y$ value will be in the same neighborhood.
Can someone please tell me what that is?

A: The point the guy in your lecture was making was right in line with what you were already understanding about limits.  Take for example the limit(X->0)  of 1/|x|.
If you approach X from the left, the y value approaches infinity.  Thus, the left-hand limit is infinity.
If you approach x from the right, the y value is also infinity.  Thus, the right-hand limit is infinity.
Since Left-hand limit = right-hand limit, the two limits are equal.
Now consider what the professor said about a circle.  If you draw a circle around 1/|X|  where X is really close to zero (can't use zero for obvious reasons) and X is positive, ten your circle will enclose both the left-hand side of the graph and the right.  That's what he means by being in the same neighborhood.
For a counter example, consider f(x) = 1/x.   As we approach from the left, the limit is  negative infinity.   As we approach from the right, the limit is positive infinity.  If you now draw your circle of radius 1 somewhere near X=0 for x positive, it will not incorporate the left-hand side of the function because it is negative.  Thus, the left-hand and right-hand limits are not in the same neighborhood.  Therefore, the limit does not exist.


text:
Q: Flash calling a FBJS  i use FBML for the FB application
I have a flash and the flash suppose to call a javascript on the page. I read so many websites trying to figure it out but still having problem.
Here is the Webpage with the javascript:
<fb:fbjs_bridge/>

call me now

           YOo

And here it is the Flash code.  (one frame. code is on the frame. with a text box "myvar1")
var connection:LocalConnection = new LocalConnection();
var connectionName:String = LoaderInfo(this.root.loaderInfo).parameters.fb_local_connection;
connection.allowDomain("apps.facebook.com", "apps.*.facebook.com");

function callFBJS():void{
    myvar1.text = "START";  // debugging purpose
    if (connectionName) {
        myvar1.text = "Connection now";  // debugging purpose
        var pArray = ['bs'];
        connection.send(connectionName, "callmenow", "callmenow", pArray);
        myvar1.text = "SENT";
    }
}

callFBJS();

Well, when I test, the flash loads. The code goes through everything and shows "SENT" in the flash text box. However, it doesn't seem like it is calling the javascript and changing the text in the HTML page.
Have I done something wrong?  I tried the ExternalInteface.call method but this doesn't work either.
ALSO, when i run it in FireFox, not error popup.
however, when i run it in IE, I got this:
VerifyError: Error #1033: Cpool entry 36 is wrong type.

ReferenceError: Error #1065: Variable FBJS is not defined.

A: Did you try changing:
connection.send(connectionName, "callmenow", "callmenow", pArray);

to
connection.send(connectionName, "callFBJS", "callmenow", pArray);


text:
Q: Content over footer So I have reviewed all of the posts about this and have tried everything...  My content is pushing my footer down as I want.  However, there is a very small portion of a div that is overlaying my footer.  It can be found at http://www. newshongumpto.org
Its only that bottom portion of the div and I cannot figure out why.  I had to move my footer css to the actual includes files as it wasn't find the media query to hide the footer on mobile but I digress.  I know, a lot going on here:
Site CSS:
@charset "UTF-8";

.navbar-nav> li > a {
  font-family: 'Arial';
  font-weight: bold;
  color: #000000;
  font-size: 15px;
}

.dropdown-menu > li > a {
    font-family: 'Arial';
  font-weight: bold;
    color: #000000;
    font-size: 15px;
}

.navbar-default {
  border-color: #000000;
}

.nav.navbar-nav a:hover {
  color: #206E38;
}

.dropdown-menu .dropdown .dropdown-toggle a {
    font-family: 'Arial';
    font-weight: bold;
    font-size: 15px;
}

.banner {
    /* Permalink - use to edit and share this gradient: http://colorzilla.com/gradient-editor/#ffffff+0,206e38+100&1+0,0.52+43,1+100 */
background: linear-gradient(-45deg, rgba(255,255,255,1) 0%, rgba(159,193,169,0.52) 43%, rgba(32,110,56,1) 100%); /* FF3.6-15 */
background: linear-gradient(-45deg, rgba(255,255,255,1) 0%,rgba(159,193,169,0.52) 43%,rgba(32,110,56,1) 100%); /* Chrome10-25,Safari5.1-6 */
background: linear-gradient(135deg, rgba(255,255,255,1) 0%,rgba(159,193,169,0.52) 43%,rgba(32,110,56,1) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#206e38',GradientType=1 ); /* IE6-9 fallback on horizontal gradient */

}

.ptobigtitle {
    font-family:'Anton', sans-serif;
    padding: 10px;

}

.ptosubtitle {
    font-family: 'Anton', sans-serif !important;
    padding-left: 10px;
    font-size: 30px;
    color: #535252;
}

.navbar-btn {
    float: right;

}

.btn-default {
    background-color: #206E38;
    color:#FFF;
}
.jumbotronimg {
    float: right;
}

.learnmorebtn {
    margin-left: 200px;

}

.articleheadline{
    font-family: 'Anton', sans-serif;
    font-size: 20px;
    background: #A1C2AB;
    color: #000;
    letter-spacing: 2px;
    padding: 5px;
    max-width: 400px;
    margin: 0 auto;
    margin-left: auto;
    margin-right: auto;
    margin-top: 10px;
    border-style: solid;
    border-width: 1px;
}

.info{

    text-align: center;
    top: 37px;
}

.rightinfo{

    text-align: center;
}

.footer {

    display:block;
    background:#CDCDCD;
    overflow:hidden;
    margin-bottom: 0;
    postion: fixed !important;
    height: auto;
    bottom: 0 !important;
    width: 100%;
    clear: both;

        }

.bottomfooter {
    color:#FFF;
    font-family: 'Arial';
    font-size: 10px;
    background: #CDCDCD;
    bottom: 0;
}

.footerheading {
    font-family: 'Anton', sans-serif;
    font-size: 18px;
    text-align: center;
    text-decoration: underline;

}

.form-inline{
    background: #CDCDCD;
}

#mc_embed_signup #mce-EMAIL{
    font-family: "Arial";
    font-size: 13px;
    padding: 5px;
    padding-top: 2px;
    margin-left:auto;
    margin-right:auto;
}

.callistcontainer {
    margin-left: auto;
    margin-right: auto;
    height: 150px;
    width: 300px;
    overflow: scroll;
}

.footertext{
    font-size: 11px;
    table-layout: fixed;
    width: 100%;
    height: auto;
    text-align: center;
    margin-left: auto;
    margin-right:auto;

}
.footerposition{
    font-weight: bold;
    text-align: right;
    padding-right: 10px;
    border-right: solid;
    border-width: 1px
}

.footername{

    border-width: 1px;
    text-align: center;
}

.footerphone{

    border-width: 1px;
    text-align: center
}

.footeremail {
    padding-left: 10px;

    border-width: 1px;
    text-align: center
}

.vl {
    border-right: solid;
    border-width:1px;
    border-color: #000000;
}

.footernavigation {
    text-align: center;
    color: #000000;
    font-size: 11px;
    margin-left:auto;
    margin-right: auto;
    border: none;
    border-collapse: separate;
    border-spacing: 20px 0

}
.footernavheader{
    text-align: center;
    text-decoration: underline;
    font-size: 11px
}
.copywrite{
    font-family: "Arial";
    font-size:11px;
    text-align: center;
    font-weight:bold;
    padding-top: 25px;

}

#mc-embedded-subscribe{
    -webkit-appearance: none;
    margin-left:285px
}
.paypal_btn{
display: inline-block;
font-family: "Gotham", "Helvetica Neue", "Helvetica", "Arial", "sans-serif";
font-size: 14px;
font-weight: 500;
color: #000000;
text-align: center;
padding: 5px 10px;
margin-top: 10px;
margin-left: 30px;
background: #FFD700;
border: solid;
border-width:thin;
border-color: #C5C5C5;
cursor: pointer;
outline: none;
border-radius: 3px;
}
.paypal_btn:hover{ background:#e7e7e7;
}

.shongumTitle{
    font-family: 'Anton', sans-serif !important;
    font-size: 20px;
    color: #767373;
    padding-right:5px

}
.store{
    margin-top:60px;
}

FOOTER CSS

HTML

    <?php include("includes/navigation.php");?>

Shongum Elementary School

Parent Teacher Organization - A Quest for Excellence

        Learn more »

 UPCOMING EVENTS

  <link href="http://www.newshongumpto.org/calendarScript/core/framework/libs/pj/css/pj.bootstrap.min.css" type="text/css" rel="stylesheet" />
<link href="http://www.newshongumpto.org/calendarScript/index.php?controller=pjFront&action=pjActionLoadCss&theme=5" type="text/css" rel="stylesheet" />

   LATEST NEWS

   GET INVOLVED!

<?php include("includes/footer.php");?>

FOOTER

<dmx-serverconnect id="serverconnect1" url="../dmxConnect/api/homePage/officerInfo.php"></dmx-serverconnect>

 Officers

      {{col_position}}
      {{col_firsrtName}} {{col_lastName}}
      {{col_phone}}
         {{col_email}}

Navigate

PTO

      About Us
      Membership

      Programs
      Classes

      Store
        Lunch Menu

     News
     Calendar

Randolph School District

      RAM Alerts
      District Calendar

Stay in Contact!

<link href="//cdn-images.mailchimp.com/embedcode/slim-10_7.css" rel="stylesheet" type="text/css">

<form action="https://ShongumPTO.us14.list-manage.com/subscribe/post?u=94f392b8b8898807cb75b5931&id=07d0e3a6fb" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>

    <input type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="Newsletter Signup" required>

<input type="text" name="b_94f392b8b8898807cb75b5931_07d0e3a6fb" tabindex="-1" value="">

<input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="btn btn-default">

</form>

 © <?php echo date("Y"); ?> Shongum Elementary School Parent Teacher Organization

A: You have this...
.info {
    text-align: center;
    top: 37px;
}

Remove the 37px and it will fix it.


text:
Q: "Task was canceled" errors on Azure website As traffic to our Azure website has increased, we've been seeing an increasing number of "A task was canceled" errors. A typical trace might look like this:
Fatal web api error: Controller: CustomerUserEventsController;
Url: http://app.payboard.com/api/organizations/9ddf55d1-e0c1-4a8f-9327-eef38682e090/addcustomeruserevent?callback=jQuery210035782216349616647_1398442710964&cookieId=05be2755-dc0d-414d-b0d2-ea1986a929c3&customerId=&customerName=&customerUserId=&customerUserFirstName=&customerUserLastName=&eventName=hr-index-GET&_=1398442710965;
Error: A task was canceled. ( at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__0.MoveNext())

We used to maybe get one a day; it's been increasing gradually, so that now we're getting a couple dozen.
You'll notice that there's only framework code in the stack trace - none of our code is in there at all. So I'm a bit at a loss for how to troubleshoot it. Any suggestions on how to approach tracking these down?

A: See the answer here:
ASP.NET Web API OperationCanceledException when browser cancels the request
And the WebAPI bug here:
http://aspnetwebstack.codeplex.com/workitem/1797
Basically, it's expected when an HTTP request is canceled, for instance, if the user closes the page that initiated the request. To keep it from showing up in your logs, basically, you just need to create a custom message handler that suppresses the error:
/// <summary>
/// See https://stackoverflow.com/questions/22157596/asp-net-web-api-operationcanceledexception-when-browser-cancels-the-request
/// </summary>
public class CancelledTaskBugWorkaroundMessageHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var response = await base.SendAsync(request, cancellationToken);

        // Try to suppress response content when the cancellation token has fired; ASP.NET will log to the Application event log if there's content in this case.
        if (cancellationToken.IsCancellationRequested)
        {
            return new HttpResponseMessage(HttpStatusCode.InternalServerError);
        }

        return response;
    }
}

A: Had the exact same problem. In my case the solution was to change the authority (an https URL) from https://login.windows.net/... to https://login.microsoftonline.com/... as it could not be reached anymore. I am not publishing the full authority as it is a specific one for our organisation. Theoretically the first one is more direct, so I used that based on advise from a Microsoft specialist. But if it cannot be reached then there is a problem. Will need to go figure out nw why it is unreachable.
Hope this will be a lead to resolve your issues.
Regards,
Coen.


text: Q: ubuntu power saving turn off screen I locked my session and left the desktop computer for several hours.  When I returned the screen was dimmed but still powered on, showing the purple "blank" screen.  How do I configure Ubuntu 20.04 to turn off everything, including the screen, that is not needed for reactivating the system?  Why am I only given the option to blank the screen after a time, not to power it off entirely to save power and wear and tear on the LCD.


text:
Q: PyTorch is running natively on M1 MacBook, but something isn't working properly I've just got an M1 MacBook Pro and have been working on getting my development environment set up. I have followed instructions to install PyTorch with mini-forge so that it will run natively.
To test this, I've been running the MNIST example code from here. The code runs fine and Activity Monitor shows me that it is running natively. However, something still seems to be wrong: when the exact same code is executed on my other machine accuracy of 99% is achieved usually after one epoch, and test loss is very low. On the M1 Macbook, although training loss goes down, test loss never drops below 2 and accuracy never exceeds 10% after 14 epochs.
Similar issues occurred when running other code, e.g. this produces a loss of nan at every step.
I haven't been able to find this issue mentioned anywhere else: PyTorch is running natively on the M1, but it just doesn't seem to be working correctly.
I'd appreciate any suggestions as to what might be causing this or how I might fix it.
Thanks!


text:
Q: Iterate list of directories and sub-directories to run a specific command under each of them in windows I have a parent folder containing several child folders. I am trying to run a bat script that runs a specific operation under the child folders. But, I do not want the script to run in all of the child folders. I need to exclude a few from the list. This is what I have now:
pushd
for /D %%i in (<<path To Parent>>\*) do call :$myFunc "%%i"
popd
exit /B

:$myFunc
for %%g in ("Child2"
"Child3") do ( if /I "%1"=="%%~g" goto match )
echo current directory: %1
exit /B

:$match
echo matched directory
exit /B

In the :$myFunc subroutine, I can do a cd %1 to enter that child directory and run my command then do a cd to come back to the parent folder. One thing I am trying to do before is to exclude the :$myFunc operation if the incoming folder is on my exclude list.
Folder tree:
ParentFolder
  Child1
  Child2
  Child3
  Child4

Given a sample folder structure like above, how can I not call myFunc when the for selects Child2 and Child3.
Any suggestions on how I can achieve this?

A: That's certainly possible and can be done with the following code (lots of changes):
@echo off
setlocal EnableDelayedExpansion

rem Set which folders to exclude. This is changeable and NOT HARDCODED:
set exclude_folders="Child2" "Child3"

for /F %%A IN ('dir /B /AD "<path to parent>"') do (
    if "!exclude_folders:%%~nxA=!" == "%exclude_folders%" (call :$myFunc "%%A" "%%~fA")
)
exit /b %errorlevel%

:$myFunc
pushd "%~2"
rem Do your commands here; don't use pushd again!
popd

Note that the first argument is the folder name if it is located it in %cd%. Else, it is full path. The second argument is optional and more general, but I am sure you will need it!
I have changed the code as follows:

*

*Created a variable named exclude_folders to list here the folders you want to execute.

*Created a for /F loop to loop through a command, (dir /B /AD) to loop through all folders, avoid hidden ones!

*If the folder name (%%~nxA) [used %%~nxA because folder may contain a dot (.)] is excluded from the exclude_folders and the variable changes (in other words if string foldername exists in exclude_folders) this means that the folder is blacklisted and the for loop will start with the next line, since there is no command for else. If the opposite happens, call subroutine $myFunc with two arguments: %%A and %%~fA

*Do some command in %~2 folder and return back to the loop.

*When the loop is finished, the script will exit.


text:
Q: How to pass a .cs parameter to Visual Studio WebTest QueryStringParameter? I have created a webtest in visual studio to perform a test on a Rest API.I have some code that generates a random serial number that i need to pass into my QueryString parameter is there anyway to do this? I noticed that i can bind xml, csv and a database to it for Dynamic values. Would i have to change my code to wright to a xml file or is it possible to perform a direct call to the method inside the .cs file? C# Langauge.
I want to do something like in the below method but i want the sessionToken.sessionToken() to be the method that was called from the .cs file.
QueryString Parameters
     generatedToken=sessionToken.sessionToken()

A: Write your code within the PreRequest method of a Web Test Request plugin, or call your method from the plugin. One of the last statements of the plugin should write the generated value to a context parameter, with code something like:
e.WebTest.Context["YourContextParameter"] = TheGeneratedValue.ToString();

The value of the query string parameter can then be in one of these styles
{{YourContextParameter}}

or
Some text{{YourContextParameter}}more text

With a little more effort you can pass the context parameter name as a parameter of the plugin.
It can be useful to add diagnostics from the plugin into the log; to showit has been called and to record its output. This can be done with a statement of the form:
e.WebTest.AddCommentToResult("Plugin result is " + TheGeneratedValue.ToString());

Another approach is to convert the entire webtest to a coded test, by using one of the command icons just above the webtest. That produces C# that you can edit as much as you want. However, that conversion is a one-way process. After doing it you cannot use the webtest editor to further change the test. Hence I recommend the plugin route.


text:
Q: document.onclick vs window.onclick Is there any difference between
document.onclick

and
window.onclick

event?

A: The JavaScript Window object is the highest level JavaScript object which corresponds to the web browser window.
The document object is the container for all HTML HEAD and BODY objects associated within the HTML tags of an HTML document. This could correspond to the top-most window, or an iframe within the window.
Update
After a quick test there really is no difference between the two. However, as others have said, window.onclick did not work when tested in IE8. So apparently the bottom line is that document.onclick is the preferred choice.

A: I've heard of some versions of IE not supporting window.onclick

A: The w3c describes the document as: "The Document interface represents the entire HTML or XML document. Conceptually, it is the root of the document tree, and provides the primary access to the document's data." (http://www.w3.org/TR/DOM-Level-2-Core/core.html#i-Document)
and window as: "...defines the Window object, which provides the global namespace for web scripting languages, access to other documents in a compound document by reference, navigation to other locations, and timers. The Window object is a long-standing de facto standard for HTML user agents. However, it should not be assumed based on this or the name "Window" that it is limited to HTML or to visual user agents." (http://www.w3.org/TR/Window/)
So to answer your question, depending on the browser there might not be any issue. But some browser vendors might implement them differently.

A: If there are any differences at all, I am not aware of any. I believe in the end the document references the window.


text:
Q: Is it possible to upload a file via FTP and reuse the same DATA port? We have a FTP Active client class we are using but we are trying to reuse the same data socket when
transferring more than 1 file. To understand the behavior, I just used the ftp.exe (Active) client
from Microsoft and then I uploaded 2 files as you can see below.
When using (Active) FTP client, the client issues a command PORT such as 192,168,150,80,14,178 (port 3762) for instance. Then the server on port 20 connects back to the client on its local port 3762 and the file is uploaded.
The problem is when I send the second file, the client issues another PORT command and it uses another local port such as 3763 for instance. This is the behavior of the Microsoft FTP client though.
However in our FTP class we have more control since we are doing all the bindings on all ports.
I did manage to transfer the second 2 file using the same client local port but at some point the server sends info to client to close that port and the second file transfer then fails.
Is there a way to go around that behavior? we cannot use PASSIVE ftp at this point.
Thanks
C:\>ftp
ftp> open 10.10.10.10
Connected to 10.10.10.10.
220 Microsoft FTP Service
User (10.10.10.10:(none)): USER01
331 Password required for USER01.
Password:
230 User logged in.
ftp> cd test
250 CWD command successful.
ftp> put c:\temp\test1.docx
c:\temp\test1.docx: File not found
ftp> put c:\temp\test1.docx
200 PORT command successful.
125 Data connection already open; Transfer starting.
226 Transfer complete.
ftp: 13097 bytes sent in 0.42Seconds 31.11Kbytes/sec.
ftp> put c:\temp\test2.docx
200 PORT command successful.
125 Data connection already open; Transfer starting.
226 Transfer complete.
ftp: 13095 bytes sent in 0.61Seconds 21.54Kbytes/sec.
ftp> quit
221 Goodbye.

Basically in C# this is what we do:
System.Net.IPEndPoint localEP = new IPEndPoint(IPAddress.Parse(sIPAddr), 4900);
listening_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listening_sock.Bind(localEP);
...
listening_sock.Listen(1);
...
//send PORT command
//send STOR command
listening_sock.Accept();
...
//transfer file (via stream);
...
//then try to issue another STOR command to transfer the file
//if the port is still open it will transfer some data but eventually the ports closes itself.

A: In active mode the server side of the data connection is on port 20. If the client reuses the same IP and Port on its side you have the same connection tuple (e.g. client_ip,client_port,server_ip,server_port) for consecutive connections. But, with TCP you have to wait some time before you can reuse the same tuple. This means, that in active mode the client needs to announce a new port for each new data transfer.
See also the RFC959 (FTP) section 3.3 "Data Connection Management".


text:
Q: ValueError: could not broadcast input array from shape (2,5,2) into shape (5,2) A n-dimensional array which is initialised as
features=np.empty(shape=(100,5,2), dtype=float)

and I am trying to add 3D array into it as
features[i,:] = features_next

features_next has shape (2,5,2).
However, it shows error,
ValueError: could not broadcast input array from shape (2,5,2) into shape (5,2).

here is the piece of code :
   features=np.empty(shape=((historical*2),5,2), dtype=float)
    i = 0
    while i < 50:
        state = self.getDictState(state_index)
        asks = state['asks']
        bids = state['bids']
        features_next = self.getNormalisedFeature(
            bids=bids,
            asks=asks,
            state_index=state_index,
            qty=qty,
            price=price,
            size=size,
            normalize=normalize,
            levels=levels
        )
        '''if i == 0:
            features = np.array(features_next)
        else:
            features = np.vstack((features, features_next))'''
        features[i,:] = features_next
        state_index = (state_index - 1)
    return features

Note : I am trying to replace commented 'if condition' with features[i,:] = features_next to make the code execution bit faster.

A: Its pretty simple, just one point to make features[i,:] has shape (5, 2) and feature_next has shape (2, 5, 2). I want to say that both are compatible shapes. But broadcasting is done on a smaller shape over a larger shape. SO there is error since you are doing revere. Also look up on broadcasting on numpy docs.
Next, this one I think will do
This does not directly solve your problem, but has some ideas about what you can try, like you can reshape your array before going in loop using features.shape = (50, 2, 5, 2).
import numpy as np

features=np.empty(shape=(100,5,2), dtype=float)
features_next = np.random.random((2, 5, 2))

features.shape = ((50, 2, 5, 2))

features[:] = features_next
features.shape = (100, 5, 2)


text:
Q: jQuery Validation Plugin ErrorPlacement inside two different elements I'm trying to place separate error messages in separate elements when validating a large form.  The form is divided into jQueryUI tabs, then accordions.
When there is an error in an element of a tab, I want to append a red exclamation point to the name of the tab, and if the error is in an accordion element, I also want to append the red exclamation point to the name of the accordion element.
Subsequently, when the errors are corrected, I would like those red ! to be removed (exactly as the error message beneath the invalid field is removed.
So:
Tab1
Tab2
   Accordion1
   Accordion2
Tab3
If the elements in accordion 2 have an error, I want to append a red ! to accordion2 and tab2:
Tab1
Tab2!
   Accordion1
   Accordion2!
Tab3
Then remove when the elements successfully validate.  I've been trying forever, but I can't figure out how to conditionally change the errorElement (a label won't work for the tab and accordion, but is perfect for the actual element)...
Hopefully this makes sense, and thanks for any input you can provide.

A: You should try using the errorcontainer option
$("#myform").validate({
   errorContainer: "#Accordion2"
})

Edited
$("#myform").validate({
   showErrors: function(errorMap, errorList) {
       //error define where the errors in the ErrorList Go
       //you could also try
       this.errorContainer = "element1id, element2id"
   }
})

Edited2
Note: I am not testing this code. just providing you ideas.
$("#myform").validate({
   errorPlacement: function(error, element) {
        error.appendTo( element.closest('.tab'));

   }
})


text:
Q: ASP.NET Web Application Restarting When Using Entity Framework I have created an ASP.NET web application (4.7.2) in Visual Studio 2019. When it starts up, using the Entity framework (6.2.0), it talks to a database and retrieves some information from a table. However once that operation has completed the web application restarts i.e. WebApiApplication::Application_End gets called.
After some investigation it turns out .edmx files are being created in the bin folder when the application starts and because the content of the bin folder has changed the web application restarts. When it starts again those same .edmx files are recreated, the contents of the bin folder has therefore changed and therefore the web application restart again.
I then created a console application to see if I had the same problem. The first time I run it the .edmx files are created, however when I run it again the .edmx are NOT recreated.
So I guess my question is what are the possible reasons these .edmx files are being recreated every time I start the web application?


text:
Q: get n smallest values of multidimensional xarray.DataArray I'm currently working with some weather data that I have as netcdf files which I can easily read with pythons xarray library
I would now like to get the n smallest values of my DataArray which has 3 dimensions (longitude, latitude and time)
When I have a DataArray dr, I can just do dr.min(), maybe specify an axis and then I get the minimum, but when I want to get also the second smallest or even a variable amount of smallest values, it seems not to be as simple
What I currently do is:
with xr.open_dataset(path) as ds:
    dr = ds[selection]
    dr = dr.values.reshape(dr.values.size)
    dr.sort()
    n_smallest = dr[0:n]

which seems a bit complicated to me compared to the simple .min() I have to type for the smallest value
I actually want to get the times to the respective smallest values which I do for the smallest with:
dr.where(dr[selection] == dr[selection].min(), drop=True)[time].values

so is there a better way of getting the n smallest values? or maybe even a simple way to get the times for the n smallest values?
maybe there is a way to reduce the 3D DataArray along the longitude and latitude axis to the respective smallest values?

A: I just figured out there really is a reduce function for DataArray that allows me to reduce along longitude and latitude and as I don't reduce the time dimension, I can just use the sortby function and get the DataArray with min values for each day with their respective times:
with xr.open_dataset(path) as ds:
    dr = ds[selection]
    dr = dr.reduce(np.min,dim=[longitude,latitude])
    dr.sortby(dr)

which is obviously not shorter than my original code, but perfectly satisfies my demands


text:
Q: Stop video recording by pressing Home button How do I safely stop video recording on AVFramework, when home button is pressed?
I want my app to work like the native camera app: when you press the home button during recording it stops the recording process and then goes to the background mode.
On my app delegate, I call [[videoController captureManager] stopRecording]; but in recordingDidFinishToOutputFileURL I get an error which says:

Stop any other actions using the recording device and try again.

A: I would suggest putting the call to stop your video recording in your app delegate's applicationWillResignActive: method. This method is triggered when your app moves from being active to being inactive, which, according to the UIApplicationDelegate docs, occurs:

... for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.

The code would look something like this:
- (void)applicationWillResignActive:(UIApplication *)application
{
    [[videoController captureManager] stopRecording];

    // Do anything else before app becomes inactive
}

A: Try recovering recorded video...
    - (void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error
    {
        BOOL recordedSuccessfully = NO;
        if ([error code] != noErr)
        {
            if(outputFileURL)
            {
                NSFileManager* manager = [NSFileManager defaultManager];
                NSString* path = outputFileURL.path;
                if([manager fileExistsAtPath:path])
                {
                    NSError *attributesError = nil;
                    NSDictionary *fileAttributes = [manager attributesOfItemAtPath:path error:&attributesError];
                    NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
                    long long fileSize = [fileSizeNumber longLongValue];
                    if(fileSize > 0)
                    {
                        NSLog(@"Recording finished with error, but trying to save whatever recorded");
                        // save whatever we have to camera roll.
                    }
                }
            }
        }
    }


text:
Q: Probability of finding $ε$-approximate median of an array I'm given an array $A$ = ($a_1, a_2, \cdots a_n$), where n is uneven. For an element $a_i$ we denote its position in the array with $p(a_i)$. This element would be an $ε$-approximate median of the array, if after we sort it, the following inequality holds:
$$\frac12 ((1 - ε) × n) < p(a_i) \leqslant \frac12 ((1 + ε) × n)$$
For example, the array $1,2,\cdots,9$ would have $4,5,6$ as $\dfrac13$-approximate medians.
My task is to analyze the following randomized algorithm, which finds an $ε$-approximate median of the array in constant time:

Choose $2k + 1$ elements of the array $A$: $b_1, b_2, \cdots, b_{2k+1}$, where each element is chosen uniformly randomly and independently of all the others (it is possible for an element to repeat). Using the algorithm for finding a median of an array in linear time (QuickSelect) output the median of the array the elements $b_1, b_2, \cdots, b_{2k+1}$ form.

I'm also given the following two random variables:
$K$: number of elements in $b_1, b_2, \cdots, b_{2k+1}$, which are smaller or equal to the $\dfrac12 ((1-ε)×n)$-biggest element in the original array
$A$.
$G$: number of elements in $b_1, b_2, \cdots, b_{2k+1}$, which are bigger than the $\dfrac12 ((1+ε)×n)$-biggest element in the original array $A$.
What I have to do is find the best possible upper bounds for
$$P(K \geqslant (1 + ε) E(K))$$
and
$$P(G \geqslant (1 + ε) E(G)),$$
where $E(K)$ and $E(G)$ are the expected values for the random variables. I also have to find a bound for the probability the algorithm will be successful, which depends only on $k$, not on $n$, $E(K)$ or $E(G)$.
What I have done so far: I computed the expected values for the two random variables. I believe they are binomially distributed, so for example for $K$ I have $2k + 1$ events each with probability $\dfrac12(1-ε)$ to happen, so
$$E(K) = (2k + 1) × \dfrac12 (1 - ε).$$
$E(G)$ turns out to be the same. Then I tried computing the two upper bounds, mentioned above with the Markov, Chebyshev and Chernoff inequalities:
Markov:
$$P(K \geqslant (1 + ε) E(K)) \leqslant \frac1{1 + ε},$$
Chebyshev (might be false):
$$P(|K - E(K)| \geqslant εE(K)) \leqslant \frac{\operatorname{Var}(K)}{ε^2 × (E(K))^2} = \frac{1}{ε(2k + 1)},$$
Chernoff:
$$P(K \geqslant (1 + ε) E(K)) \leqslant \exp\left( -\frac13 ε^2 E(K) \right).$$
Are these correct? If they are, am I correct that Chebyshev is the best one? How do I continue with finding the probability of success of the algorithm?
Thank you :)

A: The literature credits Manku et al. for solving this problem in section 5: "A Sampling based Algorithm" of their paper DOI:10.1145/276304.276342: Approximate Medians and other Quantiles in One Pass and with Limited Memory.
Beware that the OP notes $ε$ the whole confidence interval, whereas Manku et al. note $ε$ only half the confidence interval.
First observation is that if $K$ and $G$ are both less than $\frac{2k+1}2$, then the median of the sample is an ε-approximate median.
Taking $1-δ$ as the wanted level of confidence that the sample is good, then it's enough to ensure that both:
$$
P(K \ge \frac{2k+1}2) \le \fracδ2\\
P(G \ge \frac{2k+1}2) \le \fracδ2
$$
Because $K$ and $G$ are both independent Bernoulli trials of $2k+1$ events, each with probability $\frac{1−ε}2$ to happen, $E(K) = E(G) = (1-ε)\frac{2k+1}2$, therefore:
$$
P(K \ge \frac{2k+1}2) = P(K - E(K) \ge ε\frac{2k+1}2)\\
P(G \ge \frac{2k+1}2) = P(G - E(G) \ge ε\frac{2k+1}2)
$$
Then, by Hoeffding's inequality:
$$
P(K \ge \frac{2k+1}2) \le \exp(\frac{-2ε²(\frac{2k+1}2)²}{2k+1})\\
P(G \ge \frac{2k+1}2) \le \exp(\frac{-2ε²(\frac{2k+1}2)²}{2k+1})
$$
(Here I believe there's a typo in the paper and that $S²$ should be $\frac{S²}S$, hopefully the error is no longer present when the authors determine $S$ from $ε$ and $δ$.)
By the union bound, it's then enough to ensure:
$$
\exp(-ε²\frac{2k+1}2) \le \fracδ2
$$
Then, fixing $δ$ enables to determine a lower-bound for the number of samples, also independent of $n$:
$$
\frac2{ε²}\log(\frac2{δ}) \le 2k+1
$$
As a side note, there's also a related paper DOI: 10.3150/14-BEJ605 by Rémi Bardenet and Odalric-Ambrym Maillard: Concentration inequalities for sampling without replacement, stating that the sampling without replacement enables to improve Hoeffding's bound with an Hoeffding–Serfling bound depending upon $n$ which is close for a sample size below $\frac{n}2$, but decreases to zero above this point, outperforming Hoeffding's bound.


text:
Q: Firebase validate email I'm familiar only with regex when validating strings of data. What I'm trying to do, is validate a specific email address when creating a user in Firebase.
auth.createUserWithEmailAndPassword
  btnSignUp.addEventListener('click', e => {
    // Get email and pass
    const email = txtEmail.value;
    const pass = txtPassword.value;
    const auth = firebase.auth();
    // Sign in
    const promise = auth.createUserWithEmailAndPassword(email, pass);
  });

How can I validate the email that is passed through the EventListener and make sure it matches a specific email address (ex. gmail.com)?


text:
Q: Trigger Sidebar from two different button using State in React && styled-components The first button:
const [open, setOpen] = useState(false);
  return (
    <>
      <SideCart open={open} />
      <CartButton open={open} onClick={() => setOpen(!open)}>
      )
    </>

The sidebar:
const [hide, setHide] = useState(open ? true : true);
  return (
    <SidecartContainer open={open} hide={hide}>

       // Thats the second button
       // I want to close the sidebar component with this button
      <ExitButton hide={hide} onClick={() => setHide(!hide)}>
    </SidecartContainer>

const SidecartContainer = styled.div`
  transform: ${({ open, hide }) =>
    open && hide ? "translateX(0)" : "translateX(100%)"};
`;

I have one button triggering the Open state of sidebar and when it opens I have an x button to close the sidebar.
It only works once.
What shall I use so whenever I click the open button to open and then when I click on close to hide?
It's made with styled-components.

A: I think your problem is that this line const [hide, setHide] = useState(open ? true : true); only runs once on component mount. What you need is a useEffect in the sidebar to listen for changes to open and apply them to the hide state like so:
const [hide, setHide] = useState(open ? true : true);

useEffect(() => {
  setHide(!open);
}, [open]);

  return (
    <SidecartContainer open={open} hide={hide}>

--------Thats the second button
--------I want to close the sidebar component with this button
      <ExitButton hide={hide} onClick={() => setHide(!hide)}>

    </SidecartContainer>

A: I finally found what's the right way to do it and it works.
First I declared outside of the sidebar the useStates logic:
  const [open, setOpen] = useState("");
  const hide = () => setOpen("translateX(100%)");
  const show = () => setOpen("translateX(0)");

then I passed the props to Sidecart.js:
const SideCart = (props) => {
  return (
    <SidecartContainer transform={props.transform} open={props.open}>
      <ExitButton open={props.open} onClick={props.onClick}>
        <CloseIcon />
      </ExitButton>
      <ProductCards>
        <CartProductCard />
      </ProductCards>
      <Total></Total>
    </SidecartContainer>
  );
};

also this is important, in the styled component css I declared the prop value:
const SidecartContainer = styled.div`
  transform: ${(props) => props.transform};
`;

Finally I changed the onClick functions accordingly:
  <SideCart transform={open} open={open} onClick={hide} />
  <CartButton open={open} onClick={show}>


text:
Q: How to find object in php array and delete it? Here is print_r output of my array:
Array
(
[0] => stdClass Object
    (
        [itemId] => 560639000019
        [name] => Item no1
        [code] => 00001
        [qty] => 5
        [id] => 2
    )

[1] => stdClass Object
    (
        [itemId] => 470639763471
        [name] => Second item
        [code] => 76347
        [qty] => 9
        [id] => 4
    )

[2] => stdClass Object
    (
        [itemId] => 56939399632
        [name] => Item no 3
        [code] => 39963
        [qty] => 6
        [id] => 7
    )

)

How can I find index of object with [id] => 4 in order to remove it from array?

A: foreach($parentObj AS $key=>$element){
  if ($element->id == THE_ID_YOU_ARE_LOOKING_FOR){
    echo "Gottcha! The index is - ". $key;
  }
}

$parentObj is obviously your root array - the one that holds all the others.
We use the foreach loop to iterate over each item and then test it's id property against what ever value you desire. Once we have that - the $key that we are on is the index you are looking for.

A: use array_search:
$a = new stdClass;
$b = new stdClass;
$a->id = 1;
$b->id = 2;

$arr = array($a, $b);
$index = array_search($b, $arr);

echo $index;
// prints out 1

A: $found = false;
foreach($values as $key => $value) {
    if ($value->id == 4) {
        $found = true;
        break;
    }
}

if ($found) unset($values[$key]);

This is considered to be faster then any other solution since we only iterate the array to until we find the object we want to remove.
Note: You should not remove an element of an array while iterating so we do it afterwards here.

A: try this
foreach($array AS $key=>$object){
   if($object['id'] == 4){
       $key_in_array = $key;
   }
}

// chop it from the original array
array_slice($array, $key_in_array, 1);

A: Another way to achieve the result is to use array_filter.
$array = array(
    (object)array('id' => 5),
    (object)array('id' => 4),
    (object)array('id' => 3)
);
$array = array_filter($array, function($item) {
    return $item->id != 4;
});
print_r($array);

A: Here's my solution. Given, it is a bit hackish, but it will get the job done.
search(array $items, mixed $id[, &$key]);
Returns the item that was found by $id. If you add the variable $key it will give you the key of the item found.
function search($items, $id, &$key = null) {
  foreach( $items as $item ) {
    if( $item->id == $id ) {
      $key = key($item);
      return $item;
      break;
    }
  }

  return null;
}

Usage
$item = search($items, 4, $key);
unset($items[$key]);

Note: This could be modified to allow a custom key and return multiple items that share the same value.
I've created an example so you can see it in action.

A: A funny alternative
$getIdUnset = function($id) use ($myArray)
{
    foreach($myArray as $key => $obj) {
        if ($obj->id == $id) {
            return $key;
        }
    }

    return false;
};

if ($unset = $getIdUnset(4)) {
    unset($myArray[$unset]);
}

A: Currently php does not have any supported function for this yet.
So refer to Java's Vector, or jQuery's $.inArray(), it would simply be:
public function indexOf($object, array $elementData) {
    $elementCount = count($elementData);
    for ($i = 0 ; $i < $elementCount ; $i++){
        if ($object == $elementData[$i]) {
            return $i;
        }
    }
    return -1;
}

You can save this function as a core function for later.

A: In my case, this my array as $array
I was confused about this problem of my project, but some answer here helped me.
array(3) {
           [0]=> float(-0.12459619130796)
           [1]=> float(-0.64018439966448)
           [2]=> float(0)
         }

Then use if condition to stop looping
foreach($array as $key => $val){
           if($key == 0){ //the key is 0
               echo $key; //find the key
               echo $val; //get the value
           }
        }

A: I know, after so many years this could be a useless answer, but why not?
This is my personal implementation of a possible index_of using the same code as other answers but let the programmer to choose when and how the check will be done, supporting also complex checks.
if (!function_exists('index_of'))
{
    /**
     * @param iterable $haystack
     * @param callable $callback
     * @param mixed|null &$item
     * @return false|int|string
     */
    function index_of($haystack, $callback, &$item = null)
    {
        foreach($haystack as $_key => $_item) {
            if ($callback($_item, $_key) === true) {
                $item = $_item;
                return $_key;
            }
        }
        return false;
    }
}

A: foreach( $arr as $k=>&$a) {
    if( $a['id'] == 4 )
        unset($arr[$k]);
}


text:
Q: How to properly update location when requesting permission at run time? I am trying to update the users location every second (every second I want a log message to appear which contains the actual position of the user), for this I have to ask the user at run time if he wants to allow the app to get access to his position only once (I have to ask because API 24 requires this). After the user has accepted the app does not ask again.
But onLocationChanged does not get called.
@Override
protected void onCreate(Bundle bundle) {
    //initializing UI
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
}

@Override
protected void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
}

@Override
public void onConnected(Bundle bundle) {
    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_LOW_POWER);
    mLocationRequest.setInterval(1000);

    if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
            return;
        }
        else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        }
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    if(requestCode == 1) {
        if(grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults.length > 0) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
    }
}

@Override
public void onLocationChanged(Location location) {
    Log.i("LOCATION", location.toString());
}


text:
Q: trying to copy row from one workbook to another I am currently trying to make a macro to pull all of the data from a specific row on my sales quote template workbook and then make it paste into the next available row on my quote logger workbook but im really struggling to find the right code to make it work. ive searched around but found nothing concrete that I could use.
what I have so far is below.
Option Explicit
Sub Test()

Dim sht1 As Worksheet, sht2 As Worksheet
Dim i As Long

Set sht1 = ThisWorkbook.Worksheets("Sheet1")
Set sht2 = "..............RAYOTEC LOGGER.xlsm"

For i = 2 To sht1.Cells(sht1.Rows.Count, "M").End(xlUp).Row
    If sht1.Range("M" & i).Value = "No" Then
        sht1.Range("A" & i).EntireRow.Cut sht2.Range("A" & sht2.Cells(sht2.Rows.Count, "M").End(xlUp).Row + 1)
    End If
Next i

End Sub

Thanks in advance for any help

A: Change the part of your code before FOR loop with this,
Dim sht1 As Worksheet
Dim sht2 As Worksheet
Dim wb As Workbook
Dim i As Long

Set sht1 = ThisWorkbook.Worksheets("Sheet1")
Set wb = Application.Workbooks.Open("..............RAYOTEC LOGGER.xlsm")
Set sht2 = wb.Sheets("Sheet1")

A: Also you can use the below for the rest of the code as it just takes the values easily and deletes the row data that you do not need.
Dim sht1 As Worksheet
Dim sht2 As Worksheet
Dim i, n As Long
Dim iMx, nMx As Long

iMx = sht1.Cells(sht1.Rows.Count, "M").End(xlUp).Row

For i = 2 To iMx

    nMx = sht2.Cells(sht2.Rows.Count, "A").End(xlUp).Row
    If sht1.Range("M" & i).Value = "No" Then
        sht2.Range("A" & nMx + 1).EntireRow.Value = sht1.Range("A" & i).EntireRow.Value
        sht1.Range("A" & i).EntireRow.Delete Shift:=xlUp
        i = i - 1
    End If

Next i


text:
Q: Data structure to check if there are any points under query line segment Let P be a set of points, where no three points are colinear and no two points have the same x- or y-coordinates. What is a good way of preprocessing P so that one can easily do queries in the below form:
Given a line segment q, are there any points of P vertically below q? If a point is not within the x-range of q, we do not consider it to be "below" q.

A: Sort $P$ by increasing $x$-coordinate. Then, when a line segment is given by its two endpoints $a$ and $b$, where $a$ has a lower $x$-coordinate, we do the following:

*

*Remove from consideration all points not under the segment. Since the points were sorted, this is just two binary searches and array lookup.

*For each point $p$ that remains test whether it lies under the line segment. This may be done most efficiently by a cross product computation: $p$ is under iff $(p-a)×(b-a)>0$. (All letters refer to position vectors in this answer.)

A: I am considering point-line duality and have been experimenting with the following tool:
https://people.eng.unimelb.edu.au/henli/programs/duality-demo/
In the dual plane, $q$ forms a wedge while point $p$ is a line.
You can observe that if $p$ is not in the $x$-range of $q$, then its line (in dual form) spans the (negative) top and bottom sides of the wedge of $q$. If the point is vertically above or below the line segment, the line spans (positive) left and right sides of the wedge.
Ensuring that the point is strictly below the line segment is a matter of checking that the line is above the intersection point of the two lines forming the wedge in the dual plane.
I think the data structure in question would be an arrangement of lines.
P.S. I would have commented but my reputation is too low to do so on this StackExchange. I would like to hear what others think.


text:
Q: How to set the input channels size? It is an assignment using pytorch for hand gesture recognition.
Code:
D = np.array(Images).astype('float32')
y = np.array(Labels).astype(int)

for i in tqdm(range(X.shape[0])):
    train_data.append(X[i]) # original image
    train_data.append(rotate(X[i], angle = 45, mode = 'wrap'))
    train_data.append(np.fliplr(X[i]))
    train_data.append(np.flipud(X[i]))
    train_data.append(random_noise(X[i], var = 0.2 ** 2))

    for j in range(5):
        target_train.append(Y[i])

class Net(nn.Module):

    def __init__(self, num_classes = 5):

        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(in_channels = 1, out_channels = 12, kernel_size = 3, stride = 1, padding = 1)
        self.conv2 = nn.Conv2d(in_channels = 12, out_channels = 24, kernel_size = 3, stride = 1, padding = 1)
        self.pool = nn.MaxPool2d(kernel_size = 2)
        self.drop = nn.Dropout2d(p = 0.2)
        self.fc1 = nn.Linear(in_features = 19.5 * 19.5 * 24, out_features = 120)
        self.fc2 = nn.Linear(in_features = 120, out_features = num_classes)

    def forward(self, x):

        x = F.relu(self.pool(self.conv1(x)))
        x = F.relu(self.pool(self.conv2(x)))
        x = F.dropout(self.drop(x), training = self.training)
        x = x.view(-1, 19.5 * 19.5 * 24)
        x = F.relu(self.fc1(x))
        x = self.fc2(x)

Error:

RuntimeError: Given groups=1, weight of size [8, 1, 3, 3], expected input[1, 32, 78, 78] to have 1 channels, but got 32 channels instead

Size of X: (2080, 300, 300, 3)
Size of y: (2080,)
How do I set the input channel size for the fc1(fully connected layer 1)?

A: The input should be of the format [batch_size, channels, height, width] in PyTorch, so you have to change your input to (2080, 1, 300, 300) instead of (2080, 300, 300, 3). As per your NN architecture, the input should be single channel and not 3 channel.
Also,
x = x.view(-1, 19.5 * 19.5 * 24)
will throw an error if the input size and 19.5 * 19.5 * 24(i.e. 9126) are not divisible.
Fixing these 2 things should solve the problem.


text:
Q: Should I use a header for a table view controller or table inside scroll view? I'm making a chores app for fun/learning and I'm not sure the right way to implement the UI for my main page.  Here's my design below. I'd like the top score animation + the blue bar to stay put, while the chores table below it scrolls separately.
Should I use a header for a table view controller to do this, or make the chores table part of a scroll view for the entire page (or another better solution than either of these)?
I'm using Storyboard. The scores section will contain a seesaw animation, and the blue bar is a horizontal ticker with text scrolling in from the right.


text:
Q: updating summary sheet with values from multiple sheets in difference cells I am quite new to VBA, I have attempted to write a code below, but I'm getting a type mismatch error (Highlighted below). What I am trying to achieve is the following:
I have a list of properties on column A (all hyperlinked to their own respective sheets) on the first summary sheet called "sheet"

*

*For each property, go to that properties sheet

*Copy the value 3 cell right to the cell with the string "Total for this Property"

*Switch back to "sheet" and paste the value into column D, next to the corresponding property name in column A.

I think the issue is the way I am referencing the value in the other sheet, but I can't seem to find anywhere how to reference a value that is located somewhere relative to a cell with a specific text.
Thank you in advanced!
Sub Summary()

    Dim MasterBook As Workbook
    Dim Sht As Worksheet
    Dim Rng, Rng2 As Range

    Set MasterBook = ThisWorkbook
    Set Sht = MasterBook.Worksheets("Sheet")
    Set Rng = Sht.Range("A6:A" & Sht.Cells(Sht.Rows.Count, "A").End(xlUp).Row)

    Dim Cell As Range

    For Each Cell In Rng
    Cell.Hyperlinks(1).Follow NewWindow:=False, AddHistory:=True
    Cell.Offset(0, 3).Value = Cell.Value("Total for this Property").Offset(0, 3).Value  '<---- This line is giving the error

    Next Cell
End Sub

A: Try this
Sub Summary()

Dim MasterBook As Workbook
Dim Sht As Worksheet
Dim Rng As Range, Rng2 As Range, Rng3 As Range

Set MasterBook = ThisWorkbook
Set Sht = MasterBook.Worksheets("Sheet")
Set Rng = Sht.Range("A6:A" & Sht.Cells(Sht.Rows.Count, "A").End(xlUp).Row)

Dim Cell As Range

For Each Cell In Rng
    Set Rng3 = MasterBook.Sheets(Cell.Text).Cells.Find(What:="Total for this Property", LookIn:=xlValues, LookAt:=xlWhole, _
                 MatchCase:=False, SearchFormat:=False)
    If Not Rng3 Is Nothing Then
        Cell.Offset(0, 3).Value = Rng3.Offset(, 3).Value
    Else
        MsgBox "not found"
    End If
Next Cell

End Sub

A: It's no wonder that this line is giving you trouble:
Cell.Offset(0, 3).Value = Cell.Value("Total for this Property").Offset(0, 3).Value

The Value property doesn't take arguments like this! I assume you are trying the find the cell with the text Total for this Property and offset 3 from it?
In that case you should look into the Find command.
Dim myFoundCell as Range
Set myFoundCell = ActiveWorkbook.ActiveSheet.UsedRange.Find(what:="Total for this Property", lookat:=xlWhole)
If Not myFoundCell Is Nothing Then
    Cell.Offset(0, 3).Value = myFoundCell.Offset(0,3).Value
End If

I think you'll also have trouble handling which workbook you're in (the ActiveWorkbook) after following a load of hyperlinks, so look into ActiveWorkbook and ThisWorkbook. What I mean is, that each range must be within a sheet on a given workbook. You're trying to copy across workbooks so will have to specify where data is going to / coming from.
Docs for Find: https://msdn.microsoft.com/en-us/library/office/ff839746.aspx
Another question when you get stuck perhaps.

A: I guess you're after this:
Sub Summary()
    Dim Cell As Range, foundCell As Range

    With ThisWorkbook.Worksheets("Sheet")
        For Each Cell In .Range("A6", .Cells(.Rows.count, "A").End(xlUp))
            Cell.Hyperlinks(1).Follow NewWindow:=False, AddHistory:=True
            Set foundCell = ActiveSheet.UsedRange.Find(what:="Total for this Property", lookat:=xlWhole, LookIn:=xlValues)
            If Not foundCell Is Nothing Then Cell.Offset(0, 3).Value = foundCell.Offset(0, 3).Value  '<---- This line is giving the error
        Next Cell
        .Activate
    End With
End Sub

A: Since you want to "fetch" the value from a certail Worksheet (which name is placed in the cell) and not in the entire Workbook, you need to use the Find for that specific Worksheet.
The Find method syntax for that is :
Set FindRng = Worksheets(Cell.Value).Cells.Find("Total for this property")

Sub-loop Code:
Dim Cell As Range, FindRng As Range

For Each Cell In Rng
    Cell.Hyperlinks(1).Follow NewWindow:=False, AddHistory:=True

    Set FindRng = Worksheets(Cell.Value).Cells.Find("Total for this property")

    If Not FindRng Is Nothing Then    ' verify that Find was successful
        Cell.Offset(0, 3).Value = FindRng.Offset(0, 3).Value
    End If
Next Cell


text:
Q: 'ptr_fun(isalnum)' won't compile in g++? I am attempting to compile a program in g++ which compiled fine in Visual Studio 2012.
I am receiving the error :  error: no matching function for call to 'ptr_fun(<unresolved overloaded function type>)'
To the best of my knowledge, I have included all the library and header files that I need. What am I missing?
Here is my code:
#include <iostream>
#include <string>
#include <algorithm>
#include <iostream>
#include <string>
#include <functional>
#include <ctype.h>
#include <stdio.h>

using namespace std;

int main() {

    string secretWord; //to store our secret word
    string secretWordClean = ""; //given an initial value so that we can add the alpha-only characters from secretWord
    string guessedLetters; //to be loaded with _ characters equal to length of secretWord
    string incorrectlyGuessedChars = ""; //for storing our incorrectly guessed characters to be show to the user
    char individualCharGuess; //to temporarily store the individual char guess of the user
    char playAgain; //will be set to Y to play again, and tested in an if statment
    size_t countOfLetters = 0; //begine count at 0
    size_t guessesRemaining; //to store the remaining guesses of the user, will be decrimented each iteration
    int guessedUsed; //to calulate how many guesses the player used when game is complete

begin_game://label which we can use to bring us back to the start of the do-while loop at any time

    cout << "Please enter a secret word: ";

    std::cin >> std::ws;
    getline(std::cin, secretWord);
    secretWord.erase(std::remove_if(secretWord.begin(), secretWord.end(), std::not1(std::ptr_fun(isalnum))), secretWord.end());

    for(int i = 0; i < secretWord.length(); i++){
        if (isalpha(secretWord[i])){
            secretWordClean += secretWord[i];
        }
    }

    secretWord = secretWordClean; //assign all alpha secret word string back to original variable for better readability
    guessesRemaining = secretWord.length() * 2;

    for(int i = 0; i < secretWord.length(); i++){
        guessedLetters += "_"; //fills guessedLetters with blanks equal to the length of the secretWord
    }

    do{//start of the guessing portion of game

        cout << "Please guess a letter, you have " << guessesRemaining << " guesses remaining!" << endl;
        cin >> individualCharGuess;

        for(int i = 0; i < secretWord.length(); i++){ //every complete iteration of this for loop = one single guess
            if(secretWord[i] == individualCharGuess){
                guessedLetters[i] = individualCharGuess; //will replace the spaces with the correct character, if guessed
                countOfLetters++; //if any letter is guessed correctly, this indicator will be incrimented above 0
                continue;
            }

            if(secretWord.find(individualCharGuess) == string::npos){
                if(incorrectlyGuessedChars.find(individualCharGuess) == string::npos){
                    incorrectlyGuessedChars += individualCharGuess;
                }
            }
        }

        if(secretWord.compare(guessedLetters) == 0){
            cout << "You win! The word was: " << secretWord << endl;
            guessedUsed = ((secretWord.length() * 2) - guessesRemaining) + 1 ;
            cout << "You used " << guessedUsed << " guesses." << endl;
            cout << "Play again? Enter Y for Yes, or anything else to exit: ";
            cin >> playAgain;
            if(playAgain != 'Y'){
                break; //exit the loop if user guesses all the letters and doesn't want to play again
            }
            else {
                incorrectlyGuessedChars = "";
                secretWordClean = "";
                guessedLetters = "";
                //continue;
                goto begin_game;
            }
        }

        guessesRemaining--; //we decriment our total guesses remaining if the user does not win the game or run out of guesses

        if(countOfLetters > 0){
            cout << "You have correctly guessed a letter!" << endl;
            cout << "Here are the letters you have guessed correctly so far: ";
            cout << guessedLetters << endl;
            cout << "Here are the letters you have guessed incorrectly so far: ";
            cout << incorrectlyGuessedChars << endl;
            countOfLetters = 0; //reset the counter to prepare for next iteration of do-while loop
        }
        else if (guessesRemaining <= 0) {
            cout << "You have run out of guesses!" << endl;
            cout << "Here are the letters that you guessed correctly: ";
            cout << guessedLetters << endl;
            cout << "Here are the letters you guessed incorrectly: ";
            cout << incorrectlyGuessedChars << endl;
            cout << "The secret word was: " << secretWord << endl;
            cout << "Play again? Enter Y for Yes, or anything else to exit: ";
            cin >> playAgain;
            if(playAgain != 'Y'){
                break; //exit the loop if user guesses all the letters and doesn't want to play again
            }
            else {
                secretWordClean = "";
                incorrectlyGuessedChars = "";
                guessedLetters = "";
                //continue;
                goto begin_game;
            }
        }
        else {
            cout << "You guessed wrong! Keep trying, " << guessesRemaining << " guesses to go!" << endl;
            cout << "Here are the letters you have guessed correctly so far: ";
            cout << guessedLetters << endl;
            cout << "Here are the letters you have guessed incorrectly so far: ";
            cout << incorrectlyGuessedChars << endl;
        }

    }while (secretWord.compare(guessedLetters) != 0 || guessesRemaining != 0); //use to repeat the request for a single char guess

    return 0;
}

A: You should give it a little help in deducing the template types:
std::not1(std::ptr_fun<int, int>(isalnum)))

or by fully qualifying it:
std::not1(std::ptr_fun(::isalnum)))

it seems that gcc and clang have multiple overload resolution candidates due to the locale functions.


text:
Q: date arrives differently in salesforce I am using drupal and I have webform where there is field date of production and there is calendar in this field When I put date 2020-09-30 in this field and submit my form it save this field wrongly in salesforce like this:
6/9/2022 it changed to year 2022 and also changed month and day
following is the condition I have put in salesforce function
        function ublox_salesforce_salesforce_webforms_save_submission_alter(&$fields, $context) {
  foreach ($fields as $key => $value) {
    if (in_array($key, ["Date_Prototype__c", "Date_Production__c", "NBIOT_Date_of_Field_Trial__c", "NBIOT_Date_Lab_Trial__c"])) {
      $fields[$key] = trim($value);
      if ($fields[$key] == 'Date_Production__c') {
        $fields[$key] = format_date(strtotime($fields['Date_Production__c']), 'medium', 'm-d-Y');
      }
  }

You can see my if condition for 'Date_production__c' ( date of production start )
Where I am doing wrong? I am unable to find solution anyone can help me please.
I have also attached the screenshot of my field where I have put date 2020-09-30 but it reached differently like 6/9/2022
Thanks in advance

A: What's the outcome of this format_date(strtotime($fields['Date_Production__c']), 'medium', 'm-d-Y');, can you write it to log or echo or something?
Salesforce API expects dates in 2020-09-14 format (so that'd be Y-m-d?) and datetimes in 2020-09-14T18:07:30Z format. See https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_dateformats.htm


text:
Q: Importing Multiple DB to one MU database I have three databases associated with three different WP sites. I set up one MU site, with one database. How should I import each of the three databases?

A: Best thing to do is read the docs: http://codex.wordpress.org/Tools_Export_Screen and http://codex.wordpress.org/Importing_Content#WordPress and work with WXR files rather than trying to export directly from the database.
You also have the option on Import to grab images. Or you can merge the contents of the three wp-content/uploads/ directories, but be aware that it's possible some images may have the same name and get overwritten.


text:
Q: How do I prevent accidentally building X as a dependency when installing a port? I'm running FreeBSD in a small VM image, and I want to keep it headless. Is there an easy flag to set somewhere to prevent installing X as a dependency, or do I just need to rely on eternal vigilance? Thanks.

A: According to the mailing list, you should set WITHOUT_X11=yes in /etc/make.conf.


text:
Q: htaccess mod_rewrite URL problems I would like to re-write this url here;
site.com/product.php?s=electricity-at-work-regulations

to
site.com/courses/electricity-at-work-regulations

so change product.php to courses and generally tidy the url up.
Is this possible?
.htacess file
   <IfModule mod_rewrite.c>
       RewriteEngine On
       RewriteCond %{HTTP_HOST} !^peoplefactor.co.uk$ [NC]
       RewriteRule ^(.*)$ http://peoplefactor.co.uk/$1 [L,R=301]
    </IfModule>

   # Clean URLS
  <IfModule mod_rewrite.c>
       Options -MultiViews
       RewriteEngine On

       RewriteRule ^blog/([a-zA-Z0-9-/]+)/preview$ /blog/post.php?s=$1&preview=all [L]
       RewriteRule ^blog/([a-zA-Z0-9-/]+)$ /blog/post.php?s=$1 [L]

       RewriteRule ^course/([a-zA-Z0-9-/]+)$ /course.php?s=$1 [L]

       RewriteCond %{REQUEST_FILENAME} !-d
       RewriteCond %{REQUEST_FILENAME} !-f
       RewriteRule ^([^\.]+)$ $1.php [NC,L]
     </IfModule>

      # Gets rid of www.
     <IfModule mod_rewrite.c>
        RewriteEngine On

        RewriteCond %{HTTPS} !=on
        RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
        RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
    </IfModule>

A: Yes but it would be better the other way around.
You should always call site.com/courses/electricity-at-work-regulations within your application and reroute it to site.com/product.php?s=electricity-at-work-regulations. Something like
RewriteEngine On
RewriteBase /
RewriteRule ^(courses)/([a-zA-Z\-]+)$  product.php?s=$2 [L]


text:
Q: Why does the ASCII codes of number characters get written to the file? I'm writing a binary file with the following code
char x[] = "02 00 27 FF FF 92 20";
FILE *ptr_x;
ptr_x=fopen("xx","wb");
fwrite(x, 1, 1, ptr_x);

The problem is that if i open the file it is written like this:
"30 32 20 30 30 20 32 37 20 46 46 20 46 46 20 39 32 20 32 30"

Which is the ASCII representation of the text above.
What i would like to have is a file with exactly those values written in and not the ASCI representation.
Regards,
Solution:
uint8_t x[68] = {0x05,0x01,0x00,0x00,0x00,0x00,0x00,0x00,
                0x00,0x00,0x00,0x18,0xDA,0x18,0xF1,0x18,
                0xDA,0xF1,0x18,0xF1,0x18,0x00,0x05,0x02,
                0x01,0x14,0x00,0x01,0x00,0x0B,0x00,0x33,
                0x01,0x01,0x04,0x02,0x00,0x27,0xFF,0xFF,
                0x92,0x20,0x00,0x00,0x00,0x23,0xFE,0x00,
                0x04,0x02,0x00,0x27,0xFF,0xFF,0x04,0x02,
                0x00,0x23,0xFE,0x00,0x00,0x00,0x00,0x00,
                0x00,0x00,0x92,0x20};

FILE *ptr_x;
ptr_x=fopen("xx","wb");
fwrite(x, 68, 1, ptr_x);

A: Try using an array like this: unsigned char x[] = {0x02, 0x00, 0x27, 0xFF, 0xFF, 0x92, 0x20}; or, even better, use uint8_t instead of unsigned char.

A: fwrite(x, 1, 1, ptr_x);

Means "Write the data to that x points to to ptr_x. That data consists out of 1 element(s) and every element is 1 byte in size."
That's a lie. Your data consists out of 20 bytes. So either the data consists out of 20 elements that are 1 bytes each:
fwrite(x, 1, 20, ptr_x);

or it consists out of 1 element that is 20 byte in size:
fwrite(x, 20, 1, ptr_x);

Or more general:
fwrite(x, strlen(x), 1, ptr_x);


text:
Q: Blackberry (Java) - Setting scrolling be not focused on objects on the screen I have a mainscreen which currently scrolls (and I have the arrows on the right) but the scrolling seems to be focused on the ButtonField objects that I have on the page. Is there any way to set the scrolling to be non-focused scrolling (moving a few pixels each time). Is there a way to set this?
Other ideas I have had (which sound hacky so I want to avoid):
- Placing NullFields around to scroll
- Manually listening to the  trackwheelRoll event and moving appropriately

A: That's not really how scrolling works on trackball BlackBerry devices.  It's always based on the change of focus from one field to another.  The only time the whole screen may scroll "smoothly" is when there are no fields that accept focus (or on touchscreen devices such as the Storm).
To use an analogy: just think of each focusable field on the screen as being like a line of text in a text editor.  Just by moving the cursor with the arrow keys, you can get the screen to scroll but only when the cursor hits the edge of the current visible screen, and then only to the next line in a one-line increment.  On trackball BlackBerrys, the trackball is the equivalent of the arrow keys -- and unfortunately there isn't an analog to "smoothly dragging the scrollbar with a mouse" in the text editor.  Hope this makes sense!


text:
Q: Is it sufficient to only catch exceptions to detect all binary file read/write errors in C++? In example below, file exceptions are set. Inside the try-catch block is validating the size of the read data using the gcout() function. Is it necessary to test the return value of gcount() when the exceptions are set?
#include <iostream>
#include <fstream>

int main()
{
    char buf[100];
    std::ifstream file;

    file.exceptions(std::ios_base::badbit | std::ios_base::failbit | std::ios_base::eofbit);

    try {
        file.open("file.bin", std::ios_base::in | std::ios_base::binary);

        file.read(buf, sizeof buf);

        // Is this error check redundant?
        if (file.gcount() != sizeof buf) {
            std::cout << "gcount(): Read error\n";
        }

        file.close();
    } catch (...) {
        std::cout << "Exception: Read error\n";
    }

    return 0;
}

A: The fact that read() throws an exception at all guarantees that gcount() cannot be equal to the requested buffer size. You can look at gcount() after a successful read() to check how many bytes it actually read, which you know is not the case if an exception is thrown.
In your example, you have set an exception to be thrown on all possible outcomes of read() that do not read the entire requested size.  So yes, in that case, checking gcount() is redundant.  It would only make sense to check gcount() if EOF were reached with no exception thrown, and you want to know how many bytes were read.  Which doesn't make a lot of sense for a binary read, unless the data is variable-length and you simply just don't know its size up front.  If you need to handle data that ends with EOF, you shouldn't be throwing an exception on eofbit to begin with.  Throw an exception on EOF only if EOF is a real error condition (ie, the data at the end of the stream is incomplete).

A: Correct, the stream exception function is passed a std::ios_base::iostate parameter of type trait BitmaskType. Bitmask types supports all bitwise operators:

The bitwise operators operator&, operator|, operator^, operator~, operator&=, operator|=, and operator^= are defined for values of the bitmask type and have the same semantics as the corresponding built-in operators on unsigned integers would have if the bitmask elements were the distinct integer powers of two.


text:
Q: Store not getting passed down to connected cellrendererframework I'm using the following components:
react v.16.5
react-redux v.6.0
ag-grid v.18.1
I'm using cellRendererFramework to display a custom component in  one cell of ag-grid.  However as soon as i make this custom component a connected component,
Error:

Could not find "store" in the context of "Connect(TestComponent)". Either wrap the root component in a , or pass a custom React
  context provider to  and the corresponding React context
  consumer to Connect(TestComponent) in connect options.

the colDef in the ag-grid is as follows:
{
  field: "TestField",
  headerName: "Test Field",
  rowGroup: false,
  cellRendererFramework: TestComponent
}

// TestComponent.js
import React, {Component} from 'react';
import {connect} from 'react-redux';

class TestComponent extends Component {

  render() {
    return(
Hello
);
  }
}

export default connect()(TestComponent);

I've created the store and defined the provider at the Index.js level.
Is it that cellrendererFrameworks cannot be connected?
I came across this issue in another stack overflow post but there they'd said this issue has been resolved in react vers. 13?
https://github.com/ag-grid/ag-grid-react/issues/88
Please note this is not for writing a testcase- i need the TestComponent to actually be connected.
Please could someone help with this as it seems a pretty fundamental bug that nested components are getting blocked from being connected.

A: From the docs and lilbumbleber's response:

With React 16 Portals were introduced and these are the preferred way to create React components dynamically. If you wish to try use this feature you'll need to enable it as follows:

// Grid Definition
<AgGridReact
    reactNext={true}
    ...other bindings

If you use connect to use Redux, or if you're using a Higher Order Component to wrap the React component at all, you'll also need to ensure the grid can get access to the newly created component. To do this you need to ensure forwardRef is set:

export default connect(
    (state) => {
        return {
            currencySymbol: state.currencySymbol,
            exchangeRate: state.exchangeRate
        }
    },
    null,
    null,
    { forwardRef: true } // must be supplied for react/redux when using GridOptions.reactNext
)(PriceRenderer);

So, you could try adding those two:

*

*Add reactNext={true} to <AgGridReact/> component

*Change
connect()(TestComponent);
to
connect(null, null, null, { forwardRef: true })(TestComponent);
Edit: This bug was fixed in version 20.x


text:
Q: devenv.exe execute through jenkin's job doesn't work i am trying to execute devenv.exe through windows batch command plugin in Jenkins
but it keeps on executing and fails to launch the application.
Console Output :
**In progressConsole Output
Started by user anonymous
Building on master in workspace C:\Program Files (x86)\Jenkins\jobs\TEMP\workspace
[workspace] $ cmd /c call C:\Windows\TEMP\hudson3900292017086958332.bat
C:\Program Files (x86)\Jenkins\jobs\TEMP\workspace>set DEVPATH=C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE
C:\Program Files (x86)\Jenkins\jobs\TEMP\workspace>set PATH=D:\app\nazopay\product\11.2.0\dbhome_1\bin;D:\app\nazopay\product\11.2.0\client_1;C:\Program Files (x86)\Integrity\IntegrityClient10\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\cde\tools;C:\Program Files\TortoiseSVN\bin;C:\Program Files\Java\jdk1.6.0_23\bin\;C:\Program Files (x86)\Google\Chrome\Application;C:\MingW;C:\PROGRA~2\INTEGR~1\Toolkit\mksnt;%JAVA_HOME%;,;C:\Program Files\Java\jdk1.6.0_23;,;C:\Program Files\Java\jdk1.6.0_23\bin;%CLASS_PATH%;,;C:\Program Files\Java\jdk1.6.0_23\lib;,;C:\Program Files\Java\jdk1.6.0_23\lib;;C:\Program Files (x86)\M**icrosoft Visual Studio 10.0\Common7\IDE

C:\Program Files (x86)\Jenkins\jobs\TEMP\workspace>devenv.exe

A: You must execute devenv.com.
The devenv.exe always attempts to open GUI, even when commands are given, and it can't. The devenv.com has output directed to standard output and works fine from Jenkins.
You also must pass arguments.
Without arguments both devenv.com and devenv.exe just start the IDE GUI, which is not what you want. The correct command-line is
devenv.com projectname.sln /Build Release /Project projectname

First is path to the solution you want to build. Then the /Build flag is followed by configuration. If you have multiple platforms, you have to pass configuration and platform combination, e.g. Release|Win32. The /Project flag names project to build (including all dependencies). If omitted, it builds all projects selected for build in given configuration.

A: Why don't you use msbuild?
This would be a good starting point for your windows build script:
call "%VS100COMNTOOLS%\vsvars32.bat"
msbuild projectname.sln /target:Rebuild /l:FileLogger,Microsoft.Build.Engine;logfile=msbuild.log || goto error
goto end
:error
@echo ERROR: Build failed
exit/b 1
:end
exit/b 0

This way you can also capture the output log that you can parse with one of the jenkins plugins.
Ofcourse, adjust the VS100COMNTOOLS to your version of MSVS


text:
Q: How does the Fourier transform act on $\ell^2$? Given an $L^2(\Bbb R)$ function $f$, let $c_n(f)$ be its $n$th Fourier coefficient. Define an isometry $T: L^2 \to \ell^2$ by $Tf = (c_0(f),c_1(f),\ldots)$. Let $F$ be the Fourier transform operator; it's an isometry on $L^2$. So how does $T\circ F$ act on $\ell^2$? What is it doing to the Fourier coefficients?
Here, $F(f)(s) = \int_{-\infty}^\infty e^{-2\pi i st}f(t) dt$.


text:
Q: open banner overlay when the page is loaded with fancybox 4 I would like to update to the latest version of fancybox 4 the javascript code of my banner overlay that opens when the page is loaded.
I don't understand where I'm wrong.

  <href="htts://....." target="_blank">