text:
Q: first post in while loop of wordpress I am trying to create a bootstrap carousel in WordPress using advanced custom fields.
The first 'carousel-item' in the loop must have class 'active'. I am not able to figure out how to define the if condition so that the class is added to the first iteration of the loop.
Same is the case with the carousel indicators.
class active should be added to the first iteration and data-slide-to="x" should be the counter of the loop. Any idea how to get the count and class working?

            <?php $loop = new WP_Query( array ( 'post_type' => 'carousel', 'orderby' => 'post_id', 'order' => 'ASC') ); ?>
            <?php while( $loop->have_posts() ): $loop->the_post(); ?>
                <div class="carousel-item" style="background-image: url('<?php the_field('carousel_image'); ?>')">

<?php the_title(); ?>

<?php the_field('carousel_description'); ?>

            <?php endwhile; wp_reset_query();?>

            Previous

            Next

A: You can do it this way

            <?php
            $iteration = 0;
            $loop = new WP_Query( array ( 'post_type' => 'carousel', 'orderby' => 'post_id', 'order' => 'ASC') ); ?>
            <?php while( $loop->have_posts() ): $loop->the_post(); $iteration++; ?>
                <div class="carousel-item<?php if( $iteration == 1 ) echo ' active' ?>" style="background-image: url('<?php the_field('carousel_image'); ?>')" data-slide-to="<?php echo $iteration ?>">

<?php the_title(); ?>

<?php the_field('carousel_description'); ?>

            <?php endwhile; wp_reset_query();?>

            Previous

            Next

A: Here's how I implemented it.
Defined two variables. One for the carousel indicator, and one for the carousel wrapper and increment them in the loop.
$carousel_wrap = 0;
$carousel_ind = 0;

                <?php $loop = new WP_Query( array ( 'post_type' => 'carousel', 'orderby' => 'post_id', 'order' => 'ASC') ); ?>
                <?php while( $loop->have_posts() ): $loop->the_post(); $carousel_ind++; ?>
                    <li data-target="#theCarousel" data-slide-to="<?php echo $carousel_ind; ?>" class="<?php if( $carousel_ind == 1 ) echo 'active' ?>"">

                <?php endwhile; wp_reset_query();?>

                <?php $loop = new WP_Query( array ( 'post_type' => 'carousel', 'orderby' => 'post_id', 'order' => 'ASC') ); ?>
                <?php while( $loop->have_posts() ): $loop->the_post(); $carousel_wrap++; ?>
                    <div class="carousel-item <?php if( $carousel_wrap == 1 ) echo 'active' ?>" style="background-image: url('<?php the_field('carousel_image'); ?>')">

<?php the_title(); ?>

<?php the_field('carousel_description'); ?>

                <?php endwhile; wp_reset_query();?>

                Previous

                Next

A: Use for loop for that.
for ( $iteration = 0; $the_query->have_posts(); $iteration++  ) : $the_query->the_post();
endfor;


text:
Q: Upload Image in to server This my code from this link
Uploading Image via POST in Objective C
// COnvert Image to NSData
NSData *dataImage = UIImageJPEGRepresentation(_chosenImage, 1.0f);
NSLog(@"%@", dataImage);
NSString *tempURLString = [APIStr stringByReplacingOccurrencesOfString:@"***" withString:@"upload"];

// set your URL Where to Upload Image
NSString *urlString = @"My URL String";

// set your Image Name
NSString *filename = @"My File Name";

// Create 'POST' MutableRequest with Data and Other Image Attachment.
NSMutableURLRequest* request= [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
NSLog(@"%@", request);
[request setHTTPMethod:@"POST"];
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"my_upload_file_name\"; filename=\"%@_.jpg\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(@"%@", postbody);
[postbody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:dataImage]];
[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];

// Get Response of Your Request
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"Response  %@",responseString);

This code not working for me.. I'm getting failed message. Is any wrong in my code.
And i tried this code also
https://jmsliu.com/3241/select-and-upload-multiple-photos-from-gallery-or-camera-in-ios.html
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

_chosenImage = info[UIImagePickerControllerEditedImage];
   [self uploadImageLegacy:_chosenImage];
}

- (void) uploadImageLegacy:(UIImage *)image {
NSString *tempURLString = [Str stringByReplacingOccurrencesOfString:@"***" withString:@"upload"];
//upload single image
NSURL *url = @"My URL here";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
[request setHTTPMethod:@"POST"];
NSString *POST_BODY_BOURDARY = @"SportuondoFormBoundary";
NSString *contentTypeValue = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", POST_BODY_BOURDARY];
[request addValue:contentTypeValue forHTTPHeaderField:@"Content-type"];

NSMutableData *dataForm = [NSMutableData alloc];
[dataForm appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",POST_BODY_BOURDARY] dataUsingEncoding:NSUTF8StringEncoding]];
[dataForm appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"param1\";\r\n\r\n%@", @"10001"] dataUsingEncoding:NSUTF8StringEncoding]];

NSData *imageData = UIImageJPEGRepresentation(image, 0.9);
[dataForm appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",POST_BODY_BOURDARY] dataUsingEncoding:NSUTF8StringEncoding]];
[dataForm appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"my_upload_file_name\"; filename=\"%@.jpg\"\r\n", @"test"] dataUsingEncoding:NSUTF8StringEncoding]];
[dataForm appendData:[[NSString stringWithFormat:@"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[dataForm appendData:[NSData dataWithData:imageData]];

[dataForm appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",POST_BODY_BOURDARY] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:dataForm];
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend {
NSLog(@"Sent %lld, Total sent %lld, Not Sent %lld", bytesSent, totalBytesSent, totalBytesExpectedToSend);
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
_receiveData = [NSMutableData data];
[_receiveData setLength:0];
completionHandler(NSURLSessionResponseAllow);
NSLog(@"NSURLSession Starts to Receive Data");
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
[_receiveData appendData:data];
NSLog(@"NSURLSession Receive Data");
}

 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
NSLog(@"URL Session Complete: %@", task.response.description);

if(error != nil) {
    NSLog(@"Error %@",[error userInfo]);
} else {
    NSLog(@"Uploading is Succesfull");

    NSString *result = [[NSString alloc] initWithData:_receiveData encoding:NSUTF8StringEncoding];
    NSLog(@"%@", result);
}
}

A: I am using this code and working for me
    NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
    [_params setObject:[UserDict valueForKey:@"userid"] forKey:@"userid"];
    // YOU CAN ADD YOUR  PARAMETERS HERE

    NSString *BoundaryConstant = @"----------V2ymHFg03ehbqgZCaKO6jy";
    NSString* FileParamConstant = @"file";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BoundaryConstant];

    NSMutableData *body = [NSMutableData data];

    //    NSData *bodyData = [appData createFormData:_params withBoundary:BoundaryConstant];
    for (NSString *param in _params) {
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"%@\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
    }
    // I AM RESIZING IMAGE YOU CAN SKIP
    UIImage *newSizeImage = [self imageWithImage:currentlyCapturedImage scaledToSize:newImageSize];

    NSData *imageData = UIImageJPEGRepresentation(newSizeImage, 1.0);

    if (imageData) {
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image%@.jpg\"\r\n",FileParamConstant, timestamp] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:imageData];
        [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    }

    [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];

now You have body with your parameters and image.
You can use this as body of request [request setHTTPBody:body];
and call the service
Hope it will helpful
EDIT
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

}];

[postDataTask resume];

redpajama_set_name: RedPajamaStackExchange


text:
Q: R-Tree query with adapted std::pair point type I am hitting a compile-time assertion with the following (Rcpp) code. This code inserts 10^6 random points into a vector, builds and r-tree from that vector and then queries for points falling with a box bounded by (1/3, 1/3) and (2/3, 2/3).
// [[Rcpp::depends(BH)]]
// [[Rcpp::plugins(cpp11)]]

#include <Rcpp.h>
#include <vector>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/register/box.hpp>
#include <boost/geometry/geometries/register/point.hpp>

namespace bg = boost::geometry;
namespace bgi = boost::geometry::index;

using key_type = std::pair<double, double>;
using box_type = std::pair<key_type, key_type>;
using range_type = std::vector<key_type>;

BOOST_GEOMETRY_REGISTER_POINT_2D(key_type, double,
                                 bg::cs::cartesian,
                                 first, second);

BOOST_GEOMETRY_REGISTER_BOX(box_type, key_type, first, second);

// [[Rcpp::export]]
void test_it()
{
  range_type data;

  for (int i = 0; i != 1e6; ++i)
    data.emplace_back(R::runif(0, 1), R::runif(0, 1));

  using rtree_type = bgi::rtree<key_type, bgi::linear<16>>;

  rtree_type rt(data);

  key_type p1 = std::make_pair(0.33, 0.33),
    p2 = std::make_pair(0.66, 0.66);

  box_type roi = std::make_pair(p1, p2);

  range_type res;

  rt.query(bgi::contains(roi), std::back_inserter(res));

}

Compiles fine without the last query line. Compiler output is:
In file included from geom_test.cpp:7:
In file included from /usr/local/include/boost/geometry.hpp:17:
In file included from /usr/local/include/boost/geometry/geometry.hpp:50:
In file included from /usr/local/include/boost/geometry/strategies/strategies.hpp:33:
In file included from /usr/local/include/boost/geometry/strategies/disjoint.hpp:24:
In file included from /usr/local/include/boost/geometry/strategies/relate.hpp:23:
/usr/local/include/boost/geometry/strategies/within.hpp:80:5: error: no matching function for call to 'assertion_failed'
    BOOST_MPL_ASSERT_MSG
    ^~~~~~~~~~~~~~~~~~~~
/usr/local/include/boost/mpl/assert.hpp:435:48: note: expanded from macro 'BOOST_MPL_ASSERT_MSG'
#define BOOST_MPL_ASSERT_MSG( c, msg, types_ ) \
                                               ^
/usr/local/include/boost/mpl/assert.hpp:429:9: note: expanded from macro '\
BOOST_MPL_ASSERT_MSG_IMPL'
        boost::mpl::assertion_failed<(c)>( BOOST_PP_CAT(mpl_assert_arg,counter)::assert_arg() ) \
        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/local/include/boost/mpl/assert.hpp:60:58: note: expanded from macro '\
BOOST_MPL_AUX_ASSERT_CONSTANT'
#   define BOOST_MPL_AUX_ASSERT_CONSTANT(T, expr) enum { expr }
                                                         ^~~~

A: You say

then queries for points falling with a box bounded by (1/3, 1/3) and (2/3, 2/3)

Yet your code is looking for points that "contain" a box.
You probably meant:
rt.query(bgi::within(roi), std::back_inserter(res));

Demo
Live On Coliru
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/register/box.hpp>
#include <boost/geometry/geometries/register/point.hpp>
#include <vector>
#include <random>
#include <iostream>

namespace bg = boost::geometry;
namespace bgi = boost::geometry::index;

using key_type = std::pair<double, double>;
using box_type = std::pair<key_type, key_type>;
using range_type = std::vector<key_type>;

BOOST_GEOMETRY_REGISTER_POINT_2D(key_type, double, bg::cs::cartesian, first, second)
BOOST_GEOMETRY_REGISTER_BOX(box_type, key_type, first, second)

int main() {
    std::mt19937 engine { std::random_device{}() };
    std::uniform_real_distribution<double> dist(0,1.0);

    range_type data;

    for (int i = 0; i != 1e6; ++i)
        data.emplace_back(dist(engine), dist(engine));

    using rtree_type = bgi::rtree<key_type, bgi::linear<16> >;

    rtree_type rt(data);

    box_type const roi {{0.33, 0.33}, {0.66,0.66}};

    range_type res;
    rt.query(bgi::within(roi), std::back_inserter(res));

    std::cout << res.size() << " results\n";
}

Prints something like
109073 results


text:
Q: Application fails when only one of two Active Directory server is off When I unplug the Ethernet cable of one of the Active Directory servers, my application fails to authenticate user, despite there is a different Active Directory server is available on the network.   Why is that? I expect that if one of the Active Directory  servers fails, the other ones can handle requests.
I use Windows Server 2008 R2 64-bit.
I have an IIS application which authenticates users against an Active Directory.
        string serverName = ConfigurationManager.AppSettings["AD.Server"];
        string userName = ConfigurationManager.AppSettings["AD.User"];
        string password = ConfigurationManager.AppSettings["AD.Password"];
        _principalContext = new PrincipalContext(ContextType.Domain, serverName, userName, password);

Here are the configuration settings:
<add key="AD.Server" value="192.168.0.1"/> <!---  THIS IS THE PRIMARY PRODUCTION SERVER -->
<add key="AD.User" value="Domain\Administrator"/>
<add key="AD.Password" value="******"/>

Then I set up another Active Directory server (let it be 192.168.0.2).  It successfully syncs with the production server. Later, when I switch the second AD server off, my application fails with exception "The server is not operational".
Why is that?  Why does the application depend on the second server, despite being explicitly given another server in config?

A: Your DC's should work the way you are expecting.

*

*Run DCdiag /a, does it report any failures?

*If you restart your app when the "working" DC is offline does it work, presumably now pointing at the other DC (i.e. is it an either or issue where it's binding to one DC at start and then can't rebind to the other when the one it's using is unavailable)?

*How long has the new DC been up - IIS needs to have a chance to be aware it exists.

*You should not need to specify a Domain Controller - you should point your app at the domain, not a server.

I am a little confused at what is happening, in your question first you say you expect it to fail over yet you are explicitly telling it which DC to use. If you need to provide a server name try the domain's DNS name itself (company.local or whatever). This will resolve to a list of IPs for each DC in your domain.

A: Have you set all your computers in Active Directory to know about that secondary domain controller IP address? You do that in DNS section of your network configuration.


text:
Q: How do I separate datamapper observer class into a different file from the model class? I'm running into an error when I try to split the dm-observer class into a separate file from my model class. Previously it worked fine if I put it all into a single file.
# test_observer.rb
require 'dm-observer'

class TestObserver
  include DataMapper::Observer
  observe Test

  before :create do
      # does funky stuff
  end
end

# test.rb
require 'dm-core'
require File.dirname(__FILE__) + '/test_observer'

class Test
  include DataMapper::Resource

  property :id, Serial
  property :name, String
  property :state, Integer
end

Every time I require the Test class, I run into the error:
uninitialized constant TestObserver::Test (NameError)

I'm not sure why the TestObserver:: is prepended to the class name. I have a feeling I'm not putting the requires in the right places, but I've tried everything and it still won't play nice. Would appreciate any help on this.
Thanks!

A: You require test.rb which requires test_observer before Test class is declared. You should remove this line:
require File.dirname(__FILE__) + '/test_observer'
and require files in that order:
require 'test'
require 'test_observer'


text:
Q: Is java:openjdk-8-jre an offical docker image I could pull java:openjdk-8-jre with docker pull java:openjdk-8-jre command. But I can't find it out in https://hub.docker.com/. I can't find a page for java like other official images, e.g. openjdk. When I went to https://hub.docker.com/_/java, it was redirected to https://hub.docker.com/_/openjdk. So I guess it's renamed with openjdk. Where can I find the related infos about java:openjdk-8-jre in official docker hub.

A: As of the are two more or less official java distributions - the OracleJDK and OpenJDK (there are as well some derivatives of OpenJDK). Thus you either pull from https://hub.docker.com//oracle-jdk or https://hub.docker.com//openjdk. The java:openjdk-8-jre is pre-split version on official repo and shouldn't e use as is outdated:
$ docker inspect --format='{{index .Created}}'  java:openjdk-8-jre
2017-01-17T00:53:21.516522468Z

$ docker inspect --format='{{index .Created}}'  openjdk:8-jre
2020-05-15T21:05:09.719485985Z

Note: To use Oracle JDK requires subscription.


text:
Q: How can I make animation with threads I am trying to make a perpetual animationwith C#. However it crashes after some time (less than 30 seconds). I tried to use Application.DoEvents(), but it didn't work because (as I read somewhere) it turns off some some syncronization.
Now I am trying to make it work with second thread but I can't access the things created in the OnPaint function.
My code is like this:
public partial class Form1 : Form
{
    private Thread std; //cpoied from the internet

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e) //copied from the internet
    {
        Thread trd = new Thread(new ThreadStart(this.ThreadTask));
        trd.IsBackground = true;
        trd.Start();
    }

    private void ThreadTask() //copied from the internet
    {
        // I want my animation to be here.Maybe like:
        while(true)
        {Draw(g,b)
         Thread.Sleep();
         Draw(g,b1)
        }
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        Graphics g = e.Graphics;
        Brush b = new SolidBrush(Color.Black);
    }

    private void Draw(Graphics g, Brush b)
    {
        //makes the figures
    }
}

If I add Graphycs g, Brush b.... to the brackets of ThreadTask it gives me an error message

No overload for 'Thread task' matches delegate 'ThreadStart'

So as someone who is new to that stuff I would be extremely grateful if you could give some references, but any help will be appreciated


text:
Q: Just How Independent are Events Anyways I want to describe a thought experiment to explore independent events, and whether they may actually be linked.

You are given a set of independent coin generators.
Coin generators are true random number generators that return 'Heads' or 'Tails'.
The probability that any of the independent coin generators would return heads is $0.5$.
The set of all of these coin generators is $S$.
$\# S = n$.
You fire all the coin generators, and they all produce their results.
Before observing the coin generators, you split the coin generators into two groups $A$ and $B$.
The selection of each group is random.
$\# A + \# B = n$
You get two pieces of paper and write out your expectation for the number of heads you expect for each group on each piece.
You then observe $A$.
Do you change your observation for $B$?
Should you?

The random variables of interest are ${\#}h(A)$ and ${\#}h(B)$.
A few things I feel need to be made explicit. As at the time you conducted the experiment (immediately after firing the coin generators and before splitting $S$), the number of heads in $S$ was fixed. Let's call the set of all heads in $S$ $H$.
For each $V \subset S$ the set of all heads in $V$ is $h(V)$.

The selection process is random, this means that $\frac{{\#}A}{{\#}S} : \frac{{\#}h(A)}{{\#}H}$ may be $\gt 1, \, \lt 1$ or $= 1$. However, for each $A$ and $S$, only a few selections ($n\choose {\#}A$) produce $\frac{{\#}A}{{\#}S} : \frac{{\#}h(A)}{{\#}H} = 1$.
$A = B'$ and vice versa.

Let's call the sampling from $S$ such that $\frac{{\#}A}{{\#}S} = \frac{{\#}h(A)}{{\#}H}$ the equal sampling $(T_E)$.
Let's call the sampling from $S$ such that $\frac{{\#}A}{{\#}S} \gt \frac{{\#}h(A)}{{\#}H}$ the $A$-biased sampling $(T_A)$.
Let's call the sampling from $S$ such that $\frac{{\#}A}{{\#}S} \lt \frac{{\#}h(A)}{{\#}H}$ the $B$-biased sampling $(T_B)$.

$Pr(T_E) = n{\choose}{\#}A$
$$Pr(T_A) = Pr(T_B) = \frac{2^n - {{n}\choose{\#}A}}{2}$$
I feel the above should be kept in mind when we consider whether $h(A)$ affects $E\left(h(B)\right)$. For one, observing a higher than expected amount of heads in $A$ may raise the probability of the $A$-biased sampling.

I think that depending on what I observed in $A$, that I may revise my beliefs about $B$. Assuming $n = 8$, ${\#}A = 6$, and $h(A) = 6$, I will update (an increase) my posterior probability on the selection chosen favouring $A$ over $B$ in distribution of heads. This may in turn lead me to lower my estimation of the heads contained in $B$.
I think my stance of possibly shifting my beliefs about $B$ based on my observation of $A$ is legitimate, as the selection process is random and may lead to an unfair distribution of heads.
Should we shift our beliefs after observing $A$ (and more importantly, why so)?

NOTE:
I think it is important to draw a distinction between this experiment and the gambler's fallacy. We do not first generate $A$ and then subsequently generate $B$ (in which case $h(A)$ would be independent of $h(B)$), we generate $S$. We do not observe the number of heads or tails in $S$. The coin generators may be fired in any order (temporal or otherwise), but we do not observe $S$ until after all $x \in S$ have finished generating.

We then randomly sample $S$ into $A$ and $B(A')$. After sampling $S$, we estimate the number of heads in $A$ and $B$ $\left(E\left(h(A)\right) \text{and} \, E\left(h(B)\right) \text{respectively}\right)$. After our estimation, we observe $A$: should we update $E\left(h(A)\right)$ in light of $h(A)$? I don't think it's as clear cut as people seem to be making it out to be.

A: Since you know, a priori, that the outcome of each generator is iid Bernoulli(0.5), then there is no basis for you to update your estimate of $E[h(A)]$ or $E[h(B)]$. The reason is that you didn't say you know the total number of heads (#$H$), so observing $A$ doesn't constrain what $B$ could be.
The reason is that the outcomes from each generator are exchangeable, and so knowledge of one partition doesn't help you in understanding the other partition.
The issue of when the generators were fired is irrelevant, the basic theory is that, by the iid assumption, $P(S_1,S_2|S_3,S_4,...,S_n) = P(S_1,S_2)$, so your expected value calculations shouldn't change.
So what could be conditional?
Say you know $h(A) + h(B) = N$, then, even if the generators are independent, you know $h(A)$ you know that $E[h(B)] = N - h(A)$.
Another case is if we drop the constraint $h(A) + h(B) = N$, we still have $E[h(S)|h(A)] = h(A) + \frac{\#B}{2}$
That's one way you would get conditional expectation to differ from unconditional even in the case of independence...but it requires altering the sample space to reflect new knowledge.
Your derivations of $A-$biased, $B$-biased are only relevant if you know $N$...if you don't then its not relevant.
## R Code Example ##
Let's simulate this process to show what it looks like:
h_A <- c()
h_B <- c()
n_A <- c()
n_B <- c()

for(i in 1:1000){
  S <- rbinom(10,1,0.5) #fire generators
  idx_A <- sample(1:length(S),round(runif(1,0,length(S))),replace = FALSE) #select A
  A <- S[idx_A] #assign values for A
  B <- S[setdiff((1:10),idx_A)] #assign rest to B
  h_A <- append(h_A,sum(A))
  n_A <- append(n_A,length(A))
  n_B <- append(n_B,length(B))
  h_B <- append(h_B,sum(B))
}

plot(h_A,h_B)

#look at conditional means
A_values <- unique(h_A)
uncond_mean <- c()
cond_mean <- c()

for(i in 1:length(A_values)){
  val <- A_values[i]
  subset_A <- h_A==val #where did we see h_A == val
  n <- n_B[subset_A] #size of B partition
  selected_B <- h_B[subset_A] #what was the number of heads in B?
  uncond_mean <- append(uncond_mean,mean(n/2)) #just find mean of 10-N independent tosses
  cond_mean <- append(cond_mean,mean(selected_B)) #actually calculate mean of B
}

plot(uncond_mean,cond_mean)

lm(cond_mean ~ uncond_mean)

You get as output:

Now, look at conditional vs unconditional means:

Call:
lm(formula = cond_mean ~ uncond_mean)

Coefficients:
(Intercept)  uncond_mean
    0.01645      0.98479

So, the actual heads tracks the unconditional mean


text:
Q: Plotly and d3.js drag shape I want to allow the user to drag shapes in Plotly, but restrict this to horizontal movement only. Therefore, I am using d3.js for the drag behavior. Everything works nicely except that, when a user clicks a shape, apparently Plotly rewrites the  objects for all shapes -- which deletes all my modifications, hence removing the ability to drag.
Steps to reproduce:

*

*Open plotly_output.html in browser.

*Drag and drop one of the shapes: it works fine.

*Click one of the shapes: it returns to its original place (bad!). If you look at .cartesianlayer .shapelayer in the console, it gets rewritten.

*Draging and dropping no longer works.

Code:
poltly_tmk.py
import plotly
import plotly.express as px
import plotly.graph_objects as go
import numpy as np

x = np.linspace(0, 10, 50)
y = x ** 3
fig = px.scatter(x=x, y=y)

bottom_edge = 0

i = 20
point_x, point_y = x[i], y[i]
fig.add_shape(x0=point_x, x1=point_x + .1, y0=bottom_edge, y1=point_y, fillcolor='blue', layer='below', line=dict(width=0))

i = 40
point_x, point_y = x[i], y[i]
fig.add_shape(x0=point_x, x1=point_x + .1, y0=bottom_edge, y1=point_y, fillcolor='yellow', layer='below', line=dict(width=0))

extrajs = '''
<script src="https://d3js.org/d3.v6.min.js"></script>
<script src='plotly.js'></script>
'''

style = '''
<style>.cartesianlayer .shapelayer path {
    pointer-events: all;
}</style>
'''

layout = dict(dragmode=False)
fig.update_layout(layout)

config = {"modeBarButtonsToRemove": ['zoom2d']}
html = plotly.io.to_html(fig, full_html=False, config=config)
with open('plotly_output.html', 'w') as f:
    f.write(html + extrajs + style)

plotly.js
for (const node of d3.selectAll('.shapelayer path').nodes()) {
    d3.select(node)
        .datum({x: 0})
        .call(d3.drag()
        .on("drag", dragged)
        .on('end',dragended))
}

function dragged(event,d) {
    d3.select(this)
    .attr("transform", "translate(" + (d.x = event.x) + "," + 0 + ")")
}

function dragended(event,d){
    console.log(event.x)
}


text:
Q: JSON Path: how to convert URN references to local references Whilst converting a JSON schema file to Java classes using the Maven org.jsonschema2pojo:jsonschema2pojo-maven-plugin:1.0.0-alpha2 I am getting errors related to urn references which cannot be resolved.
Here is a sample error message:
[ERROR] Failed to execute goal org.jsonschema2pojo:jsonschema2pojo-maven-plugin:1.0.0-alpha2:generate (default) on project model-reservation: Execution default of goal org.jsonschema2pojo:jsonschema
2pojo-maven-plugin:1.0.0-alpha2:generate failed: Unrecognised URI, can't resolve this: urn:jsonschema:com:lumina:pnr:model:Reference: unknown protocol: urn -> [Help 1]

Here is the JSON it refers to with the $ref element which is causing the exception:
    "remarkFields": {
      "type": "object",
      "additionalProperties": {
        "type": "array",
        "items": {
          "type": "object",
          "id": "urn:jsonschema:com:lumina:pnr:model:FileFinishingField",
          "properties": {
            "lineNumber": {
              "type": "integer"
            },
            "name": {
              "type": "string"
            },
            "value": {
              "type": "string"
            },
            "references": {
              "type": "array",
              "items": {
                "type": "object",
                "$ref": "urn:jsonschema:com:lumina:pnr:model:Reference"
              }
            }
          }
        }
      }
    }

How can I convert these to local references in Java and use the conversion output to successfully convert my code to Java classes using the org.jsonschema2pojo:jsonschema2pojo-maven-plugin:1.0.0-alpha2 Maven plugin?

A: There might be better ways to solve this problem, yet one possible solution is this one:
Use a recursive method to convert the urn style references to local references:
Here is the recursive method using the Jackson library:
private static final String ITEMS = "items";
private static final String ID = "id";
private static final String PROPERTIES = "properties";
private static final String ADDITIONAL_PROPERTIES = "additionalProperties";
private static final String REF = "$ref";

private static void parseReferences(JsonNode jsonNode, String path) {
    if (jsonNode.has(ID)) {
        typeMap.put(jsonNode.get(ID).asText(), path);
        final JsonNode properties = jsonNode.get(PROPERTIES);
        final Iterator<Map.Entry<String, JsonNode>> fields = properties.fields();
        path += "/" + PROPERTIES;

        while (fields.hasNext()) {
            Map.Entry<String, JsonNode> entry = fields.next();
            parseReferences(entry.getValue(), path + "/" + entry.getKey());
        }
    } else if (jsonNode.has(ITEMS)) {
        final JsonNode item = jsonNode.get(ITEMS);
        parseReferences(item, path + "/" + ITEMS);
    } else if (jsonNode.has(REF)) {
        ObjectNode objectNode = (ObjectNode) jsonNode;
        objectNode.set(REF, new TextNode(typeMap.get(jsonNode.get(REF).asText())));
    } else if (jsonNode.has(ADDITIONAL_PROPERTIES)) {
        JsonNode additionalProperties = jsonNode.get(ADDITIONAL_PROPERTIES);
        parseReferences(additionalProperties, path + "/" + ADDITIONAL_PROPERTIES);
    }
}

This is how I am calling this method after having instantiated a JAXB parser:
private static void writeSchemaToFile(ObjectMapper jaxbObjectMapper, String origPath, String path) throws Exception {
    InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(origPath);
    try (Reader r = new InputStreamReader(resourceAsStream, "UTF-8")) {
        JsonNode root = jaxbObjectMapper.readTree(r);
        parseReferences(root, "#");
        String changedJson = jaxbObjectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(root);
        final Path targetPath = Paths.get(path);
        if (!Files.exists(targetPath)) {
            Path parent = targetPath.getParent();
            if (parent != null) {
                Files.createDirectories(parent);
            }
        }
        try (Writer writer = Files.newBufferedWriter(targetPath, Charset.forName("UTF-8"), StandardOpenOption.CREATE)) {
            writer.write(changedJson);
        }
    }
}

If you call this method, it will convert the JSON specified in the question to:
"remarkFields" : {
  "type" : "object",
  "additionalProperties" : {
    "type" : "array",
    "items" : {
      "type" : "object",
      "id" : "urn:jsonschema:com:lumina:pnr:model:FileFinishingField",
      "properties" : {
        "lineNumber" : {
          "type" : "integer"
        },
        "name" : {
          "type" : "string"
        },
        "value" : {
          "type" : "string"
        },
        "references" : {
          "type" : "array",
          "items" : {
            "type" : "object",
            "$ref" : "#/properties/passengers/items/properties/reference"
          }
        }
      }
    }
  }
}


text:
Q: Basecamp API authentication with OAuth2: internal checksum failed error I'm trying to write a CodeIgniter controller to handle OAuth2 authentication for the 37signals' Basecamp API.
The problem is I keep encountering the 'internal checksum failed' error, when trying to connect (via cURL) to https://launchpad.37signals.com/authorization.json, providing the Auth Token in a HTTP header.
Here's the index and _authcode functions from my controller class:
<?php

// constants:
// BC_REQUEST_URL = 'https://launchpad.37signals.com/authorization/new'
// BC_TOKEN_URL   = 'https://launchpad.37signals.com/authorization/token'

// ...

public function index() {
    // if get data is set.
    if ($this->input->get()) {

        // if auth code is provided via GET, switch to _authcode method.
        if ( $code = $this->input->get('code') ) {
            return $this->_authcode($code);
        }

        // On error, kill yourself.
        if ( $error = $this->input->get('error') ) {
            die($error);
        }

    }

    // redirect to 37 signals to get an authcode
    header("Location: ".BC_REQUEST_URL."?type=web_server&client_id=".BC_CLIENT_ID."&redirect_uri=".BC_REDIRECT_URL."");
}

// handles the Authentication code that is returned by 37 Signals.
private function _authcode($code) {
    // set vars to POST
    $vars = array(
        'type' => 'web_server',
        'client_id' => BC_CLIENT_ID,
        'redirect_uri' => BC_REDIRECT_URL,
        'client_secret' => BC_CLIENT_SECRET,
        'code' => $code
    );

    // make a request for the access_token
    $url = BC_TOKEN_URL;
    $c = curl_init($url);
    curl_setopt($c, CURLOPT_POST, true);
    curl_setopt($c, CURLOPT_POSTFIELDS, http_build_query($vars));
    curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
    $response = json_decode(curl_exec($c));
    curl_close($c);
    unset($c,$url);

    // get the access vars from this request
    $expiry_seconds = $response->expires_in;    // default: 1209600 (14 days)
    $refresh_token  = $response->refresh_token;
    $access_token   = $response->access_token;
    unset($response);

    // make a separate request to get user info for current user.
    $url = "https://launchpad.37signals.com/authorization.json";
    $c = curl_init($url);

    curl_setopt($c, CURLOPT_HTTPHEADER, array(
        "Authorization: Bearer <$access_token>",
        "Content-Type: application/json; charset=utf-8",
        "User-Agent: MyApp (http://myapp.example.com)"
    ));
    curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
    $response = json_decode(curl_exec($c)); // reply from 37 signal auth
    curl_close($c);
    unset($c,$url);

    echo "response obj = " . print_r($response,1);
    /* prints: response obj = stdClass Object ( [error] => OAuth token could not be verified. The internal checksum failed, so the token data was somehow mangled or tampered with. ) */

    // get the user data from this request
    // $expires_at = $response->expires_at; // the timestamp for when this request expires
    // $identity   = $response->identity;   // the current user
    // $accounts   = $response->accounts;   // list of accounts we can access
    // unset($response);

    // store the response data to the database for easy recall.
    // $this->db->query("REPLACE INTO `sometable` SET `key1`='value', `key2`='value');

}
// ...
?>

A: I ran into this error when saving the auth token in the database with varchar(255). Basecamp's auth token has some checksum data which brings the token over 255 characters.
You don't appear to be pulling it from a database in your example, so this might not affect you, however checking for Basecamp's token being cut off is what I would first look at.
Optionally, remove the <> characters around your $access_token when setting the Bearer header.


text:
Q: straight lines on spherical surfaces I'm not sure how to explain this so here goes. I want to place a horizontal line of text on the side of a curved brandy glass. Is there a formula that can be applied to ensure the text stays horizontal and in a perfectly straight line when the text is applied at a specific point up or down the glass from a flat sheet of paper? (ie I want to print it on paper in the correct curve so when applied to the glass it will appear straight).I suppose the same formula could be used on a tapered glass?? Thoughts or a definitive answer would be great.
Thanx

A: If you write text on a sheet of paper, and then roll it up into a cylinder or cone, if it seems "straight" or not will depend on perspective (the position of the viever's eye).
In the case of a cone (presumably the form of a glass you have in mind), it will look "straight" to someone looking perpendicular to the axis if it follows a circle at constant distance from the cone's point.


text:
Q: EMR: Master instance failed attempting to download bootstrap action I am trying to Install:
1) A Cluster with Spark.
2) A Cluster with Hbase.
First attempt to install add a cluster with Bootstrapping Spark succeeded but, I used SSH wrong key, so I have to redo the install with new key. Since then (from second attempt) I am getting the same error on every attempt while installing 1 and 2 above.
I am following the instructions from: https://aws.amazon.com/articles/ElasticMapReduce/4926593393724923
My command from aws CLI:
aws emr create-cluster --name GCSpark --ami-version 3.2 --instance-type m3.xlarge --instance-count 3 --ec2-attributes KeyName=KeyPair--applications Name=Hive --bootstrap-actions Path=s3://support.elasticmapreduce/spark/install-spark

Output from stderr.txt:
  + python install-spark-script BA 14/10/31 22:00:45 INFO guice.EmrFSBaseModule: Consistency disabled, using
  com.amazon.ws.emr.hadoop.fs.s3n.S3NativeFileSystem as FileSystem
  implementation. 14/10/31 22:00:46 INFO fs.EmrFileSystem: Using
  com.amazon.ws.emr.hadoop.fs.s3n.S3NativeFileSystem as filesystem
  implementation 14/10/31 22:00:47 INFO s3n.S3NativeFileSystem: Opening
  's3://support.elasticmapreduce/spark/1.1.0/scala-2.10.3.tgz' for
  reading 14/10/31 22:01:06 INFO guice.EmrFSBaseModule: Consistency
  disabled, using com.amazon.ws.emr.hadoop.fs.s3n.S3NativeFileSystem as
  FileSystem implementation. 14/10/31 22:01:07 INFO fs.EmrFileSystem:
  Using com.amazon.ws.emr.hadoop.fs.s3n.S3NativeFileSystem as filesystem
  implementation 14/10/31 22:01:08 INFO s3n.S3NativeFileSystem: Opening
  's3://support.elasticmapreduce/spark/1.1.0/spark-1.1.0.e.tgz' for
  reading /bin/cp: cannot stat /usr/share/aws/emr/emr-fs/lib/: No such
  file or directory Traceback (most recent call last): File
  "install-spark-script", line 120, in  prepare_classpath() File
  "install-spark-script", line 52, in prepare_classpath
  subprocess.check_call() File "/usr/lib64/python2.6/subprocess.py",
  line 505, in check_call raise CalledProcessError(retcode, cmd)
  subprocess.CalledProcessError: Command '' returned non-zero exit
  status 1*

Any help would be greatly appreciated.
Thanks!

A: The install error was a temporary issue at the time and fixed with a later version (1.1.0.f).
A readme of changes and notes are at https://github.com/awslabs/emr-bootstrap-actions/tree/master/spark.


text:
Q: Downloading a directory/subdirectory from the FTP server to ios application folder i am creating an application which requires me to download & sync all the data on the FTP directory to the ios application's document directory. I found many examples like  apple's sample FTP code : https://developer.apple.com/library/ios/samplecode/SimpleFTPSample/Introduction/Intro.html#//apple_ref/doc/uid/DTS40009243-Intro-DontLinkElementID_2
FTPhelper class :
https://github.com/erica/iphone-3.0-cookbook-/tree/master/C13-Networking/15-FTP%20Helper
& some others as well. But No one is suitable to download & sync all the data from server to my document directory. I am able to download the files one by one but How to download a complete directory ? Is there any way for this?
I found the library for chilkat here :
http://www.chilkatsoft.com/chilkatftp.asp
I tested it to synchronise the folder & it works successfully. But it is paid $149 . Cost is very high. Is there any other alternative for this? Or any other way by which i can achieve the same?
I found some other questions on this site but they haven't provided a proper solution.
Please show me the correct direction. Even if i have to write code myself for the sync then please tell me how i should do it.
Any help would be appreciated.

A: The simplest solution is to create exact same directory tree on your device and dowload each file using queue.


text:
Q: How to delete all databases on Postgres? I take daily backs of our postgres development box using:
    pg_dumpall -h 127.0.0.1 -U user -w | gzip blah.gz
Since 9.0 is now a release candidate I would like to restore this daily backup on a daily basis to a postgres9.0rc1 box for testing, however I'm not sure how to script it repeatedly. Is there some directory I can nuke to do this?

A: You can do "drop cluster" and "create cluster" which will automtically erase all databases. Erase all data in you $PGDATA directory and reinit the cluster using:
initdb -D /usr/local/pgsql/data

A: You can use:
$ pg_dropcluster 9.2 main
$ pg_createcluster 9.2 main
$ pg_ctlcluster 9.2 main start
$ pg_restore -f your_dump_file

where 9.2 = cluster version and main = cluster name

A: Granted the question is 9 years old at this point, but it's still the second google result for deleting all databases.  If you just want to go from N DBs to 0 without jacking with your config and also having rummage through the file system, this is a much better answer:
https://stackoverflow.com/a/24548640/3499424
From the answer, the following script will generate N drop database commands, one for each non-template DB:
select 'drop database "'||datname||'";'
from pg_database
where datistemplate=false;

From there, you can edit and run manually, or pipe further along into a script.  Here's a somewhat verbose one-liner:
echo \pset pager off \copy (select 'drop database "'||datname||'";' from pg_database where datistemplate=false) to STDOUT; | psql -U <user> -d postgres | <appropriate grep> | psql -U <user> -d postgres
Explanation:

*

*This is a series of pipes

*echo \pset pager off \copy (select 'drop database "'||datname||'";' from pg_database where datistemplate=false) to STDOUT; generates a string for psql to execute

*

*\pset pager off ensures you get all records instead of that (54 rows) crap

*\copy (select 'drop database "'||datname||'";' from pg_database where datistemplate=false) to STDOUT; executes the aforementioned query, sending the result to STDOUT. We have to do this since we lead with \pset.

*| psql -U <user> -d postgres pipes said string into psql, which executes it. Replace <user> with the user you want to use

*| <appropriate grep> is for stripping out the "Pager usage is off" line

*

*Windows users can use findstr /v "Pager" or findstr /b "drop"

**nix users can use grep 'drop'

*| psql -U <user> -d postgres pipes the resulting set of drop database commands into psql again, which executes them, thus dropping all the databases

*WARNING: Without any additional filtering, this will also drop the postgres database.  You can strip it either in the SELECT or the grep if you don't want that to happen.

A: Moving the database data somewhere else can achieve the same as deleting, and you can easily move it back in case you change your mind (But be sure to be careful and back up your data in any case).
1) Create a directory somewhere (e.g. /home/USERNAME/BACKUPDIR).
2) As a superuser go to the postgresql data directory (Fedora e.g. /var/lib/pgsql/)
3) Move the data to your backup folder: mv data /home/USERNAME/BACKUPDIR
4) Then reinit a new database using e.g. sudo postgresql-setup --initdb --unit postgresql

A: run this command as root:
cd /var/lib/postgresql/ && sudo -u postgres psql -c "SELECT 'dropdb '||datname||'' FROM pg_database WHERE datistemplate = false AND datallowconn = true And datname NOT IN ('postgres')" |grep ' dropdb ' |  sudo -u postgres /bin/bash ; cd


text:
Q: Maui Can't open MSIX installer The Error
I published the default Maui Project but I can't open the installer msix file.
I always the error The app was not started with no further information why.
I can however install it using the powershell script which comes with the publishing.
Is there any way how I can fix this or just get a reasonable error message?
More Info
My dotnet version: 7.0.100
My Visual Studio version: 17.5.0 Preview 1.0
My Windows version: Windows 11 22H2


text:
Q: Using a pronoun and a proper noun with a descriptor With the sentence: "If he was Little Freddie, the apple of Vinnie's eye, would have told him."
Does it mean if he was Little Freddie, or was he referring to Little Freddie? I think the meaning is for the latter, but reading the sentence itself makes me feel something's off.
If it's the former, how would one go about to make it mean the latter? Should it be "If he was, Little Freddie, the apple of Vinnie's eye, would have told him."
By the way, he refers to another person, not Little Freddie or Vinnie. Little Freddie is Vinnie's younger brother.
Here's a more complete example:

Vinnie feels like his father isn't telling the truth. If he was Little Freddie, the apple of Vinnie's eye, would have told him.

A: The sentence most likely means:

If he was [lying], Little Freddie would have told him.

The author's inclusion of "the apple of Vinnie's eye" makes the sentence very confusing to read because they subsequently dropped the comma after "was [lying]".
You could also rewrite the sentence as such:

Little Freddie, the apple of Vinnie's eye, would have told him if their father was lying.


text:
Q: Read (and write) SVG from Geopackage with QGIS There is the possibility to save the style of a layer in a geopackage:
Layer.saveStyleToDatabase
This style can be read by QGIS without additional code.
But is there a way for QGIS to read SVG symbols from a gpkg?
I could write the SVG by code, but reading should be done without additional code.

A: I was very interested by myself, to find out how we can package a QGIS project with all external dependencies inside a GeoPackage database. With the help of the "indispensible" expression editor, it's possible to reference SVGs/images stored in a BLOB column and base64 encode on-the-fly.

*

*Create a GPKG layer (i.e. "svg") with 2 columns (name:text,image:binary[blob])

*Store your SVG images in the layer "svg" (click on the "..." button to embed the SVG):

*Reference the SVG symbols in your vector layer (i.e. table "locations", column "type")

*Use SVG Marker styling with the following expression to display your SVG symbols

'base64:'|| to_base64(attribute(get_feature(
'svg','name',"type"),'image'))

*Praise the Qt developer, who has added support for inline SVGs and inline images!


text:
Q: postMessage from child to parent window in Safari using window.open I'm using window.open(...) to open a completely new window (same domain, same subdomain, same directory, same everything, but a different .html file).  In the child window, I'm using this to send messages back to the parent:
window.opener.postMessage({status:'ready'}, window.opener.location);

It works great in Chrome and Firefox ... but not in Safari.  Here are some alternatives I tried that did not work:
window.opener.* // no matter what I put, Safari says .opener is an empty object
window.parent // child refers to self despite different window, same subdomain

How can I get a reference to the parent window so I can send postMessage(...) messages back?


text:
Q: Layout Height AppCompat Not Full Screen What's wrong with AppCompat?
My application does not use AppCompat and there are no problems with XML Layout
But after I use AppCompat why is the XML Layout not full on the screen?

I tried by creating a new XML layout, but the results were the same.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Hello World!"/>

</LinearLayout>

A: Add this theme to your activity
in style.xml
<style name="AppTheme" parent="@style/Theme.AppCompat.Light.NoActionBar">
<item name="android:windowNoTitle">true</item>
<item name="android:windowActionBar">false</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowContentOverlay">@null</item>
</style>

and define this style to your activity in AndroidManifest :
<activity
android:name=".YourActivity"
android:theme="@style/AppTheme"/>

Using this will remove the extra space coming for toolbar by default.

A: You can achieve fullscreen mode when you use AppCompact like this
Add this to your style file
<style name="Theme.AppCompat.Light.NoActionBar.FullScreen"
  parent="@style/Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowActionBar">false</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowContentOverlay">@null</item>
</style>

And in your manifest file add this to your Activity tag
android:theme="@style/Theme.AppCompat.Light.NoActionBar.FullScreen"


text:
Q: How to capitalise every letter in odd position as in memes? For example, SoMeThInGlIkEtHiS
How might one achieve this? I am writing a meme paper this is important. . .

A: A LaTeX3 version, adapted from egreg's answer here:
\documentclass{article}
\usepackage{xparse}
\usepackage{expl3}

\ExplSyntaxOn
\NewDocumentCommand{\markletters}{m}
 {
  \int_zero:N \l_tmpa_int
  \tl_set:Nn \l_tmpa_tl { #1 }
  % replace spaces with something different
  \tl_replace_all:Nnn \l_tmpa_tl { ~ } { \c_space_tl }
  \tl_map_inline:Nn \l_tmpa_tl
   {
    \tl_if_blank:eTF { ##1 }
     { ~ } % don't advance the counter and issue a space
     {
      \int_if_odd:nTF { \l_tmpa_int } { \tex_lowercase:D } { \tex_uppercase:D } { ##1 }
      \int_incr:N \l_tmpa_int
     }
   }
 }
\prg_generate_conditional_variant:Nnn \tl_if_blank:n { e } { T,F,TF,p }
\ExplSyntaxOff

\begin{document}

\markletters{something like this}

\end{document}

A: A bit shorter with the xstring package:
\documentclass{article}
\usepackage{xstring}
\newif\ifupper\uppertrue
\newcommand{\mixedcase}[1]{%
\StrSplit{#1}{1}{\currentchr}{\tailchr}%
\ifupper\MakeUppercase{\currentchr}\upperfalse\else\MakeLowercase{\currentchr}\uppertrue\fi%
\IfStrEq{\tailchr}{}{\uppertrue}{\mixedcase{\tailchr}}%
}
\begin{document}
\mixedcase{something like this}
\end{document}

Same output as Andrews answer.
Explanation: split the string at the first character, make this character upper or lower case depending on a toggle (\ifupper), switch the toggle, check if there are characters left in the string (the second part of the split is not empty), if yes call the command recursively, if no then reset the toggle for the next time and stop.

A: Here's a slightly different LaTeX3 implementation using regular expressions. A space character is treated as a letter so that the two lines
\CaPiTaLiSe{Something like this}
\CaPiTaLiSe{Somethinglikethis}

produce slightly different capitalisations:

Here is the code:
\documentclass{article}

\usepackage{xparse}
\ExplSyntaxOn
\seq_new:N \l_evan_letters_seq
\cs_new_protected_nopar:Nn \evan_make_upper:n {
  \str_uppercase:n {#1}
  \cs_set_eq:NN \evan_capitalise:n \evan_make_lower:n
}
\cs_new_protected_nopar:Nn \evan_make_lower:n {
  \str_lowercase:n {#1}
  \cs_set_eq:NN \evan_capitalise:n \evan_make_upper:n
}
\NewDocumentCommand\CaPiTaLiSe{m}{
  \regex_split:nnN {} {#1} \l_evan_letters_seq
  \cs_set_eq:NN \evan_capitalise:n \evan_make_upper:n
  \seq_map_inline:Nn \l_evan_letters_seq {\evan_capitalise:n {##1} }
}
\ExplSyntaxOff
\begin{document}

  \CaPiTaLiSe{Something like this}

  \CaPiTaLiSe{Somethinglikethis}

\end{document}

Rather than incrementing a counter I have a dummy macro \evan_capitalise:n that swaps between choosing upper and lower case.


text:
Q: Convert SQL to eloquent query i have the next query with subequery how can convert it to eloquent, i have some troubles with eloquent conversion :S. Thanks
select a.* from (
    select *
    from "public"."tabla_procesados"
    where "state" LIKE '%Failed%'
    and id_execution = (select max(id_execution) from public.tabla_procesados)
    order by public.tabla_procesados.ts_start_processing desc limit 1
) a
where ts_start_processing < (now() - '10 minutes'::INTERVAL)

A: DB::query() returns an instance of the query builder.
From that instance, you can call from(table, alias) to set the main table the query is using. For subqueries, table can be another query builder containing the subquery, or a Closure.
You can also call DB::table(table, alias). It's the same as DB::query()->from(table, alias). alias is optional unless table is a subquery.

Using a query builders for every subquery:
$max = DB::query()
    ->selectRaw('max(id_execution)')
    ->from('public.tabla_procesados');

$sub = DB::query()
    ->from('public.tabla_procesados')
    ->where('state', 'like', '%Failed%')
    ->where('id_execution', $max)
    ->orderByDesc('public.tabla_procesados.ts_start_procesing')
    ->limit(1);

$query = DB::query()
    ->select('a.*')
    ->from($sub, 'a')
    ->whereRaw("ts_start_processing < (now() - '10 minutes'::INTERVAL");

Using Closures whenever possible:
$query = DB::query()
    ->select('a.*')
    ->from(function ($sub) {
        $sub->from('public.tabla_procesados')
            ->where('state', 'like', '%Failed%')
            ->where('id_execution', function ($max) {
                $max->selectRaw('max(id_execution)')
                    ->from('public.tabla_procesados');
            })
            ->orderByDesc('public.tabla_procesados.ts_start_procesing')
            ->limit(1);
    }, 'a')
    ->whereRaw("ts_start_processing < (now() - '10 minutes'::INTERVAL");

Executing the query
// string containing actual SQL that will be executed. Use to check if the query is the same.
$sql = $query->toSql();
// Execute query and get results into a Collection
$results = $query->get();


text:
Q: Find $a^3+b^3+c^3-3abc$ (binomial theorem)
$$a=\sum_{n=0}^\infty\frac{x^{3n}}{(3n)!}\\b=\sum_{n=1}^\infty\frac{x^{3n-2}}{(3n-2)!}\\c=\sum_{n=1}^\infty\frac{x^{3n-1}}{(3n-1)!}$$Find $a^3+b^3+c^3-3abc$:
$(a)\ 1$
$(b)\ 0$
$(c)-1$
$(d)-2$

Please help me solve this question.
I added $a,b$ and $c$. It gives me the expansion of $e^x$.
But i dont know how to use it.

A: Put $x=y\omega$ in the expansion of $e^x$ to get$$e^{y\omega}=\sum_{n=0}^\infty\frac{y^{3n}}{(3n)!}+\omega\sum_{n=1}^\infty\frac{y^{3n-2}}{(3n-2)!}+\omega^2\sum_{n=1}^\infty\frac{y^{3n-1}}{(3n-1)!}=a+b\omega+c\omega^2$$since $\omega^{3k}=1,\omega^{3k+1}=\omega,\omega^{3k+2}=\omega^2~\forall k\in\Bbb Z$.
Similarly, put $x=y\omega^2$ in the expansion of $e^x$ to get$$e^{y\omega^2}=a+b\omega^2+c\omega$$Finally, recall that $a^3+b^3+c^3-3abc=(a+b+c)(a+b\omega+c\omega^2)(a+b\omega^2+c\omega)=e^{y(1+\omega+\omega^2)}=1$ since $1+\omega+\omega^2=0$.


text:
Q: Azure WebApp + MySQL and Entity Framework : The system cannot find the file specified I have just deployed my web application on azure using Web App + MySQL app service.
I use entity framework for the database and after the deployment I am getting the "The system cannot find the file specified" exception. I think it has to do something about connection strings. I think that the application cannot actually connect the database.
I spent many days trying to figure out how to fix it. I've gone through so many tutorials about this but no success.
Application Settings
MySQL in App
I can only post 2 pictures.
This is the DbContext I used
to create a LocalDB, I am not sure how to change it to make a connection with the Database on Azure.
public class AppDbContext : DbContext
{
public AppDbContext() : base("Valtrends")
    {
        InitializeDbContext();
    }

    public DbSet<FactorType> FactorTypes { get; set; }
    public DbSet<ComplexType> ComplexTypes { get; set; }
    public DbSet<Value> Values { get; set; }
    public DbSet<DataLoader.Entities.Version> Versions { get; set; }
    public DbSet<DefaultPlotData> DefaultPlotData { get; set; }
    public DbSet<GraphBucket> GraphBuckets { get; set; }
    public DbSet<XfactorFrom> XfactorsFrom { get; set; }
    public DbSet<XfactorTo> XfactorsTo { get; set; }
    public DbSet<DistributionData> DistributionData { get; set; }
    public DbSet<Bin> Bins { get; set; }
    public DbSet<DefaultPlotSettings> DefaultPlotSettings { get; set; }

    private void InitializeDbContext()
    {
        Database.SetInitializer(new AppDbInitializer());
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<FactorType>().HasMany(m => m.CompatibilityListXY).WithMany();
    }

}

A: If you want to use MySQL in-app, I suggest you could firstly find the connectionstring by using the ftp.
You could firstly set the deployment credentials and use this username and passowrd access the webapplicaiton's ftp. Like below image shows:
Set the  deployment credentials.

Locate the mysql folder and find the MYSQLCONNSTR_localdb.txt as below:
Path:ftp://{url}.ftp.azurewebsites.windows.net/data/mysql/

You will find the connection string as below:
Database=localdb;Data Source=127.0.0.1:52739;User Id=azure;Password=6#vWHD_$

Note:The right connection string in your web config is like below, the connection string you get from the txt is wrong:
Database=azuredb;Data Source=127.0.0.1;User Id=azure;Password=6#vWHD_$;port=52739

Update: I suggest you could use GetEnvironmentVariable method to get the connection string, since the port of your my sql will be changed if restart the web service. You could try below codes to get the conneciton string and convert it to right format.
Get connection string and format it sample:
  public static string connStrToArray()
        {
            string connStr = Environment.GetEnvironmentVariable("MYSQLCONNSTR_localdb").ToString();
            string[] connArray = Regex.Split(connStr, ";");
            string connectionstring = null;
            for (int i = 0; i < connArray.Length; i++)
            {

                if (i == 1)
                {
                    string[] datasource = Regex.Split(connArray[i], ":");
                    connectionstring += datasource[0] + string.Format(";port={0};", datasource[1]);
                }
                else
                {
                    connectionstring += connArray[i] + ";";
                }
            }

            return connectionstring;
        }

Besides, I guess your localdb is used sql server, if you want to use mysql to become the EF data server provider, you need install the MySql.Data.Entity(you could find it in the Nuget Package) and use Database.SetInitializer to set the SqlGenerator to MySqlClient.
More details, you could refer to below dbcontext codes:
namespace TestForMySQL
{
    using System;
    using System.ComponentModel.DataAnnotations;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;
    using System.Text.RegularExpressions;

    public class MyContext : DbContext
    {

        public static string connStrToArray()
        {
            string connStr = Environment.GetEnvironmentVariable("MYSQLCONNSTR_localdb").ToString();
            string[] connArray = Regex.Split(connStr, ";");
            string connectionstring = null;
            for (int i = 0; i < connArray.Length; i++)
            {

                if (i == 1)
                {
                    string[] datasource = Regex.Split(connArray[i], ":");
                    connectionstring += datasource[0] + string.Format(";port={0};", datasource[1]);
                }
                else
                {
                    connectionstring += connArray[i] + ";";
                }
            }

            return connectionstring;
        }

        public MyContext( )
        {

            this.Database.Connection.ConnectionString = connStrToArray();
        }

        static MyContext()
        {

            //This is important
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, Configuration>());
        }

        public virtual DbSet<Mytest> MyEntities2 { get; set; }
    }

    internal sealed class Configuration : DbMigrationsConfiguration<TestForMySQL.MyContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
            //Change the SqlGenerator to MySql very important
            SetSqlGenerator("MySql.Data.MySqlClient", new MySql.Data.Entity.MySqlMigrationSqlGenerator());

        }

        protected override void Seed(TestForMySQL.MyContext context)
        {
            context.MyEntities2.AddOrUpdate(new Mytest()
            {
                Id = 1
            });
            context.SaveChanges();
        }
    }

    public class Mytest
    {
        public int Id { get; set; }

    }
}

what does the url in :ftp://{url}.ftp.azurewebsites.windows.net/data/mysql/ stand for? The URL of the app service doesn't work for me

You could find the ftp url and username in the overview like below:
See the FTP hostname and FTP/deployment username.

Update:

I have changed the credentials, but I have only URL, App Service plan/pricing tier and Continuous delivery status in the right column of Essentials

You could download the publish profile which contains the ftp url.
See below image:

The file:

Besides, there are another way you could find the storage connection string.
You could use kudu tool to directly see the files in your web service.
More details, you could refer to below steps.
1.Find the Advanced Tools in DEVELOPMENT TOOLS click go.

*Click dubug console's cmd.

3.Locate the right folder(data\mysql) and find the MYSQLCONNSTR_localdb.txt file.
Click the Edit button.

A: In asp.net, try printing connection string using,
protected void Page_Load(object sender, EventArgs e)
{
    Response.Write(Environment.GetEnvironmentVariable("MYSQLCONNSTR_localdb").ToString());
}

This will print your whole connction string
Now, $conn_str will give you the connection string.
and from connection string you can extract host, username and password for your MySQL Database.
you can use a function to do this for you,
protected void Page_Load(object sender, EventArgs e)
    {
        string conn_str = Environment.GetEnvironmentVariable("MYSQLCONNSTR_localdb").ToString();
        connStrToArray(conn_str);
    }
    public void connStrToArray(string connStr)
    {
        string[] connArray = Regex.Split(connStr, ";");
        string[] connArray2 = new string[] {};
        string[] keyArray = new string[] {"Database", "Data Source", "User ID", "Password"};
        for (int i = 0; i < connArray.Length; i++)
        {
            Response.Write(keyArray[i] + ":" + connArray[i].Substring(connArray[i].IndexOf("=") + 1).ToString() + "<br />");
        }
    }

find more about Asp.net and MySQL connection here.


text:
Q: Setting Cron Job in AWS EC2 instance I've created a cron job in AWS EC2 but it is not working.
I followed below steps to create cron tab:
Step 1: I logged in to AWS EC2 Instace
step 2: sudo su
step 2: crontab -e
Step 3: Insert mode
Step 4: I entered
    # M H DOM M DOW CMND

15 14 * * 3 /services/backup.sh >/tmp/error.log 2>&1

Step 5: :wq
Cron tab is created but not running.
Please can you any one help me , why it is not working?
UPDATE :
after lots of researching i found that i can give a log to the particular cron file so added >/tmp/error.log 2>&1 in my file and created error.log there.
but i am not getting any cron log there. now i think my cron file is not running(obviously it is not running).
but how to see whether i am lacking
and when i checked cron service it is running with the name crond
service crond status
crond (pid  28283) is running...

(backup.sh script absolutely running fine)

A: could you try full path of backup.sh in cron like below; you can use pwd command to find full path of your script.
# M H DOM M DOW CMND
25 12 * * 3 /home/user/script/backup.sh

Maybe, your cron service not started, you can check status with  "ps -ef | grep cron | grep -v grep"
if not see any thing run this;
sudo service cron start

if run; change cron as below;
15 13 * * 3 root /fullpath/backup.sh >/tmp/error.log 2>&1

then you check error.log
>/tmp/error.log 2>&1 is;
redirect the output of your program to /tmp/error.log. Include both the Standard Error and Standard Out

A: I think your issue might with permission and ownership of your backup.sh file.
Check the ownership of file and then do changes accordingly in your /etc/crontab file :
25 12 * * 3 <owner of the file>  /home/user/script/backup.sh

For example if the owner of file backup.sh is root then it should look something like this:
25 12 * * 3 root  /home/user/script/backup.sh

Hope this help!


text:
Q: php unquoted attribute value Hi I am trying to create my first REST service and have spent some time reading tutorials, I am following one through and in the client code I am getting a "=" in a unquoted attribute value.  in the href line between the last
 entry.  I can't see whats wrong.  I would like to get the example working and then build it up for the solution I am working on.
<?php

/*** this is the client ***/

if (isset($_GET["action"]) && isset($_GET["id"]) && $_GET["action"] == "get_user") // if the   get parameter action is get_user and if the id is set, call the api to get the user information
{
 $user_info = file_get_contents('http://localhost/RestServer/api.php?action=get_user&id=' . $_GET ["id"]);
$user_info = json_decode($user_info, true);

// THAT IS VERY QUICK AND DIRTY !!!!!
?>

    Name: 	 <?php echo $user_info["last_name"] ?>

    First Name: 	 <?php echo $user_info["first_name"] ?>

    Age: 	 <?php echo $user_info["age"] ?>

Return to the user list
<?php
}
else // else take the user list
{
$user_list = file_get_contents('http://localhost/RestServer/api.php?action=get_user_list');
$user_list = json_decode($user_list, true);
// THAT IS VERY QUICK AND DIRTY !!!!!
?>

<?php foreach ($user_list as $user): ?>

    <a href=<?php echo "http://localhost/RestClient/index.php?action=get_user&id=" . $user   ["id"]  ?> alt=<?php echo "user_" . $user_["id"] ?>><?php echo $user["name"] ?>

<?php endforeach; ?>

<?php
}
?>

A: <a href="<?php echo "http://localhost/RestClient/index.php?action=get_user&id=" . $user   ["id"]  ?>" alt="<?php echo "user_" . $user_["id"] ?>"><?php echo $user["name"] ?>

OR
<a href=<?php echo "'http://localhost/RestClient/index.php?action=get_user&id=" . $user   ["id"]."'"  ?> alt=<?php echo "'user_" . $user_["id"]."'" ?>><?php echo $user["name"] ?>

A: I have updated your code, and it works well
<?php echo ""; ?><?php echo $user["name"] . ""; ?>

A: May be helpful.
<a herf="http://localhost/RestClient/index.php?action=get_user&id="<?php echo $user["id"]; ?> alt="user_"<?php echo $user_["id"]; ?> > <?php echo $user["name"]; ?>

or
<a herf="http://localhost/RestClient/index.php?action=get_user&id=<?php echo $user['id']; ?>" alt="user_<?php echo $user_['id']; ?>" > <?php echo $user["name"]; ?>


text:
Q: Why is (-1)(-1) = 1? I apologize if this is too obvious, but I crave for a reasonable definition/explanation - why is
$(-1)(-1)=1$?
Something akin to the reason $a^{-1}=\frac{1}{a}$, I.e. because $a^{-1}a^1=a^{1-1=0}=1$, so we get $a^{-1}=\frac{1}{a^1}=\frac{1}{a}$ by dividing both sides by $a^1$.
That sort of stuff.

A: The similar would be $0(-1)=(1+(-1))(-1)=1(-1) + (-1)(-1)=-1+???=0$


text:
Q: What is meant by "the source character newline?" A particular definition in the python reference library (sub-section: string literals) is making me feel a lot of uncertainty.
shortstringchar ::= <any source character except "\" or newline or the quote>
What is meant by newline here? It definitely couldn't be \n, that's not just one source character, but two: \ and n. Right?
I've been told that it's an invisible character, characterized by the split of a string into two physical lines when you press "enter/return" on your keyboard. For example,
1 hello
2 world
there is a newline character between hello and world.
How true is this? Could I get some more detail and maybe some source material that talks about the newline character?

A: newline is in fact a single character, a control character; its hexadecimal value is 0x0a. The way it usually is written is \n, where \ "escapes" the following character, which is not a regular n but, in it's escaped context, the newline-character.
Put faith in good old wikipedia.

A: Actually (which is the case on windows) newline can consist of two characters: \r\n, the first of which has code 13 in decimal, the second is 10 in decimal. On linux it is just \n.
And yes, the wikipedia article linked in the other answer is pretty definitive on the subject.

A: Don't think of it as an "invisible character, characterized by the split of the string". At the level of bytes, a newline is like any other character -- with the glitch that sometimes it'll be one byte, sometimes (i.e. on Windows) you'll see two.
But instead of being shown as black pixels on your screen (or as ink, if you're printing out), a newline causes a repositioning of where the next characters will be displayed. Other characters also have special meaning, e.g. Control-G used to ring the terminal bell (or later to flash the screen), certain sequences of characters clear the screen, etc. What's special about newlines is that they don't just affect display, they signal the division of text into logical records (lines) when it is read or written.
PS. To make it easy to write and see a newline like any other character, many programming languages and notations understand \n to represent a newline. But that's just a way to communicate "newline", it's not what files contain or programs manage.

A: A newline is the character between these two words:

stack
overflow


text:
Q: Detect javascript console output with python When I'm working in a javascript-heavy application I like to use Console.log() a lot for debugging. However, I want to ensure I've properly suppressed all console logging in production.
I'd like to create a python script to walk through a site and generate a list of pages that write something to the console. I know I could just have it rip through the javascript files before minimization and search for "Console.Log" but I'm often the analyst on a project and consequently don't have access to the codebase. We also have a ton of sites that haven't been touched in a while but could use a scan (great intern project :-) ).
Is this doable with python?

A: What you can do is to use selenium browser automation tool and check the console logs:
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

capabilities = DesiredCapabilities.CHROME
capabilities['loggingPrefs'] = { 'browser':'ALL' }

driver = webdriver.Chrome(desired_capabilities=capabilities)

driver.get('http://foo.com')

# print console log messages
for entry in driver.get_log('browser'):
    print entry

Taken from Getting console.log output from Chrome with Selenium Python API bindings.


text:
Q: Adding a ProgressBar to a multithreaded Python script i am trying to add a progressbar  to my script but i couldn't succeed because i think it is multi-threaded or maybe it should be added  in a separate thread . i found plenty of solutions in stackoverflow , for example tqdm library but i couldn't implement it  , also i think i have a confusion where exactly i have to implement the progress bar code to make it works.
this is my code :
# -*- coding: utf-8 -*
from __future__ import unicode_literals
# !/usr/bin/python
import  codecs
from multiprocessing.dummy import Pool

start_raw = "myfile"
threads = 10

with codecs.open(start_raw, mode='r', encoding='ascii', errors='ignore') as f:
    lists = f.read().splitlines()
    lists = list((lists))

def myfunction(x):
    try:
        print x

    except:
        pass

def Main():
    try:
        pp = Pool(int(threads))
        pr = pp.map(myfunction, lists)

    except:
        pass

if __name__ == '__main__':
    Main()

i have tried this solution
https://stackoverflow.com/a/45276885/9746396 :
# -*- coding: utf-8 -*
from __future__ import unicode_literals
# !/usr/bin/python
import  codecs
from multiprocessing.dummy import Pool
import tqdm

start_raw = "myfile"
threads = 1

with codecs.open(start_raw, mode='r', encoding='ascii', errors='ignore') as f:
    lists = f.read().splitlines()
    lists = list((lists))

def myfunction(x):
    try:
        print (x)

    except:
        pass

def Main():
    try:
        pp = Pool(int(threads))
        pr = pp.map(myfunction, lists)

    except:
        pass

if __name__ == '__main__':
    with Pool(2) as p:
        r = list(tqdm.tqdm(p.imap(Main(), range(30)), total=30))

but code does not run and i get exception (TypeError: 'NoneType' object is not callable)
0%|                                                                                | 0/30 [00:00<?, ?it/s]Traceback (most recent call last):
  File "file.py", line 35, in <module>
    r = list(tqdm.tqdm(p.imap(Main(), range(30)), total=30))
  File "C:\mypath\Python\Python38-32\lib\site-packages\tqdm\std.py", line 1118, in __iter__
    for obj in iterable:
  File "C:\mypath\Python\Python38-32\lib\multiprocessing\pool.py", line 865, in next
    raise value
  File "C:\mypath\Python\Python38-32\lib\multiprocessing\pool.py", line 125, in worker
    result = (True, func(*args, **kwds))
TypeError: 'NoneType' object is not callable
  0%|                                                                                | 0/30 [00:00<?, ?it/s]

A: I presume you wanted to pass myfunction instead of Main to imap, consistently with the first example.
When you pass Main() to p.imap in r = list(tqdm.tqdm(p.imap(Main(), range(30)), total=30)), Python calls executes Main method and passes the return value as the first argument to imap.
You should remove the parentheses after Main as: p.imap in r = list(tqdm.tqdm(p.imap(Main, range(30)), total=30)).


text:
Q: Showing continuity in supremum norm Let $C([0,1])$ be the set of continuous functions $u:[0,1]\to \mathbb{R}$.
For any $u\in C([0,1])$, let a map $(Lu)(t) =
\frac{1}{2}\int\limits_0^1 e^{-u(x)}(x+t)dx$
Let the space $C([0,1])$ have the sup-norm metric, ie
$d(u,v) = \underset{x\in[0,1]}{sup}\{|u(x)-v(x)|\}$
I'm to show that L is a continuous function with respect to the sup-norm metric.
So I tried letting $u,v \in C([0,1])$, then
$|(Lu)(t)-(Lv)(t)| = |\frac{1}{2}\int\limits_0^1
(x+t)[e^{-u(x)}-e^{-v(x)}]dx|$,
but I don't know how to proceed from here, the $(x+t)$-bit throws me.
Help?!

A: Hint: $|(Lu)(t)-(Lv)(t)| = |\frac{1}{2}\int\limits_0^1
(x+t)[e^{-u(x)}-e^{-v(x)}]dx| $
$\le \frac{1}{2} \int_0^1(|x|+|t|)|e^{-u(x)}-e^{-v(x)}| dx \le \int_0^1|e^{-u(x)}-e^{-v(x)}| dx $,
since
$|x|+|t| \le 2$ for $t,x \in [0,1]$.

A: We need to prove that for two functions $u$ and $v$ if  $$\sup_{0<x<1}|u(x)-v(x)|<\epsilon$$which is equvalent to the following $$\forall 0<x<1 \qquad,\qquad |u(x)-v(x)|<\epsilon$$then$$\forall 0<t<1\qquad,\qquad|Lu(t)-Lv(t)|<k\epsilon$$with $k$ being a constant. Also by definition we have$$|Lu(t)-Lv(t)|=\frac{1}{2}|\int\limits_0^1 \left(e^{-u(x)}-e^{-v(x)}\right)(x+t)dx|\le\frac{1}{2}\int\limits_0^1 \left|e^{-u(x)}-e^{-v(x)}\right|(x+t)dx$$since both $u$ and $n$ have been defined on a compact set and are continuous so their range is a compact set and is bounded. Let$$|u(x)|<u$$therefore $$-u<u(x)<u\\-\epsilon<v(x)-u(x)<\epsilon$$substituting this in the latter integral gives us$$\frac{1}{2}\int\limits_0^1 \left|e^{-u(x)}-e^{-v(x)}\right|(x+t)dx\le\dfrac{e^u(e^{\epsilon}-1)}{2}\int\limits_0^1 x+tdx<e^u(e^\epsilon-1)$$using Taylor series$$e^u(e^\epsilon-1)=e^u(1+\epsilon+\dfrac{\epsilon^2}{2}+\dfrac{\epsilon^3}{6}+...-1)$$and for small enough $\epsilon$ we have $$e^u(e^\epsilon-1)<2e^u\epsilon=k\epsilon$$which is what we wanted to prove.


text:
Q: Remove everything from submodule directories (as they were before initial submodule update) I need to test a facility that calls git submodule update --init.
For the command to have a visible effect, I wish to reset submodule directories to the state they were in before I initially called submodule update -- i.e. a blank directory but still registered as a submodule.
If I just rm -rf everything under them, it's rather interpreted as a local change -- not what I need.
Removing and re-adding all the submodules is not something I wish to resort to unless there really is no better way.

A: git submodule deinit does that.


text:
Q: Access encrypted home directory of one user when I am logged in as another user On Ubuntu 14.04 I have created an encrypted home directory for a certain user A (with ecryptfs-utils & cryptsetup). However I am usually logged in as another user B. When I am logged in as user B, how could I access the contents of the home directory of user A as if it was not encrypted?
For example, since user B is an Admin, and I have user B's login credentials, I am (kind of) able to see the contents of user A's home directory from nautilus, but all I see there is some encrypted stuff.

A: User B being an admin does not mean it can decrypt the home directory of user A. The reason is that only when User A logs in the home folder is made available as if was not encrypted.
I believe this behavior is intended and it is - and should not be - possible.

A: I just founds this page looking for a similar solution and I can confirm I just did an su myuser and logged in from terminal
Then with root I could access all the files in myuser's home directory - actually using Mint but its based on Ubuntu so should be the same.

A: The ecryptfs mount overlays the existing home dir.  When you sudo su - other-user you become that user, but that doesn't mount the ecryptfs over the existing home dir.  For that you can use ecryptfs-mount-private.
related (my question):
Do I need unencrypted files underneath encrypted overmount?


text:
Q: Is there a configurable "word-of-the-day"-screensaver/ -widget I am looking for a "word-of-the-day" screensaver or dashboard widget where I can configure (e.g. in a text file) that "words" to be displayed?

A: AFAIK - there's word-of-the-day screensaver that comes packed with every Mac OS X (since Tiger). You can configure it on a "per dictionary" basis. So if you need a limited list of some words, just create your own dictionary, install it on the system and I believe you'll be able to use it in a screensaver yourself.


text:
Q: React MUI tooltip bigger arrow I'm trying to achieve bigger tooltip arrow using Material UI v4. I saw workaround for react-tooltip library using css property border-width. Is there any workaround for MUI tooltip arrow?

A: You need to override two style classes.
If overriding popperArrow class, styles apply to the Popper component if arrow={true} and if overriding arrow class, styles apply to arrow element when overriding arrow class.
const useStyles = makeStyles({
  popperArrow: arrowGenerator(),

  arrow: {
    width: 24,
    height: 17, /* = width / sqrt(2) = (length of the hypotenuse) */,
  }
});

export default function ArrowTooltips() {
  const classes = useStyles();

  return (
    <Tooltip title="Add" arrow classes={classes}>
      <Button>Arrow</Button>
    </Tooltip>
  );
}

Function arrowGenerator is defined to apply different styles based on the placement of the Tooltip.
function arrowGenerator() {
  return {
    '&[x-placement*="bottom"] $arrow': {
      marginTop: -17
    },
    '&[x-placement*="top"] $arrow': {
      marginBottom: "-0.71em"
    },
    '&[x-placement*="right"] $arrow': {
      marginLeft: "-0.71em"
    },
    '&[x-placement*="left"] $arrow': {
      marginRight: "-0.71em"
    }
  };
}

To have the best result you need to set margin values in this function according to the values you set for width and height when overriding arrow class.
Say you set placement="bottom" prop on your component, in '&[x-placement*="bottom"] $arrow': you need to set marginTop to the minus value of height you set for your arrow.

Reference: Tooltip file


text:
Q: How to save down currently displayed HTML page - Firefox? I have a webpage that I need to save down. I load the page with AutoPager.
But saving large pages loaded with AutoPager just won't work. (see my Q)
What I see on the page would be perfect (in HTML, that is).
I tried the "Inspect Element" and Firebug's tool as well, but they are not the same as I would save down the page with CTRL+S.
I also tried:

*

*Installing Firefox on Linux - nope.

*Try DownThemAll on the loaded
pages - nope.

*Install Nightly - nope.

*Install Firefox on a RamDisk - nope.

*Try 64-bit Firefox - nope.

*Try loading the rule into AutoPage/Chrome (it won't do anything) - nope.

Selenium would be great for example, but it can't save.
(Also, I would need to page on the file. Like Open the page, Save page, Click next, Save page, Click next, Save page, so on, so on.)

A: You could use Mozilla Archive Format firefox addon or SaveALL! But i prefer first ...


text:
Q: Unite two similar routes I have this two routes:
  get "shopping", to: "bar#show"
  get "shopping/*relative_path", to: "bar#show"

How can I join them, to one route?
When I simply omit get "shopping", to: "bar#show" then the user who goes to localhost:3000/shopping is not redirected to the controller bar#show
Thanks

A: You could make second part optional by wrapping it into parenthesis:
get "shopping(/*relative_path)", to: "bar#show"

Description of this behavior in docs.


text:
Q: Attribute Routing Inheritance I always used this approach in my MVC applications before
[Route("admin")]
public class AdminController : Controller
{

}

[Route("products")]
public class ProductsAdminController :AdminController
{
    [Route("list")]
    public IActionResult Index()
    {
        ...
    }
}

Url.RouteUrl() for Index action returned /admin/products/list/
Now in .NET Core it ignores base class route attribute and result is just /products/list/
Is this new to .NET Core? Is there any setup so system can combine action + controller + base-controller routes?

A: I can't find a way to combine action + controller + base-controller automatically, but it is possible to achieve what you're looking for like this:
[Route("admin")]
public class AdminController : Controller { }

public class ProductsAdminController : AdminController
{
    [Route("products/list")]
    public IActionResult Index()
    {
        ...
    }
}

This approach ends up generating a URL of /admin/products/list, with the obvious downside that products is something that needs to be repeated for each action. This might be an acceptable compromise; that's up to you to decide. You could make it a bit better with a constant, like this:
private const string RoutePrefix = "products";

[Route(RoutePrefix + "/list")]
public IActionResult Index()
{
    ...
}

It's not pretty as it's just a workaround, but worth considering if you don't want to go with Chris Pratt's Areas suggestion.

A: As far as I'm aware, that never would have worked. You could use areas, and by applying the [Area] attribute to the base controller, you'd get the result you describe:
[Area("admin")]
public class AdminController : Controller

[Route("products")]
public class ProductsAdminController : AdminController

The same would work in Core, as well.

A: Anyone still looking for a way to define "baseURL/ControllerName" in .Net core 3.1.
You would need to define RouteAttribute on your base controller like this:
[Route("admin/[controller]")]

Note [controller] would allow the routing to automatically take the controller name in child class.


text:
Q: How to turn off tab indicators for a specific file type in vim currently I have this in my .vimrc
:set listchars=tab:\|\

I would like to turn this off when working with csv files because it interferes with the vim csv plugin.
How do I achieve this in my .vimrc?

A: Add this to your .vimrc to not show tab characters on csv files
au BufNewFile,BufRead *.csv set nolist


text:
Q: Fuzzy string matching with support for words in multiple languages or different words with same meaning I'm looking for an algorithm that would support Fuzzy string matching like Damerau–Levenshtein or DICE or Longest Common Subsequence. But this algorithm should have the ability to match words in different languages and consider them equal when spelled in their respective languages or close if spelled incorrectly in their respective languages.
I think an example will better explain what I mean (1,2,5,6 form a group the same for 3,4,7,8) :
A well spelled cmpny name   A well spelled term we can find in multiple languages
    _____________           ___________________________________________________

1 StackOverflow             Question            // would easily match with 2
2 StackOverflow             Frage               // would easily match with 1
3 Swiss Life                Pension Fund        // would easily match with 4
4 Swiss Life                Caisse de pension   // would easily match with 3

Also, I would like them to be matched easily even if spelled incorrectly :
A misspelled company name   A misspelled term we can find in multiple languages
_________________________   ____________________________________________________

5 stackverflow              qestion        // would match easily with 1,2,6
6 SteckOverflw              frge           // would match easily with 1,2,5
7 Swisslife                 pension        // would match easily with 3,4,8
8 swizerland life           caisse pension // would match easily with 3,4,7

By match I mean having a good score. And I've actually tried to achieve this kind of comparison using Dice and lcs but the issue is that it's very weak against words spelled in multiple languages.
Look Dice coef in a tricky case :
name 1                  name 2                      coef
____________________    ______________________      _______________

migros pensionskasse    sig pensionskasse           0.769230769
migros pensionskasse    caisse pensions migros      0.727272727

The above first is better only because pensionskasse is matched and is larger than migros or sig. But because pensionskasse means caisse de pension the second should be better in the algorithm I seek.
I know the possible words that can be spelled in various languages so I can make a dictionary with the connections between those words.
I also could get rid of them (the multi-languages words) but then I would loose some insightful information to build groups based on those connections.
Has anyone seen an implementation that looks like this ? Ideally in C# ?


text:
Q: Sending a DataTable's content in an html email, what is the preferred way to generate HTML from a DataTable? Sending a DataTable's content in an html email, what is the preferred way to generate HTML from a DataTable?

A: Bind to GridView or DataGrid and use the RenderControl method.
http://blogs.x2line.com/al/articles/859.aspx

A: You could either :

*

*manually generate an HTML table by looping through the table data

*serialize the DataTable to XML (WriteXml method), and perform an XSL transform on the XML to generate HTML


text:
Q: callback function with underscore _.each() I'm trying to implement an _.each() (that I wrote) inside another function and I keep getting "undefined" returned to me. I'm trying to use _.each() to apply a test function to an array. I know this a simple callback syntax issue, but its perplexing me.
thanks in advance from a noob.
here's my function:
_.filter = function(collection, test) {
  _.each(collection, test());
};

this returns 'undefined'
this is the array i'm passing as 'collection':
[1, 2, 3, 4, 5, 6]

this is the function i'm passing as 'test':
function (num) { return num % 2 !== 0; }

here's my _.each():
_.each = function(collection, iterator) {

    if( Object.prototype.toString.call( collection ) === '[object Array]' ) {
        for (var i=0; i<collection.length; i++){
            iterator(collection[i], i, collection);
        }
    } else if (typeof collection === 'object'){
        for (var i in collection){
            iterator(collection[i], i, collection)
        }
    } else if (typeof collection === 'int'){
        console.log('int')
    }
};

A:  _.filter = function(collection, test) {
  var result =[];
  _.each(collection, function(curio) {
    if (test(curio))
    result.push(curio);
  });
  return result;
};

that fixed it


text:
Q: Dumpbin.exe for Linux to view imports I'm not sure my question makes sense in a linux way. I'm searching for something that would work similar to dumpbin.exe from Visual Studio toolkit.
Basically I have an existing project with a bunch of libraries and a single executable. I'd like to figure out which libraries are really needed and which function in each library.
I'm using shared objects only since this project targets an ARM device.

A: maybe you can use ldd and nm. ldd will tell you which shared objects (aka dll in win) are needed. and nm will tell dump the symbols.
example run:
$ ldd a
        linux-vdso.so.1 =>  (0x00007fffd1dff000)
        libc.so.6 => /lib/libc.so.6 (0x00007fcbc97d9000)
        /lib64/ld-linux-x86-64.so.2 (0x00007fcbc9b21000)
$ nm a
0000000000600e40 d _DYNAMIC
0000000000600fe8 d _GLOBAL_OFFSET_TABLE_
00000000004005b8 R _IO_stdin_used
                 w _Jv_RegisterClasses
0000000000601020 A __bss_start
0000000000601008 D __data_start
0000000000601010 D __dso_handle
                 w __gmon_start__
0000000000600e14 d __init_array_end
0000000000600e14 d __init_array_start
00000000004004d0 T __libc_csu_fini
00000000004004e0 T __libc_csu_init
                 U __libc_start_main@@GLIBC_2.2.5
0000000000601020 A _edata
0000000000601028 A _end
00000000004005a8 T _fini
00000000004003c0 T _init
0000000000400400 T _start
0000000000601008 W data_start
00000000004004b8 T main

EDIT: forgot about objdump. i.e:
$ objdump -f a

a:     file format elf64-x86-64
architecture: i386:x86-64, flags 0x00000112:
EXEC_P, HAS_SYMS, D_PAGED
start address 0x0000000000400400

using -x will give you all headers (quite verbose to post, but try it out :))


text:
Q: Why PHPmailer is not sending attachment? If I use the following code directly to a file e.g. test.php page then it sends the email with the attachment.
$email = new PHPMailer();
$email->From      = 'from address';
$email->FromName  = 'Your Name';
$email->Subject   = 'Message Subject';
$email->Body      = '
hello message
';
$email->AddAddress( 'to@gmail.com' );
$file_to_attach =  $path = '/home/xxxx/public_html/pdf/'.'1254.pdf';
$email->AddAttachment( $file_to_attach , '1254.pdf' );
return $email->Send();

But If I send the email with attachment with the above same code using a method of a class then it's not sending the attachment (message body is sending).
Mail class:
public static function sendMail ($to, $subject, $message, $from, $fromName, $attachment, $attachmentName) {

    $email            = new PHPMailer();

    $email->isHTML(true);
    $email->From      = $from;
    $email->FromName  = $fromName;
    $email->Subject   = $subject;
    $email->Body      = $message;
    $email->AddAddress($to);
    $file_to_attach   = $attachment;
    $email->AddAttachment( $file_to_attach , $attachmentName );

    return $email->Send();

}

Sending Email:
$path           = '/home/xxx/public_html/pdf/'.$confirm_id.'.pdf';
$pathFileName   = $confirm_id.'.pdf';

$message = "Hello $name";

$confirmMail = Mail::sendMail($email, "xxxx pdf confirmation", $message, "xxxx@xxxx.org", "xxxx.org", $path, $pathFileName );

if(!$confirmMail) {
    echo 'Confirmation mail is not sent';
}

Can you tell me where I'm doing wrong?!


text:
Q: Unable to upload multiple image to server Alamofire I tried too many time and used many way but could not upload image to server let me know what I am doing wrong,but unable to upload image to server.
func callsendImageAPI(){

        let headers: HTTPHeaders
        headers = ["Content-type": "multipart/form-data",
                   "Accept-Language": ApiService.instance.defaults[.langugaeCode] ?? "en",
                   "Authorization": "Bearer " + ApiService.instance.getToken()
        ]
        let url = BASE_URL + "uploadImages"
        AF.upload(multipartFormData: { (multipartFormData) in
            for item in self.carImages.enumerated() {
                switch item.element  {
                case .photo(let photo):
                    let image = photo.image
                    multipartFormData.append(image.jpegData(compressionQuality: 1)!, withName: "images[0]", fileName: "file.jpeg", mimeType: "image/jpeg")
                default:
                    break
                }
            }

        },to: url, usingThreshold: UInt64.init(),
        method: .post,
        headers: headers).response{ response in

            if((response.error != nil)){
                do{
                    if let jsonData = response.data{

                        let jsonDecoder = JSONDecoder()
                        let JSON = try jsonDecoder.decode([RegularPostImage].self, from: jsonData)
                        print(JSON)
                    }
                }catch{
                    print("error message")
                }
            }else{
                print(response.error)
            }
        }
    }

Thanks in Advance


text:
Q: php echo DOM Elements as strings I have used the following code to store a small timetable in an array. I am trying to return specific elements of the array but get the error Cannot use object of type DOMElement as array.
I would be grateful if somebody could tell me how to retrieve the nodeValue of certain elements and display them.
$doc = new DOMDocument();
$doc->loadHTML($timetable);
$headers = $doc->getElementsByTagName('th');//' missed which is typo i think
$cells = $doc->getElementsByTagName('td');//' missed which is typo i think
$array = iterator_to_array($cells);

I can loop through this and display the entire table with a for loop, and that's fine, but I can't return 1 value from the array:
for ($i=0; $i<=5; $i++){
  $val = $array[$i];
  echo $val[1]->nodeValue;
}

And this returns the error I mentioned above.


text:
Q: Downloaded OCaml, get error "Bad CPU type in executable" So I'm running Mac OS X Yosemite 10.10.5. I need to use OCaml 3.08.3 to run someone else's code (the code won't run with the latest version of OCaml...), and I downloaded the .dmg file here. The installation seemed to be fine, but whenever I run the command 'ocaml' in Terminal, I get
-bash: /usr/local/bin/ocaml: /usr/local/bin/ocamlrun: bad interpreter: Bad CPU type in executable

Anyone know what's up? Would greatly appreciate any help.

A: The version that you downloaded works only for Mac OS X 10.3 (Panther). It might work for some other versions, but it is not guaranteed. In MacOS, binaries compiled for one version, are often not compatible with other versions.
If you need a version of OCaml for which there is no binary distribution, you can always build it yourself, either manually (the hard way), or via the OPAM system.
Alternative solutions would be using Docker or a virtual machine.
Update
Also, the code that you're trying to compile doesn't really need exactly 3.08. It compiles perfectly fine on any version of a compiler, up to 4.04. The problem is that in a build system a fatal warning flag is turned on so that all warnings are translated to errors (a very bad practice of distributing software, I would like to say). The good news is that it can be easily fixed, just open Makefile in a text editor, and remove all occurrences of the following string -warn-error A.