text:
Q: Copying from vector into a struct in C++ 11 In C++ 11, what is the best way to perform the following code:
// definitions
vector<char> rcvbuf;

 struct somethingParams
{
  char Magic[4];
  int Version;
  int MsgID;
  int MsgLen;
};

Code:
struct somethingParams mParams;
memcpy(&mParams, rcvbuf.data(), sizeof(somethingParams));
rcvbuf.erase(rcvbuf.begin(), rcvbuf.begin + sizeof(somethingParams));

From what I've read, memcpy is not recommended in C++. I understand that it is "C-style". Is there a better way to achieve what I am doing above? (ie. Copying data from a vector into a struct.)
Just see-ing if I can make it more "C++".
Thanks.

A: memcpy is kosher in C++. Of course it should not be used to make a copy of an array (we have std::copy for that, as well as vectors and other fun things) but the case of initializing a struct from binary data is inherently type-unsafe so C++ doesn't give you anything here that C doesn't.
You must, however, remember to use memcpy only with trivially copyable types. You can use a static_assert to make sure you don't run afoul of this rule and trigger undefined behaviour.
static_assert(std::is_trivially_copyable<somethingParams>::value,
              "somethingParams must be trivially copyable");

A: Your code is confusing. You have a vector of chars (of length n let's say) on the one hand.
And you have a struct with a char array of length 4 and three ints.
I don't see what a blind memcpy would bring as a reasonable result really.
But maybe I can evoke some thoughts that could help you dig further:

*

*A vector of char elements could maybe replaced by a string object? A string object is meant to hold a char array internally. I consider this more C++, but depends on your requirements.

*memcpy simply copies memory. I am not sure if this is what you want; I reckon the struct contains garbage after the copy. Unpredictable in my opinion.

*To copy from a container (a vector is an STL container) a standard way of doing it in C++ (apart from the aforementioned std::copy function) is by iterating over the elements and copy them. See below.

Most familiar with iterators:
for (vector<char>::iterator it = rcvbuf.begin(); it != rcvbuf.end(); it++) {
    //copy element *it into something
}

C++11 introduced auto range for loops:
for (auto elem : rcvbuf) {
    //copy element elem into something
}

Further elaboration:
The vector contains 16 elements. The 4th element is the null character to simulate the end of the C style string. Without the null character the char array would contain garbage too.
I removed the erase for simplicity. It simply erases the elements in a specified range (by iterators); in your case it simply removes sizeof(somethingParams) bytes/chars from the vector, provided it contains enough elements, otherwise segmentation fault is likely.
See the result below, it's plain nonsense.
char t[] = {'a', 'b', 'c', '\0', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o'};
vector<char> rcvbuf(t, t + 16);

struct somethingParams {
    char Magic[4] = {'w', 'x', 'y', 'z'};
    int Version{99};
    int MsgID{99};
    int MsgLen{99};
} mParams;

memcpy(&mParams, rcvbuf.data(), sizeof(somethingParams));
//rcvbuf.erase(rcvbuf.begin(), rcvbuf.begin() + sizeof (somethingParams));

cout << "Magic:   " << mParams.Magic << endl;
cout << "Version: " << mParams.Version << endl;
cout << "MsgID:   " << mParams.MsgID << endl;
cout << "MsgLen:  " << mParams.MsgLen << " bytes" << endl;

Result (with int occupying 4 bytes on my machine):
Magic:   abc
Version: 1734763876
MsgID:   1802135912
MsgLen:  1869507948 bytes


text:
Q: I can't update angular app from 6.1 to angular 8 on yarn workspace with lerna I want to upgrade my angular app from 6.1 to 8.0. My setup has lerna and yarn workspace. I want to upgrade each package in the repo. When I follow the update instruction on https://update.angular.io/ I doesn't update the sub packages . I tried to search about this problem but I haven't found a solution.
I run "ng update @angular/core @angular/cli" but I just managed to update the main package.json packages but when I check the sub packages they are still on angular 6.1. I have also tried this https://www.npmjs.com/package/lerna-update-wizard to update but it still fail.
If anyone has this situation before I would appreciate the help. Thanks

A: I found an answer, if you have a setup of packages as a monorepo, you would need to use a package to update each angular application package.json.
I used https://www.npmjs.com/package/npm-check-updates.
run lerna exec "npx npm-check-updates -u '/^(@angular).*$/'" to upgrade only angular packages to latest. this /^(@angular).*$/ means select only angular applications.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Customize URL to a failed build in MailNotifier When my buildbot fails, it is configured to send an email.
Current configuration is:
mailNotify = MailNotifier(fromaddr="****@****.com",
sendToInterestedUsers=True,
extraRecipients=['*****@*****.com', '****@****.com'],
relayhost="mail.****.com",
smtpPort=587,
addLogs = True,
addPatch = True,
useTls=True,
smtpUser="****@****.com",
smtpPassword="****"
mode="failing")

I have a buildmaster setup in my local network, at 192.168.1.11. Because of that, when an email comes, it contains the following information:
Full details are available at:
 http://192.168.1.11:8020/builders/BuilderName/builds/136

Buildbot URL: http://192.168.1.11:8020/

Apart from that, I have a publicly accessible server, by which I can access buildbot, i.e. https://mydomain.com/buildbot/
What I want to get is
Full details are available at:
https://mydomain.com/buildbot/builders/BuilderName/builds/136

Buildbot URL: https://mydomain.com/buildbot/

I'd love NOT to rewrite a whole message formatter, but I couldn't find a way to do that. Is it even possible?

A: AFAIK the best way is to write your own messageFormatter(). It is not much of a pain. I have done it for my buildbot and it works like a charm.
If you look into the sources buildbot\status\mail.py there is function called defaultMesage(...). Just override this in your buildbot's configuration and pass it to the MailNotifier constructor ! Most likely you have to change just the line:108
def myMessageFormatter(mode, name, build, results, master_status)
    # Copy everything from buildbot\status\mail.py:defaultMessage()

    # Change this to point to https://mydomain.com/buildbot/
    if master_status.getURLForThing(build):
        text += "Full details are available at:\n %s\n" % master_status.getURLForThing(build)
    text += "\n"


text:
Q: R Squared missing from output of coxph I'm new to R and am doing an online course. I'm running a cox model, but not getting an r squared value in the output. Anyone know why?
cox2 <- coxph(Surv(fu_time,death) ~ age_cat)
> summary(cox2)
Call:
coxph(formula = Surv(fu_time, death) ~ age_cat)

  n= 1000, number of events= 492

                   coef exp(coef) se(coef)      z Pr(>|z|)
age_catUnder 65 -1.4264    0.2402   0.2402 -5.938 2.88e-09 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

                exp(coef) exp(-coef) lower .95 upper .95
age_catUnder 65    0.2402      4.164      0.15    0.3846

Concordance= 0.549  (se = 0.007 )
Likelihood ratio test= 56.34  on 1 df,   p=6e-14
Wald test            = 35.26  on 1 df,   p=3e-09
Score (logrank) test = 41.66  on 1 df,   p=1e-10

A: R packages are "live", they change with time. Form version 2.44 of the package "survival", summary.coxph does not report R2 anymore.
You can read the reason for this in the "Changes in version 2.44":

The Nagelkirke R^2 has been removed from summary.coxph. The
  shortcomings of this measure are well known, concordance is a better
  measure.


text:
Q: Extending a resource created inside a module to avoid redundancy to set up a Docker Swarm with Terraform Let's say I've a module which creates some resources that represent a default server. Now I want to inherit this default server to customize it into different directions.

At the Manager node which inherits the DockerNode I want to run docker swarm init and get the join token. On all Worker nodes I want to join with the token.
So in my main.tf where I use the DockerNode I have defined the nodes like this:
module "manager" {
  source = "./modules/swarm-node"

  node_network = {
    network_id = hcloud_network.swarm-network.id
    ip         = "10.0.1.10"
  }
  node_name_prefix       = "swarm-manager"
  server                 = var.server
  docker_compose_version = var.docker_compose_version
  volume_size            = var.volume_size
  volume_filesystem      = var.volume_filesystem
  ssh_keys               = [hcloud_ssh_key.ssh-key-a.name, hcloud_ssh_key.ssh-key-b.name]

  depends_on = [
    hcloud_network_subnet.swarm-network-nodes
  ]
}

module "worker" {
  count  = 2
  source = "./modules/swarm-node"

  node_index = count.index
  node_network = {
    network_id = hcloud_network.swarm-network.id
    ip         = "10.0.1.10${count.index}"
  }
  node_name_prefix       = "swarm-worker"
  server                 = var.server
  docker_compose_version = var.docker_compose_version
  volume_size            = var.volume_size
  volume_filesystem      = var.volume_filesystem
  ssh_keys               = [hcloud_ssh_key.ssh-key-a.name, hcloud_ssh_key.ssh-key-b.name]

  depends_on = [
    hcloud_network_subnet.swarm-network-nodes,
    module.manager
  ]
}

*

*How to run docker swarm init and return the join token on the server resource inside of module.manager?

*How  to join the swarm with each worker?

I've researched this for quite a while:

*

*Some solutions expose the Docker Daemon over TCP and access it from the worker to get the token. I don't like to expose the Docker Daemon unnecessarily.

*Some solutions copy the base module (in my case DockerNode) just to modify one or two lines. I like to to follow DRY.

*Some solutions have an additional shell script, which read the .tfstate and SSH into each machine to do further customization. I would like to use Terraform for this with all it's benefits.


text:
Q: Как вставить слово в текст на php? Нужно подмешать ключи в текст в случайное место в тексте и желательно выставить количество вставок ключей или в числовой форме или в процентах.
Пытался использовать так:
$final_text = str_replace (", ",", keyword ",$text);

Но блин, заменяются все запятые и получается переспам, как можно рандомизировать место вставки и контролировать количество вставок?

A: $count = 3;
$text = 'Some text';
$keyword = '-';
$lengh = strlen($text);

for ($i = 1; $i <= $count; $i++) {
     $text = substr_replace($text, $keyword, rand(0, $lengh) , 0);
}

echo $text;

Пример Нужно еще проверку места добавить, чтобы два подряд не было. Но суть я думаю понятна.


text:
Q: Why can't I access my extensions' settings on the frontend? Trying to access a few settings that I've created in my constants.txt file. It looks like this:
plugin.tx_my_ext {
    settings {
        # cat=plugin.tx_my_ext/urgences; type=boolean; label=Activer les urgences
        activerUrgences = 0
    }
}

Then in my setup.txt file I have this:
plugin.tx_my_ext.settings.activerUrgences = {$plugin.tx_my_ext.settings.activerUrgences}

Any reason why I wouldn't be able to access my settings using {settings} in my Fluid layout?
BTW, my extension name does include an underscore _ between the words. I have tried removing the underscore, then removing the tx_, and then a combination of those two.
Any help would be appreciated!
Thanks

A: *

*For ext with key my_ext it should be plugin.tx_myext.settings

*Make sure that you 'Included static from extension' in your TypoScript Template. If your ext is not available on the list add it in ext_localconf.php like that:
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addStaticFile($_EXTKEY, 'Configuration/TypoScript', 'MyExt');

*Do not forget to clear System cache and FE cache at least million times ;)

*Use TypoScript object browser to check if on given page your plugins TS is still available (maybe something resets TS in meanwhile:

*Finally make sure that you don't clear $this->settings array within your controller, if you do manipulate it for any reason assign it to the view again before view rendering,like that:
$this->view->assign('settings', $this->settings);


text:
Q: Does Perl support named parameters in function calls? In my experience of languages that support the feature, programs that call functions with named parameters rather than positional parameters are easier to read and maintain.
I think Perl has this feature, but it's not working for me.
Is it a quirk of the package I'm using, or am I doing it wrong?
Setting up the function call
My fist Perl project is to use the HTML::TableExtract package to extract table data from HTML markup and display it as text.
The following code sets up the parser:
use strict;
use warnings;
use HTML::TableExtract;

my $markup = <<MARKUP;

 a	 b	 c

 1	 2	 3

 4	 5	 6

MARKUP

my $parser = HTML::TableExtract->new() ;

$parser->parse($markup) ;

The documentation says that I can dump output to the Command Prompt using the tables_dump method and use parameters $show_content and $col_sep to control the output format:

tables_report([$show_content, $col_sep])
Return a string summarizing extracted tables, along with their depth and count. Optionally takes a $show_content flag which will dump the extracted contents of each table as well with columns separated by $col_sep. Default $col_sep is ':'.
tables_dump([$show_content, $col_sep])
Same as tables_report() except dump the information to STDOUT.

Calling with positional and with named parameters
If I pass positional parameters in documentation order, I get the output I expect:
$parser->tables_dump(1, '_') ;

The columns are separated by an underscore instead of the default colon:
TABLE(0, 0):
a_b_c
1_2_3
4_5_6

Following Perl.com's Advance Subroutines article, I tried to pass a hash containing parameter names and values to clarify the meaning of the parameters:
$parser->tables_dump({show_content => 1, col_sep => '_'}) ;

Perl doesn't understand this. It ignores the value of col_sep and outputs with the default value:
TABLE(0, 0):
a:b:c
1:2:3
4:5:6

I get the same output if I don't try to change the separator:
$parser->tables_dump({show_content => 1}) ;

Even if I specify nonsense parameter names, I get the same output:
$parser->tables_dump({tweedledum => 1, tweedledee => '_'}) ;

Can I call this function using the named parameter style, or should I just settle for positional?

A: Named parameter passing in Perl (even with default values) is explained very well in Object Oriented Perl, Chapter 6.
This style is very important and is widely used in object constructors. That's why it is explained in their OO Perl book.
I will quote two of their examples:
# This is how you call a subroutine using named argument passing
interests(name => "Paul", language => "Perl", favourite_show => "Buffy");

# This is how you define the subroutine to accept named arguments
sub interests {
   my (%args) = @_;

   # This is how you capture named arguments and define
   # defaults for the ones missing from a particular call.
   my $name           = $args{name}           || "Bob the Builder";
   my $language       = $args{language}       || "none that we know";
   my $favourite_show = $args{favourite_show} || "the ABC News";

   print "${name}'s primary language is $language. " .
   "$name spends their free time watching $favourite_show\n";
}

Another example that gives a different way of defining defaults (in a hash) is this:
my %defaults = ( pager => "/usr/bin/less", editor => "/usr/bin/vim" );

sub set_editing_tools {
    my (%args) = @_;

    # Here we join our arguments with our defaults. Since when
    # building a hash it's only the last occurrence of a key that
    # matters, our arguments will override our defaults.
    %args = (%defaults, %args);

    # print out the pager:
    print "The new text pager is: $args{pager}\n";

    # print out the editor:
    print "The new text editor is: $args{editor}\n";
}

A: Perl has no built-in support for named parameters. If you want to use them, the function has to be specifically written to accept arguments in that style. So you'll have to settle for positional arguments (or write a wrapper function (probably in a subclass)).

A:
Following Perl.com's Advance Subroutines article, I tried to pass a
  hash containing parameter names and values to clarify the meaning of
  the parameters:

That article covers a way to write subroutines such that they will accept a hashref of named parameters.  If you're calling a sub that isn't written to accept that, then it won't know how to handle it correctly.

$parser->tables_dump({show_content => 1, col_sep => '_'}) ;

Perl doesn't understand this. It ignores the value of col_sep and
  outputs with the default value:

Not to be overly pedantic, but Perl understands that just fine.  However, tables_dump is only written to accept a list of scalar parameters.  When you call it that way, it receives a single scalar parameter.  This parameter just happens to be a reference to a hash, but tables_dump doesn't know or care about that, so it uses the reference as the value of $show_content.  This is probably equivalent to passing 1 for show_content, since both 1 and any possible reference will evaluate as "true" in boolean context and I assume that $show_content is only ever used as a boolean.
Since there is no second parameter, nothing gets assigned to $col_sep, so it uses the default separator, as you observed.

A: It's not too complicated. You pass the key-value pair like a hash or as a hash reference, and in the subroutine you load the arguments into a hash or hash reference.
# called like $parser->tables_dump({show_content => 1, col_sep => '_'}) ;
sub TheParser::tables_dump {
    my ($self, $args) = @_;
    if ($args->{show_content} == 1) {
        print join $args->{col_sep}, $self->the_column_data();
        ...
    }
}

With another line, you can load the named arguments you know about into appropriately named variables:
    my ($self, $args) = @_;
    my ($show_content, $col_sep) = @$args{qw(show_content col_sep)};
    if ($show_content == 1) {
       ...

A: Going off just the title's question, you could do something like the below:
use strict;
use Carp::Assert;

sub func {
   my (%hash) = @_;
   assert($hash{'baz'} == 1);
   assert($hash{'mu'} == 2);
}

func('baz' => 1, 'mu' => 2);

A: Perl doesn't natively support named parameters, however it's possible to design functions to accept named parameters (as a hash or hashref).  It's up to the author of the function as to how they implement it.  You'll need to supply arguments the function is expecting or you'll get unexpected results.

A: Here is a simple program I wrote that can use a type of named parameters. It allows for default values.
#!/usr/bin/perl
use strict;
use warnings;
use 5.014;
use POSIX qw/ strftime /;

# Script to get prior Monday (if today is Mon, then Mon a week ago).

for my $day (qw/ Sun Mon Tue Wed Thu Fri Sat /) {
    say "Last $day: ", last_monday( day => $day );
}

sub last_monday {
    my %arg =  ( time => [localtime],
                 day  => 'mon',
                 span => 1,
                 @_
               );
    my $dow; # day of week

    if    ('sunday'    =~ /$arg{day}/i) { $dow = 0}
    elsif ('monday'    =~ /$arg{day}/i) { $dow = 1}
    elsif ('tuesday'   =~ /$arg{day}/i) { $dow = 2}
    elsif ('wednesday' =~ /$arg{day}/i) { $dow = 3}
    elsif ('thursday'  =~ /$arg{day}/i) { $dow = 4}
    elsif ('friday'    =~ /$arg{day}/i) { $dow = 5}
    elsif ('saturday'  =~ /$arg{day}/i) { $dow = 6}
    else {
        warn "$arg{day} is not a valid day of week. $!";
        return;
    }

    my ($wday, @dmy) = @{ $arg{time} }[6, 3..5];

    # (will work across month, year boundries)
    $dmy[0] -= ($wday - $dow) % 7 || ($arg{span} ? 7 : 0); # $dmy[0] == mday
    return strftime "%Y%m%d", 0,0,0,@dmy;
}


text:
Q: 2nd exploded string to be a value to 1st exploded string in php I'm new to php.. This is my problem: I have 2 exploded string, I want to make the 2nd exploded string to be the value of the 1st exploded string, the result of this I want    to insert in my database, but I don't have any problem with inserting.
For example, in the code below I want the $date to be a value to the $layer.
1st word of $layer is a value to 1st word of $date, 2nd word to 2nd word and so on..
$layer1=$_POST['layer'];

$date=$_POST['date'];

$layer=explode(",",$layer1);
$date=explode(",",$date);

foreach ($layer as $layer2=>$date )
{
//my problem is how to make the date a value to my layer?
$con=mysqli_connect("localhost","xxxx","xxx") or die ('unable to connect server');
mysqli_select_db($con, "xxxxxxxx") or die ('cant connect database');

$x="INSERT INTO xxxxx (Layer, date ) VALUES ('$layer2', '$date') ";
$result=mysqli_query($con,$x) or die ('cant proceed query');

//i want to appear look like this on database:

LAYER       DATE
layer1      date1
layer2      date2
layer3      date3

say my data inputted from form is this one:

$_POST['layer']=layer1,layer2,layer3
$_POST['date']=date1,date2,date3

A: $con = mysqli_connect("localhost","xxxx","xxx", "xxxxxxxx");

$layer_arr = explode(",",$_POST['layer']);
$date_arr  = explode(",",$_POST['date']);

foreach ($layer_arr as $key => $layer )
{
    $date  = $date_arr[$key];
    $date  = mysqli_real_escape_string($con, $date);
    $layer = mysqli_real_escape_string($con, $layer);

    $sql   = "INSERT INTO xxxxx (Layer, date ) VALUES ('$layer', '$date') ";
    $result=mysqli_query($con,$x) or trigger_error(mysqli_error($con));
}

please note that instead of manual formatting your strings you have to use placeholders in your query and thus use PDO instead of mysqli.


text:
Q: invalid block-tag when I implement i18n I'm currently adding i18n in my website but there is something wrong.
When I use code from djangoproject
<form action="{% url 'set_language' %}" method="post">
{% csrf_token %}
<input name="next" type="hidden" value="{{ redirect_to }}" />
<select name="language">
{% get_language_info_list for LANGUAGES as languages %}
{% for language in languages %}
<option value="{{ language.code }}">{{ language.name_local }} ({{ language.code }})</option>
{% endfor %}
</select>
<input type="submit" value="Go" />
</form>

I get this error

Invalid block tag: 'get_language_info_list'

I don't understand why get_language_info_list is unknown. Templates_context_processors is ok. HTML form is on my homepage.

A: Always make sure you load the tag library first before you requests any tags. To use get_language_info_list, you need to make sure {% load i18n %} is in your template.


text:
Q: Correlation between three variables Here is my question.
If A and B has a correlation of 0.8, B and C has a correlation of 0.6. What is the range of correlation between A and C?

A: Let $A=(a_1,\ldots,a_n)$.
Let $\bar a=(a_1+\cdots+a_n)/n$.
Let $A_\text{corrected} = (a_1,\ldots,a_n) - (\bar a,\ldots,\bar a)$.
Let $\displaystyle \operatorname{ss}_A^2 = \langle A_\text{corrected},A_\text{corrected}\rangle$ where $\langle\cdot, \cdot\rangle$ is the dot product, the usual inner product and $\operatorname{ss}$ stands for "sum of squares". And let $\operatorname{ss}_A = \sqrt{\operatorname{ss}_A}$$.
Then $\displaystyle \left\langle \frac{A_\text{corrected}}{\operatorname{ss}_A}, \frac{A_\text{corrected}}{\operatorname{ss}_A} \right\rangle = 1$.
And similarly for $B$ and $C$.
Then the correlation is $\displaystyle \operatorname{corr}(A,B) = \left\langle \frac{A_\text{corrected}}{\operatorname{ss}_A}, \frac{B_\text{corrected}}{\operatorname{ss}_B} \right\rangle = \cos\theta_{AB}$, where $\theta_{AB}$ is the angle between these two unit vectors.
Then $\theta_{AB} = \arccos 0.8$ and $\theta_{BC}= \arccos0.6$.
The correlation $\cos\theta_{AC}$ must be between $\cos(\theta_{BC} \pm \theta_{AB})$.  Notice that $\theta_{AB}+\theta_{BC} = 90^\circ$ because of the Pythagorean theorem.
This puts the correlation between $0$ and $0.96$ --- not a very narrow range, but it rules out a negative correlation between $A$ and $C$.
Here I've dealt only with a finite sample in which I've assigned each point a weight of $1/n$, but the whole thing can also work for discrete distributions on infinite set and for continuous distributions and other distributions.  One would use integrals rather than sums for continuous distributions.


text:
Q: Error while extracting the zip file I am facing a problem while extracting some windows .xap, it gives me error show in the image below..

I have tried to replace the current .dll witih new dotnetzip .dll , but still facing same error..
Any Suggestions ??


text:
Q: Cant handle event in vue.js I was trying to handle an event in vue.js , But i think the function mm is out of scope . the error i am getting is [Vue warn]: v-on:mouseover="mm" expects a function value, got undefined .
This is my code
    var menuHover=new Vue({
            e1:'#t',
            data:{
                active:true
            },
            methods: {
                mm: function()
                {
                    alert(1);
                    This.active=!this.active;
                }
            }
        }
    );

This is my html

Test vue

I tried several links and solutions , none of them worked .

A: try this:jsfiddle,i have run this and success.

       {{message}}

Test vue

this is the js:
 new Vue({
  el: '#app',
   data: {
   active:true,
     message: 'Hello Vue.js!'
   },
    methods: {
            mm: function(){
                alert(1);
                this.active=!this.active;
            }
        }
 })


text:
Q: R compare with median, into T/F I am new to R and I would like to ask your help with the following topic.
Sorry that I nv implement the sample, but the dataset is roughly like this but there are more columns and rows.
statistic                            total
#    Subject Min Median   Max        #     row.names    Art   English ...
#1   Art     20    59     70         #1      James       59     61
#2   English 30    55     65         #2      Lloyd       60     55
...                                  ...

Compare the (statistic table, median) more(>)than (total table ,each of their subject) into TRUE(1) or FALSE(0)
output
#    names      Art         English
#1   James      0           1
#2   Lloyld     1           0

Thanks in advance!

A: Assuming that the order of Subject in statistic is the same as the column order in total
 output <- total
 nm1 <- setdiff(colnames(total), "row.names")

 output[,nm1] <-(total[,nm1] >statistic$Median[col(total[,nm1])])+0
 output
 #  row.names Art English
 #1     James   0       1
 #2     Lloyd   1       0

Update
If there are NA values in the total dataset, for example
total1 <- total
total1$English[1] <- NA
output1 <- total1
output1[,nm1] <- (total1[,nm1] > statistic$Median[col(total[,nm1])])+0
output1[is.na(output1)] <- 0
output1
#     row.names Art English
#1         1   0       0
#2         1   1       0

data
total <- structure(list(row.names = c("James", "Lloyd"), Art = 59:60,
    English = c(61L, 55L)), .Names = c("row.names", "Art", "English"
   ), class = "data.frame", row.names = c("1", "2"))

statistic <-  structure(list(Subject = c("Art", "English"), Min = c(20L, 30L
 ), Median = c(59L, 55L), Max = c(70L, 65L)), .Names = c("Subject",
"Min", "Median", "Max"), class = "data.frame", row.names = c("1",
"2"))


text:
Q: NIntegrate with a function defined with conditions Good afternoon,
I am trying to integrate a function that is defined with a conditional. The simplified code is the following:
Area[J_, L_] := Block[ {int},
  If[L < 0,
   int = L*NIntegrate[Max[J x, x^2], {x, 0, 1}] ,
   int = L*NIntegrate[Min[J x, x^2], {x, 0, 1}]
   ];
  Return[Abs[int]]
  ]

Vol[J_] :=
 NIntegrate[Area[J, L], {L, -1, 1}, Method -> "QuasiMonteCarlo",
  AccuracyGoal -> 20, PrecisionGoal -> 20]

The Area[J,L] function is working properly, in fact i.e. Area[2,L] can be plotted for a range of L and it is a normal function. However, its integral does not work: Vol[2] does not give any result. I am assumig that I am not calling properly the NIntegrate command.
How can I define the NIntegrate so it works with conditional functions?
Any help is welcome. Thank you.

A: Clear["Global`*"]

Rather than using If, I recommend that you use Piecewise
area[J_, L_] =
 Piecewise[{{Abs[L*Integrate[Max[J x, x^2], {x, 0, 1}]], L < 0}},
  Abs[L*Integrate[Min[J x, x^2], {x, 0, 1}]]]

Vol[J_] = Integrate[area[J, L], {L, -1, 1}] // Simplify

Vol[-J] == Vol[J] // Simplify

(* True *)

Plotting,
Plot[Vol[J], {J, 0, 5}, AxesOrigin -> {0, 0}]

A: Fix area[] (_?NumericQ, single NIntegrate):
ClearAll[area, vol, vol2];

area[J_?NumericQ, L_?NumericQ] :=
  NIntegrate[
   Abs[L]*If[L < 0,
     Max[J x, x^2],
     Min[J x, x^2]
     ],
   {x, 0, 1}];

Iterated integral version, with singularity L == 0 (not as efficient as a multiple integral):
vol[J_?NumericQ] := NIntegrate[area[J, L], {L, -1, 0, 1}];

vol[2] // RepeatedTiming

(*  {0.18, 0.666667}  *)

Multiple integral version (requires some tricky code generation, but much faster):
vol2[J_?NumericQ] := Block[{L},
   Block[{NIntegrate = Hold},
     Block[{NumericQ = True &},
      area[J, L] /. DownValues[area]]
     ] /. Hold[f_, rest___] :> NIntegrate[f, {L, -1, 0, 1}, rest]
   ];

vol2[2] // RepeatedTiming

(*  {0.0028, 0.666667}  *)

Note: The single NIntegrate in area[] facilitates the code generation in vol2[]; otherwise, it is not strictly necessary.

A: Regarding my comment under OPs question here a solution using nested numerical integration
area[J_?NumberQ,L_?NumberQ]:=Block[{int},If[L<0,int=L*NIntegrate[Max[J x,x^2],{x,0,1}],int=L*NIntegrate[Min[J x,x^2],{x,0,1}]];Return[Abs[int]]]
volume[J_?NumberQ]:=NIntegrate[area[J,L],{L,-1,1}]
areaBobHanlon[J_,L_]=Piecewise[{{Abs[L*Integrate[Max[J x,x^2],{x,0,1}]],L<0}},Abs[L*Integrate[Min[J x,x^2],{x,0,1}]]];
volumeBobHanlon[J_]=Integrate[areaBobHanlon[J,L],{L,-1,1}]//Simplify;

Table[{J,volume[J]},{J,-5,5,1/2}];
Show[{Plot[volumeBobHanlon[J],{J,-5,5},Frame->True,GridLines->Automatic,FrameLabel->{"J","volume[J]"}],ListPlot[%]}]

for comparison I included the analytical solution presented by Bob Hanlon. The code above should produce this plot

EDIT: Regarding the extension to higher dimensions mentioned in the comments under this answer: yes it is possible to extend this code but the way the code is written makes it highly ineffective. I would strongly suggest using piecewise functions and either integrating analytically (as pointed out by Bob Hanlon) or numerically without nesting:
dArea2dx[J_,L1_,L2_,x_]:=Abs[Piecewise[{{L1*Max[J x,x^2],L1<0}},L1*Min[J x,x^2]]-Piecewise[{{L2*Max[J x^2,x],L2<0}},L2*Min[J x^2,x]]]
volume2[J_?NumberQ]:=NIntegrate[dAreadx[J,L1,L2,x],{x,0,1},{L1,-1,1},{L2,-1,1}]
volume2Analytical=Integrate[dAreadx[J,L1,L2,x],{x,0,1},{L1,-1,1},{L2,-1,1}]

Table[{J,volume2[J]},{J,-5,5,1/2}];
Show[{Plot[volume2Analytical,{J,-5,5},Frame->True,GridLines->Automatic,FrameLabel->{"J","volume2[J]"}],ListPlot[%]}]

which results (after a few seconds of computation time) in

Mathematica is quite good in integrating over Piecewise functions with simple values and seems to handle the Min and Max in this problem quite well. If high dimensional integration becomes necessary one should avoid unnecessary nesting of integrals or if this is for some reason unavoidable or desired (this problem does not call for it) one should decrease the PrecisionGoal and AccuracyGoal to speed up computation.


text:
Q: PHP, отсортировать массив с timestamp Имеется массив с timestamp-ми примерно с прошлого года (когда добавлялись пользователи). Надумала сделать статистику, но не пойму как можно день за днем отсортировать этот массив, чтобы вышло что-то типа
[
  '27.05.18' => 25,
  '28.05.18' => 5
]

Где 25 и 5 - соответственно количество пользователей за день. У меня же имеется просто список
 ["1597770786","1597771694","1597771715","1597776373","1597776819"],

A: Что-то мне подсказывает, что информация о зарегистрированных пользователях хранится вовсе не в текстовом файле. Скорее всего - в базе данных. Так почему бы не получить эти данные сразу запросом из БД? Например, если registered_at - поле типа TIMESTAMP, то запрос будет выглядеть как-то так:
SELECT
  DATE_FORMAT(registered_at, '%d.%m.%Y') AS registerDate,
  COUNT(*) AS usersCount
FROM users
GROUP BY DATE_FORMAT(registered_at, '%d.%m.%Y')
ORDER BY DATE_FORMAT(registered_at, '%d.%m.%Y');

Ну а если registered_at - это поле типа INTEGER, хранящее unix timestamp, то запрос будет имет примерно такой вид:
SELECT
  FROM_UNIXTIME(registered_at, '%d.%m.%Y') AS registerDate,
  COUNT(*) AS usersCount
FROM users
GROUP BY FROM_UNIXTIME(registered_at, '%d.%m.%Y')
ORDER BY FROM_UNIXTIME(registered_at, '%d.%m.%Y');

И выполнится быстрее, и возни меньше, и последующая обработка проще - данные уже отсортированы, сгруппированы и готовы к помещению в массив:
$result = [];
foreach ($pdo->query($sql) as $row) {
    $result[$row['registerDate']] = $row['usersCount'];
}

P.S. Варианты запроса представлены для MySQL.

A: Например так:
$arr =  ["1597770786","1597771694","1597771715","1564404622","1597776819"];

$result = [];
foreach($arr as $row){
    $date = date('d.m.Y', $row);
    isset($result[$date]) ? $result[$date]++ : $result[$date] = 1;
}

A: Предлагаю, для определения количества одинаковых значений в массиве, использовать ф-ю array_count_values().
Тогда задача сводится к преобразованию значений массива в строки, содержащих дату в формате "d.m.Y" и последующий подсчет, с помощью функции array_count_values(), кол-ва одинаковых значений:
<?php
$input = ["1597610786", "1597611786", "1597770786", "1597771694", "1597771715", "1597776373", "1597776819" ];

sort($input); // <--- если значения уже отсортированны - строчку можно удалить

$output = array_count_values(
    array_map(
        function ($itm) {
            return date('d.m.Y', $itm);
        },
        $input
    )
);

var_dump($output);

Вывод:
array(2) {
  '16.08.2020' =>
  int(2)
  '18.08.2020' =>
  int(5)
}


text:
Q: About atomicity guarantee in C On x86 machines, instructions like inc, addl are not atomic and under SMP environment it is not safe to use them without lock prefix. But under UP environment it is safe since inc, addl and other simple instructions won't be interrupted.
My problem is that, given a C-level statement like
x = x + 1;

Is there any guarantees that C compiler will always use UP-safe instructions like
incl %eax

but not those thread-unsafe instructions(like implementing the C statement in several instructions which may be interrupted by a context switch) even in a UP environment?

A: No.
You can use "volatile", which prevents the compiler from holding x in a temporary register, and for most targets this will actually have the intended effect. But it isn't guaranteed.
To be on the safe side you should either use some inline asm, or if you need to stay portable, encapsulate the increment with mutexes.

A: If you use GLib, they have macros for int and pointer atomic operations.
http://library.gnome.org/devel/glib/stable/glib-Atomic-Operations.html

A: There is absolutely no guarantee that "x - x + 1" will compile to interrupt-safe instructions on any platform, including x86. It may well be that it is safe for a specific compiler and specific processor architecture but it's not mandated in the standards at all and the standard is the only guarantee you get.
You can't consider anything to be safe based on what you think it will compile down to. Even if a specific compiler/architecture states that it is, relying on it is very bad since it reduces portability. Other compilers, architectures or even later versions on the same compiler and architecture can break your code quite easily.
It's quite feasible that x = x + 1 could compile to an arbitrary sequence such as:
load r0,[x]  ; load memory into reg 0
incr r0      ; increment reg 0
stor [x],r0  ; store reg 0 back to memory

on a CPU that has no memory-increment instructions. Or it may be smart and compile it into:
lock         ; disable task switching (interrupts)
load r0,[x]  ; load memory into reg 0
incr r0      ; increment reg 0
stor [x],r0  ; store reg 0 back to memory
unlock       ; enable task switching (interrupts)

where lock disables and unlock enables interrupts. But, even then, this may not be thread-safe in an architecture that has more than one of these CPUs sharing memory (the lock may only disable interrupts for one CPU), as you've already stated.
The language itself (or libraries for it, if it's not built into the language) will provide thread-safe constructs and you should use those rather than depend on your understanding (or possibly misunderstanding) of what machine code will be generated.
Things like Java synchronized and pthread_mutex_lock() (available to C under some OS') are what you want to look into.

A: In recent versions of GCC there are __sync_xxx intrinsics to do exactly what you want.
Instead of writing:
x += 1;
write this:
__sync_fetch_and_add(&x, 1);
And gcc will make sure this will be compiled into an atomic opcode. This is supported on most important archs now.
http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Atomic-Builtins.html
It stems originally from the recommendations from Intel for C on ia64, but now found it ways to gcc on a lot of other archs, too. So it's even a bit portable.

A:

Is there any guarantees that C compiler will always use UP-safe instructions

Not in the C standard. But your compiler/standard library may provide you with special types or certain guarantees.
This gcc doc may be along the lines of what you need.

A: I believe you need to resort to SMP targeted libraries or else roll your own inline assembler code.

A: A C compiler may implement a statement like x = x + 1 in several instructions.
You can use the register keyword to hint the compiler to use a register instead of memory, but the compiler is free to ignore it.
I suggest to use OS lock specific routines like the InterlockedIncrement Function on Windows.

A: Worrying about just x86 is horribly unportable coding anyway.  This is one of those seemingly small coding tasks that turns out to be a project in itself.  Find an existing library project that solves this sort of problem for a wide range of platforms, and use it.  GLib seems to be one, from what kaizer.se says.


text:
Q: How do I make a video cut-scene with XNA 4.0? I have transitions in my game and they work fine, but I want to now play a video cut-scene between certain transitions but can't find out how to do it.
EDIT Actually I just found out that XNA 4.0 has video playing capabilities now, they just have to be in .wmv format. Thanks for any help.

A: You might want to check out http://xnadsplayer.codeplex.com, saw that linked in a few different places.


text:
Q: How to make pre-lollipop style of Edit-Text in android all versions Hi i am trying to make rectangular Edit-text style like below image for this i used below code but its not showing Edit-text like my below image can some one help me please
rect_text_edit:-
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="10dp"
    android:shape="rectangle">
    <solid android:color="#FFFFFF" />
    <corners
        android:bottomLeftRadius="5dp"
        android:bottomRightRadius="5dp"
        android:topLeftRadius="5dp"
        android:topRightRadius="5dp"/>
</shape>

login.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="@dimen/layout_padding"
        android:orientation="vertical">

        <EditText
            android:id="@+id/searchBox"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/rect_text_edit"
            android:textColor="@color/black"
            android:textCursorDrawable="@null"
            android:singleLine="true"
            android:padding="10dp">

        </EditText>

    </LinearLayout>

</RelativeLayout>


text:
Q: Decreasing height of a menu I want to decrease the height of menu so I had height:30px; in #cssmenu but the text is not in the center of the menu.

#cssmenu {
  padding: 0;
  margin: 0;
  border: 0;
  background:#CDCDCD;
}

#cssmenu ul,
#cssmenu li {
  list-style: none;
  margin: 0;
  padding: 0;
}

#cssmenu ul {
  position: relative;
  z-index: 597;
}

#cssmenu ul li {
  float: left;
  min-height: 1px;
  vertical-align: middle;
}
#cssmenu ul li.hover,
#cssmenu ul li:hover {
  position: relative;
  z-index: 599;
  cursor: default;
}
#cssmenu ul ul {
  visibility: hidden;
  position: absolute;
  top: 100%;
  left: 0;
  z-index: 598;
  width: 100%;
}
#cssmenu ul ul li {
  float: none;
}
#cssmenu ul ul ul {
  top: 0;
  left: 190px;
  width: 190px;
}
#cssmenu ul li:hover > ul {
  visibility: visible;
}
#cssmenu ul ul {
  bottom: 0;
  left: 0;
}
#cssmenu ul ul {
  margin-top: 0;
}
#cssmenu ul ul li {
  font-weight: normal;
}
#cssmenu a {
  display: block;
  line-height: 1em;
  text-decoration: none;
  height:30px;
}
/* Custom CSS Styles */

#cssmenu > ul {
  *display: inline-block;
}
#cssmenu:after,
#cssmenu ul:after {
  content: '';
  display: block;
  clear: both;
}
#cssmenu ul {
  text-transform: uppercase;
}
#cssmenu ul ul {
  border-top: 3px solid #5f7a77;
  text-transform: none;
  min-width: 190px;
}
#cssmenu ul ul a {
  background: #759b98;
  color: #ffffff;
  border-bottom: 1px solid #3c4d60;
  border-top: 0 none;
  line-height: 100%;
  padding: 12px 12px;
  font-size: 12px;
}
#cssmenu ul ul ul {
  border-top: 0 none;
}
#cssmenu ul ul li {
  position: relative;
}

#cssmenu ul ul li:hover > a {
  background: #5f7a77;
  color: #ffffff;
}

#cssmenu ul ul li.has-sub > a:after {
   content: '+';
  position: absolute;
  top: 50%;
  right: 15px;
  margin-top: -8px;
}
#cssmenu ul li:hover > a,
#cssmenu ul li.active > a {
 background: #5f7a77;
 color: #ffffff;
}
#cssmenu ul li.has-sub > a:after {
   content: '+';
  margin-left: 5px;
}
#cssmenu ul li.last ul {
  left: auto;
  right: 0;
}
#cssmenu ul li.last ul ul {
  left: auto;
  right: 99.5%;
}
#cssmenu a {

  color: #3c4d60;
  padding: 0 15px;
}
#cssmenu > ul > li > a {
  line-height: 48px;
  font-size: 12px;
}

Home

Products

Product 1

Sub Product

Sub Product

Product 2

Sub Product

Sub Product

About

Contact

A: Change your line-height to 30px:
#cssmenu > ul > li > a {
  line-height: 30px;
}

A: The properties float:left and vertical-align doesn't work together. In order to get the vertical-alignment on items like this menu you can use line-height. I made this changes:
#cssmenu ul li.has-sub > a:after {
  content: '+';
  display:inline-block; /*Add to keep + sign aligned too*/
  margin-left: 5px;
}
#cssmenu > ul > li > a {
  /*line-height: 48px; Remove this line to keep the next value*/
  font-size: 12px;
}
/*Add all this next Selector CSS*/
#cssmenu ul li > a span {
  display:inline-block;
  vertical-align:middle;
  line-height:30px;
}

#cssmenu {
  padding: 0;
  margin: 0;
  border: 0;
  background:#CDCDCD;
}

#cssmenu ul,
#cssmenu li {
  list-style: none;
  margin: 0;
  padding: 0;
}

#cssmenu ul {
  position: relative;
  z-index: 597;
}

#cssmenu ul li {
  float: left;
  min-height: 1px;
}
#cssmenu ul li.hover,
#cssmenu ul li:hover {
  position: relative;
  z-index: 599;
  cursor: default;
}
#cssmenu ul ul {
  visibility: hidden;
  position: absolute;
  top: 100%;
  left: 0;
  z-index: 598;
  width: 100%;
}
#cssmenu ul ul li {
  float: none;
}
#cssmenu ul ul ul {
  top: 0;
  left: 190px;
  width: 190px;
}
#cssmenu ul li:hover > ul {
  visibility: visible;
}
#cssmenu ul ul {
  bottom: 0;
  left: 0;
}
#cssmenu ul ul {
  margin-top: 0;
}
#cssmenu ul ul li {
  font-weight: normal;
}
#cssmenu a {
  display: block;
  text-decoration: none;
  height:30px;
}
/* Custom CSS Styles */

#cssmenu > ul {
  *display: inline-block;
}
#cssmenu:after,
#cssmenu ul:after {
  content: '';
  display: block;
  clear: both;
}
#cssmenu ul {
  text-transform: uppercase;
}
#cssmenu ul ul {
  border-top: 3px solid #5f7a77;
  text-transform: none;
  min-width: 190px;
}
#cssmenu ul ul a {
  background: #759b98;
  color: #ffffff;
  border-bottom: 1px solid #3c4d60;
  border-top: 0 none;
  line-height: 100%;
  padding: 12px 12px;
  font-size: 12px;
}
#cssmenu ul ul ul {
  border-top: 0 none;
}
#cssmenu ul ul li {
  position: relative;
}

#cssmenu ul ul li:hover > a {
  background: #5f7a77;
  color: #ffffff;
}

#cssmenu ul ul li.has-sub > a:after {
   content: '+';
  position: absolute;
  top: 50%;
  right: 15px;
  margin-top: -8px;
}
#cssmenu ul li:hover > a,
#cssmenu ul li.active > a {
 background: #5f7a77;
 color: #ffffff;
}
#cssmenu ul li.has-sub > a:after {
  content: '+';
  display:inline-block;
  margin-left: 5px;
}
#cssmenu ul li.last ul {
  left: auto;
  right: 0;
}
#cssmenu ul li.last ul ul {
  left: auto;
  right: 99.5%;
}
#cssmenu a {

  color: #3c4d60;
  padding: 0 15px;
}
#cssmenu > ul > li > a {
  font-size: 12px;
}
#cssmenu ul li > a span {
  display:inline-block;
  vertical-align:middle;
  line-height:30px;
}

Home

Products

Product 1

Sub Product

Sub Product

Product 2

Sub Product

Sub Product

About

Contact


text:
Q: How to send one or the other attribute in the form I have a form for which I am using checkboxes (Not using radio buttons for my purpose). The problem I run into is when I submit a form, I get an error saying params is missing or value is empty:checkup. I am trying to use hidden filed but get the same error. HOw to have an option of sending only one if selected?
   def checkup_params
    params.require(:checkup).permit(:eye, :heart)
   end

my form:
<%= form_for(@checkup) do |f| %>
 <%= hidden_field_tag "checkup[eye]", nil %>
 <%= check_box_tag :eye, "eye" %>
 <%= hidden_field_tag "checkup[heart]", nil %>
 <%= check_box_tag :heart, "heart" %>
 <%= f.submit %>
<% end %>

A: I suggest reading this guide http://guides.rubyonrails.org/form_helpers.html#dealing-with-model-objects
Most specifically section 2.2. You really shouldn't be using tag helpers here.


text:
Q: HP ALM 11.52 - OTA API - Check In/Out test cases with VB script I am using OTA to upload test cases from excel to ALM.
I have used the excel add-in and have found it to be quite cumbersome for my project needs, so I am writing a custom script to accomplish the task.
Note: Version Control is ON.
I have version control on, therefore, I need to check out the created test case before I can add steps. Preferably, I'd like to be able to check in the test case again when I am complete. Is there a way to do this with the OTA api?
This is the script that I am using:
Sub UploadTC()

Dim QCConnection
Dim qcUserName, qcPassword, qcDomain, qcProj
Dim tsf, trmgr
Dim trfolder, trtest
Dim dsf, dstep, steplist
Dim TCR As Range
Dim cache As Range
Dim scount As Range
'Fields
Dim TCName As Range
Dim TCStep As Range
Dim TCDesc As Range
Dim TCExRe As Range
Dim TCComm As Range
Dim TCType As Range

'~~~These need to come from a user form. Temporary.
qcUserName = "ssoong01"
qcPassword = "*********"
qcDomain = "HUB"
qcProj = "*********"

Set QCConnection = CreateObject("TDApiOle80.TDConnection")
'MsgBox ("Connect to QC Server")

QCConnection.InitConnectionEx "http://hpalm-qc.*****.net:8080/qcbin/"
'MsgBox ("Connection Established.")

QCConnection.Login qcUserName, qcPassword
'MsgBox ("Login Authenticated.")

QCConnection.Connect qcDomain, qcProj
'MsgBox ("Connected to Project.")

Set tsf = QCConnection.TestFactory
Set trmgr = QCConnection.TreeManager

With ThisWorkbook.Sheets("Test Cases")

 'Create Project Folder
Set trfolder = trmgr.NodebyPath("Subject").AddNode(.Cells(3, 2))
trfolder.Post
'Loop through each row in sheet from A4
Set cache = ThisWorkbook.Sheets("Values").Range("$A$3")
For Each TCR In .Range(.Cells(4, 1), .Cells(.Cells(Rows.Count, 1).End(xlUp).Row, 1))
    Set TCName = .Range(TCR.Offset(0, 1).Address)
    Set TCType = .Range(TCR.Offset(0, 7).Address)

    'If Folder Then
        If TCType.Value = "Folder" Then
            Set trfolder = trmgr.NodebyPath("Subject" & TCR.Value).AddNode(TCName.Value)
            trfolder.Post
    'If Test Case Then
        ElseIf TCType.Value = "MANUAL" Then
            'If cached TC name = current row TC name then skip
            If TCName = cache.Value Then
            'Add Test Case
            ElseIf TCName <> cache.Value Then
                Set trfolder = trmgr.NodebyPath("Subject" & TCR.Value)
                Set trtest = trfolder.TestFactory.AddItem(TCName.Value)
                    ' set values
                    trtest.Field("TS_NAME") = TCName
                    trtest.Field("TS_RESPONSIBLE") = qcUserName ' Designer
                    trtest.Field("TS_TYPE") = "MANUAL"

                    trtest.Post

            'Steps
            Set dsf = trtest.DesignStepFactory
            Set steplist = dsf.Newlist("[empty]")

            ' loop through all the steps
            Set scount = .Range(TCName.Address)
            Do
                Set TCStep = .Range(scount.Offset(0, 1).Address)
                Set TCDesc = .Range(scount.Offset(0, 2).Address)
                Set TCExRe = .Range(scount.Offset(0, 3).Address)
                Set TCComm = .Range(scount.Offset(0, 4).Address)

                Set dstep = dsf.AddItem(Null)
                    dstep.Field("DS_STEP_NAME") = TCStep.Value
                    dstep.Field("DS_DESCRIPTION") = TCDesc.Value
                    dstep.Field("DS_EXPECTED") = TCExRe.Value
                    Set scount = .Range(scount.Offset(1).Address)
            Loop Until scount.Value <> scount.Offset(-1).Value

            dstep.Post

                'cache TC name
                cache.Value = TCName.Value
            End If
        Else:
            MsgBox ("Invalid type at cell: " & TCR.Address)
        End If

Next TCR

HP Application Lifecycle Management
Application Lifecycle Management Edition 11.52.514
OTA Client 11.52.514.0

A: Yes, you can perform both check-in and check-out operations using the OTA API. It is described in detail in the documentation, and there are also some sample scripts there that shows how it can be done. I assume that you know where to find the OTA API reference/documenation?
Here is a sample script from the documentation, which shows how to write a function that performs a check-out of a test:
Public Function CheckoutTest(tst As Test, comment$, _
    ByRef CanContinue As Boolean) As Object

    On Error GoTo checkout_err
    CanContinue = True

    Dim fVersionControl As VCS
    Set fVersionControl = tst.VCS

    If IsNull(fVersionControl) Then
        Set CheckoutTest = Null
        Exit Function
    End If

    Set CheckoutTest = fVersionControl
    fVersionControl.CheckOut -1, comment, False

Exit Function
checkout_err:
    CanContinue = False
    ErrHandler err, "CheckoutTest", "", FATAL_ERROR
End Function

A: I found the answers I was looking for in the OTA documentation. Definitely a resource I should utilise more often.


text:
Q: How do you calculate the change in temperature of an adiabatic system? I really don't even know how to start doing this problem.
I understand PV=nRT and I understand that if either T, V, or P is kept constant, then the other 2 change at the same rate, and I understand that if either T, V, or P is kept constant while the other two change, then the system experiences a change in heat. I also understand that the internal energy is kept constant and that internal energy = heat - work. However I do not know how to relate the change in temperature to a change in heat. Can somebody please walk me through this?
Here is a diagram to better visualize the problem.

My homework question asks to find the temperature at point c
I have already calculated that n=0.41 and that the pressure at point b is 2.01966 atm
You do not need to solve for c, just please tell me how.
Okay so I couldn't handle it anymore and I just looked at the answer which happened to be 810J. This make me even more confused. Where did the extra 110J of energy just appear from?

A: An ideal gas undergoing an adiabatic transformation is subjected to the law:
$$P\,V^{\gamma} = \operatorname{constant}$$
where $\gamma$ is a nice fraction that depends on the number of atoms in the gas molecule. For a monatomic gas (like helium) $\gamma = 5/3$, for a diatomic gas (like hydrogen, oxygen, nitrogen...) and linear molecules (like carbon dioxide) $\gamma = 7/5$, in all the other cases is $4/3$ (but then the ideal gas hypothesis becomes weak).
This equation will allow you to find out $P_c$ starting from the point $a$. Then you can use the equation of status, which of course is still valid, to work out also $T_c$.

A: As long as you are familiar with the equation $W=-\int P\ dV$, this should be pretty straightforward. If you aren't, there should be a derivation for this formula in your text.
The ideal gas law states:
$$
PV=nRT \rightarrow P=\frac{nRT}{V}
$$
We know that $n$ and $R$ are constant and that the temperature, $T$, is constant because the process between $a$ and $b$ is isothermal. Now that we have the pressure as a function of volume, it's pretty straightforward to use this in conjunction with the above work equation and integrate from the initial volume to the final volume to find the work done between states $a$ and $b$.
It seems like you're aware of how to continue the problem after this point.


text:
Q: Cisco Extended ACL on 2811 Not Working Properly I am almost positive this is an issue of missing a key component or not declaring/applying the ACL properly, but I am unable to figure out the fix on my own. What I am trying to do is only allow PC2 to send any traffic to PC3 and PC1. Essentially PC4 should be inaccessible to PC2.
Since I am unable to post images yet, I will try to explain the topology which is very simple. PC1 and PC2 are behind SWITCH1 and SWITCH1 is connected to ROUTER0 on port f0/1. On the left side PC3 and PC4 are behind SWITCH2 and SWITCH2 is connected to ROUTER0 on port f0/0. The IPs are as follows:

*

*PC1 11.0.0.2/8  & Connected to f0/1 on SWITCH1

*PC2 11.0.0.3/8  & Connected to f0/2 on SWITCH1

*PC3 10.0.0.2/8  & Connected to f0/1 on SWITCH2

*PC4 10.0.0.3/8  & Connected to f0/2 on SWITCH2

*ROUTER0 f0/0 10.0.0.1/8  & Connects to f0/24 on SWITCH2

*ROUTER0 f0/1 10.0.0.2/8  & Connects to f0/24 on SWITCH1

The ACL as it exists now is as follows:
ip access-list extended NSL1
 permit ip host 11.0.0.3 host 10.0.0.2

The problem is that devices on the left side of the topology (PC1 & 2) can no longer ping 11.0.0.1 or 10.0.0.1 when they were able to prior to implementing the ACL. It gives the "Destination host unreachable." error. PC1 also cannot ping anything on or to the right of the router, but I know that is because I have not put a permit statement in for it yet. Any help would be greatly appreciated. I would think it should be a simple fix, but I don't know since I don't have much experience with Cisco IOS.
Below is the full running-config of ROUTER0.
Router>
Router>en
Router#sh run
Building configuration...

Current configuration : 579 bytes
!
version 12.4
no service timestamps log datetime msec
no service timestamps debug datetime msec
no service password-encryption
!
hostname Router
!
!
!
!
!
!
!
!
!
!
!
!
!
!
spanning-tree mode pvst
!
!
!
!
interface FastEthernet0/0
  ip address 10.0.0.1 255.0.0.0
  duplex auto
  speed auto
!
interface FastEthernet0/1
  ip address 11.0.0.1 255.0.0.0
  ip access-group NSL1 in
  duplex auto
  speed auto
!
interface Vlan1
  no ip address
  shutdown
!
ip classless
!
!
ip access-list extended NSL1
 permit ip host 11.0.0.3 host 10.0.0.2
!
!
!
!
!
line con 0
 line vty 0 4
 login
!
!
!
end

A: Your access list is specifying 11.0.0.3 as the source and 10.0.0.2 as the destination - other traffic ingressing on the f0/1 interface will not be allowed (and I think it's a little strange that they're sending ICMP Unreachables instead of just dropping the packet, but there you have it).
If you want to allow pings to the router's IPs, you'll also need to put those in the ACL:
ip access-list extended NSL1
 permit ip host 11.0.0.3 host 10.0.0.2
 ! let it communicate with the other interface's routed IP:
 permit ip host 11.0.0.3 host 10.0.0.1
 ! let's just allow it to hit anything else in its subnet; might as well, right?
 permit ip host 11.0.0.3 11.0.0.0 0.255.255.255

Note that only 11.0.0.3 will be able to ping now with this ACL; you'd need to allow 11.0.0.2 explicitly as well.


text:
Q: How to use literal expressions under templates in locomotivejs? I have the following template:
<!DOCTYPE HTML>

<link href="css/style.css" rel="stylesheet"/>

Like in smarty, from php, I want to use {literal} declarations in the template, under the script session.
How to do this in locomotivejs views?

A: As far as I understand {literal}/{/literal}, everything between those tags isn't interpreted. EJS templates don't have something similar, although there are ways of circumventing that.
One way is to configure EJS to use different open/close tags, described here.
Another way is to use a different templating engine altogether, which isn't too difficult since LocomotiveJS isn't hardcoded to using EJS templates. I like the Swig templating engine myself, which has the {% raw %} tag that seems to do the same as {literal}.


text:
Q: Is there way to wait for multiple synchronization objects in Delphi for mobile platforms? Delphi has THandleObject.WaitForMultiple function, but it is available at Windows platform only. How to wait for multiple synchronization objects (in my case i need to wait for semaphore&event) for mobile platforms?
Is it possible?
I can use kind of workaround if will wait them in cycle with timeout, but it doesn't seem to be a good solution.


text:
Q: Checked list item display only one value I filled the list with some string values..Then after on item click...I'm able to see the Toast message for all checked items...Well the issue is that I want to move the indexes/string/position to a string and display it on next tab...But on next tab it gives me the item which I checked first...
protected void onListItemClick(ListView l, View v, int position, long id) {
        //final ViewHolder viewHolder = new ViewHolder();
        SparseBooleanArray sp=getListView().getCheckedItemPositions();

        String str="";
        for(int i=0;i<sp.size();i++)
        {
            str+=items[sp.keyAt(i)]+",";
        }
        Toast.makeText(this, ""+str, Toast.LENGTH_SHORT).show();

        Product.pro_selected= l.getItemAtPosition(position).toString();;

I use the following to display all selected item..
txtPro=(TextView)findViewById(R.id.select_pro_name);
                txtPro.setText(Product.pro_selected);

A: protected void onListItemClick(ListView l, View v, int position, long id) {

    ArrayList<String> itemSelected = new  ArrayList<String>();
    itemSelected.add(presidents[position]);
 }

This code is placed from you navigate to next activity/Screen
    Intent i = new Intent(getApplicationContext(),Second.class);
    i.putStringArrayListExtra("SelectedItems", itemSelected);
    startActivity(i);

in Second Activity get the value of intent and use it.
Intent intent = getIntent();
ArrayList<String> items = new ArrayList<String>();
items = intent.getStringArrayListExtra("SelectedItems");

This will shows you all selected items.
for (int i = 0; i < items.size(); i++) {

Toast.makeText(getApplicationContext(), String.valueOf(items.get(i)), Toast.LENGTH_SHORT).show();
}

To display them in a List extends ListActivity
ListView listView = getListView();
listView.setChoiceMode(listView.CHOICE_MODE_NONE);

setListAdapter(new ArrayAdapter<String>
                (this,android.R.layout.simple_list_item_1,items));

To display Selected items
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        // TODO Auto-generated method stub
        Toast.makeText(getApplicationContext(), items[position], Toast.LENGTH_SHORT).show();
        super.onListItemClick(l, v, position, id);
    }


text:
Q: NoMethodError for defined scope in ActionView In my Template model I have
# models/template.rb
class Template < ActiveRecord::Base
  scope :recent, -> { order('created_at DESC') }
end

I try to make the following call:
# views/template/_template_sidebar.haml
- Template.recent.each do |template|
  %h2= template.title

I get the following error:
undefined method `recent' for ActionView::Template:Class

Is it possible to do what I'm trying to do? Is there a better if I use an instance variable instead? I'm avoiding the latter suggestion because I feel it creates an additional layer of complexity.

A: It turns out that Template should be a reserved class name due to this previously existing rails class. As a workaround I used the following call instead.
 - ::Template.recent.each do |template|
  %h1= template.title

Thanks to @D-side for the suggestion in the comments.

A: Well... the situation got a bit sticky.
You have your own Template class. But there is also ActionView::Template.
A view is executed in context of an ActionView instance (you can verify that by doing binding.pry inside it and looking at self). When you use a bare Template there Ruby looks it up in closest scopes, going up from the one you're in (ActionView).
Hence, it looks up ActionView first, resulting in ActionView::Template popping up instead. Oops.
To resolve this, assuming you don't want to do anything with your current class, is to explicitly specify "Template from the root scope", ::Template that is.


text:
Q: How to implement custom user-based authorization in jax-rs rest service? This tutorial explains how to do role authorization using jax-rs.
I am looking for user level authorization.  For example, for certain methods, such as removing or editing or accessing personal user information, only the user that is owner of that information should be able to access those resources.  What would be the best way to implement this?

A: Use XACML and a JAX-RS policy enforcement point in front of your JAX-RS service.
XACML is the eXtensible Access Control Markup Language. What XACML helps you achieve is:

*

*attribute-based access control where an attribute is just a key-value pair. An attribute could be the user id, the resource owner, the time of the day, the action...

*externalized authorization: decouple the business logic inside your JAX-RS service from the authorization logic now expressed in a central point called the policy decision point (PDP)

*policy-based: the authorization logic is expressed inside the PDP as policies that use the attributes previously defined. For instance:

*

*A user with the role==editor can do the action==edit on a document if the document.owner==user.id
You can read more on XACML and ABAC here:

*

*ABAC: NIST project page.

*XACML introduction & architecture.

You will need to deploy an interceptor (policy enforcement point) in front of the JAX-RS service you want to protect.


text:
Q: How to get application instance from anywhere in Vaadin? I do not create Application object explicitly and suppose Vaadin does it silently.
How can I get a reference to it?

A: In Vaadin 7 is called UI.
Accessible with:
UI.getCurrent();

And for your own methods in extended UI like:
((MyUI) UI.getCurrent()).getMyData();

More info in Vaadin book.


text:
Q: how to reattach singleton Spring beans upon deserialization I want to reinject singleton-scoped dependencies into prototype Spring beans, after they have been deserialized.
Say I've got a Process bean, which depends on a Repository bean.  The Repository bean is a scoped as a singleton, but the Process bean is prototype-scoped.  Periodically I serialize the Process, and then later deserialize it.
class Process {
   private Repository repository;
   // getters, setters, etc.
}

I don't want to serialize and deserialize the Repository.  Nor do I want to put "transient" on the member variable that holds a reference to it in Process, nor a reference to some kind of proxy, or anything other than a plain old member variable declared as a Repository.
What I think I want is for the Process to have its dependency filled with a serializable proxy that points (with a transient reference) to the Repository, and, upon deserialization, can find the Repository again.  How could I customize Spring to do that?
I figure I could use a proxy to hold the dependency references, much like .  I wish I could use that exact technique.  But the proxy I've seen Spring generate isn't serializable, and the docs say that if I use it with a singleton bean, I'll get an exception.
I could use a custom scope, perhaps, on the singleton beans, that would always supply a proxy when asked for a custom-scoped bean.  Is that a good idea?  Other ideas?

A: I used this instead, without any proxy:
public class Process implements HttpSessionActivationListener {
    ...
    @Override
    public void sessionDidActivate(HttpSessionEvent e) {
        ServletContext sc = e.getSession().getServletContext();
        WebApplicationContext newContext = WebApplicationContextUtils
            .getRequiredWebApplicationContext(sc);
        newContext.getAutowireCapableBeanFactory().configureBean(this, beanName);
    }
}

The example is for a web environment when the application server serializes the session, but it should work for any ApplicationContext.

A: Spring provides a solution for this problem.
Take a look at the spring documentation http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-atconfigurable.

7.8.1 Using AspectJ to dependency inject domain objects with Spring
...
The support is intended to be used for objects created outside
of the control of any container. Domain objects often fall into
this category because they are often created programmatically
using the new operator, or by an ORM tool as a result of a database query.

The trick is to use load time weaving. Just start the jvm with -javaagent:path/to/org.springframework.instrument-{version}.jar. This agent will recognize every object that is instantiated and if it is annotated with @Configurable it will configure (inject @Autowired or @Resource dependencies) that object.
Just change the Process class to
@Configurable
class Process {

   @Autowired
   private transient Repository repository;
   // getters, setters, etc.
}

Whenever you create a new instance
Process process = new Process();

spring will automatically inject the dependencies.
This also works if the Process object is deserialized.

A: I think the idea of serializing a bean and then forcing a reinjection of dependencies is not the best architecture.
How about having some sort of ProcessWrapper bean instead which could be a singleton.  It would be injected with the Repository and either manages the deserialization of the Process or has a setter for it.  When a new Process is set in the wrapper, it would call setRepository() on the Process.  The beans that use the Process could either be set with the new one by the wrapper or call the ProcessWrapper which would delegate to the Process.
class ProcessWrapper {
   private Repository repository;
   private Process process;
   // getters, setters, etc.

   public void do() {
      process.do();
   }

   public void setProcess(Process process) {
      this.process = process;
      this.process.setRepository(repository);
   }
}

A: How about added using aspects to add an injection step when you deserialize the object?
You would need AspectJ or similar for this. It would work very similarly to the @Configurable function in Spring.
e.g. add some advice around the a "private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException" method
This article may also help: http://java.sun.com/developer/technicalArticles/Programming/serialization/

A: Answering my own question: how I've solved the problem so far is to create a base class which serializes and deserializes using a cheap little proxy.  The proxy contains only the name of the bean.
You'll note that it uses a global to access the Spring context; a more elegant solution might store the context in a thread-local variable, something like that.
public abstract class CheaplySerializableBase
   implements Serializable, BeanNameAware {

    private String name;

    private static class SerializationProxy implements Serializable {

        private final String name;

        public SerializationProxy(CheaplySerializableBase target) {
            this.name = target.name;
        }

        Object readResolve() throws ObjectStreamException {
            return ContextLoader.globalEvilSpringContext.getBean(name);
        }

    }

    @Override
    public void setBeanName(String name) {
        this.name = name;
    }

    protected Object writeReplace() throws ObjectStreamException {
        if (name != null) {
            return new SerializationProxy(this);
        }
        return this;
    }
}

The resulting serialized object is 150 bytes or so (if I remember correctly).

A: The method applicationContext.getAutowireCapableBeanFactory().autowireBean(detachedBean); can be used to reconfigure a Spring-managed bean that was serialized and then de-serialized (whose @Autowired fields become null). See example below. The serialization details are omitted for simplicity.
public class DefaultFooService implements FooService {

    @Autowired
    private ApplicationContext ctx;

    @Override
    public SerializableBean bar() {
        SerializableBean detachedBean = performAction();
        ctx.getAutowireCapableBeanFactory().autowireBean(detachedBean);
        return detachedBean;
    }

    private SerializableBean performAction() {
        SerializableBean outcome = ... // Obtains a deserialized instance, whose @Autowired fields are detached.
        return outcome;
    }

}

public class SerializableBean {

    @Autowired
    private transient BarService barService;

    private int value;

    public void doSomething() {
        barService.doBar(value);
    }

}


text:
Q: How to use fzf to search for directories only? Here is a use case: I use fzf to search for a list of directories, which then used with the cd command:
cd $(fzf)

However, the fzf command only displays files, not directories. Is there a way to instruct fzf to select only directories?

A: Per my comment, you can generate a list of directories using find:
cd $(find . -type d -print | fzf)

You can adjust the find command to limit the depth of directories, or to only match directories with specific names, etc.
Generally, you're expected to use fzf as a filter, taking input from some external command.


text:
Q: Automatically Assign Values To $fillable attribute (Laravel 4) I'm trying to Sync data from a Localhost database to a Live one using Laravel 4. Everything works fine except for a table where columns' are dynamic. So in my Model I did something like:
<?php
class myModel extends \Eloquent {
    protected $fillable = [];
    protected $connection = 'live';
    protected $table = "myLiveTable";

    public function __construct()
    {
        $this->setFillable();
    }
    public function setFillable()
    {
        $fields = someSQLHandler::getColumns('myLocalTable');

        $this->fillable = $fields;
    }
}

in order to prevent typing the fields in $fillable manually as it is impossible!
Is there any way to make it automatically assigned or at least prevent the Mass Assignment error even if I know it's a bad practice?
Thanks!

A: How about using a black-list instead of a white-list:
protected $guarded = array('id', 'random_column');

And remove the $fillable completely.


text:
Q: Где лучше возвращать ошибку 404 в yii2 В приложении в контроллере user есть несколько экшнов, каждый из которых получает из запроса параметр user_id и по нему ищет пользователя в бд. Отсюда возникаем необходимость проверять существует ли пользователь с указанным id и если такого нет то возвращать сообщение об ошибке
Например так:
$user_id = $_GET['id'];

if (User::findIdentity($user_id)==null)
        throw new HttpException(404 ,'User not found');

Где лучше будет вставить код с проверкой чтобы избежать повторения одного и того же кода во всех экшнах?

A: В контроллере можно создать метод который будет возвращать пользователя в противном случаи кидать Exception
public function actionIndex() {
    $user = $this->findUser($_GET['id']);
}

public function findUser(id) {
    $user = User::findIdentity($id);
    if (null != $user) {
        throw new HttpException(404 ,'User not found');
    }
    return $user
}

A: Простой вариант - базовый контроллер (от которого потом отнаследуете все остальные) в котором необходимо переопределить метод beforeAction. В нем вы будете проверять ваше условие и выбрасывать ошибку. Это будет работать, но будет несколько неправильно идеологически. В вашем случае, насколько я понимаю, вы проверяете аутентификацию пользователя - можно создать базовый контроллер, с поведением authenticator (подробнее здесь http://www.yiiframework.com/doc-2.0/guide-rest-authentication.html), и значением
[
    'class' => CompositeAuth::className(),
    'authMethods' => [
        [
            'class' => UserIDAuth::className(),
        ],
    ],
]

где UserIDAuth - это потомок класса AuthMethod реализующий метод authenticate в котором вы осуществите свою проверку и вернете либо аутентифицированного пользователя либо null, если он не найден. Если пользователь не найден - то будет выброшена ошибка. Если найден - то его пропустит дальше, при этом впоследствии можно обращаться к модели аутентифицированного пользователя через Yii::$app->getUser(). Можно переопределить выбрасываемую ошибку на 404. Можно оставить как есть - 403 что возможно будет правильнее для вашего случая. Управлять применением аутентификатора к определенным actionам можно так же через поведение authenticator - поля optional, only, except.
Помимо этого можно использовать поведение access со значением
[
    'class' => AccessFilter::className(),
]

в котором фильтром будет выступать реализованный вами класс AccessFilter наследованный от ActionFilter с переопределенным методом beforeAction в котором вы осуществите вашу проверку и вернете булево значение пропускать пользователя дальше или нет.
P.S - если у вас user_id - это действительно значение передаваемое в get параметрах, по которому вы проверяете аутентификацию - хотелось бы предостеречь вас от такой реализации т.к это очень небезопасно - возможно стоит посмотреть в сторону Oauth или хотя бы Basic авторизации поверх https


text:
Q: iOS - Parse: findObjectsInBackgroundWithBlock with completion I'm fetching data using findObjectsInBackgroundWithBlock but I have to use the data when all of it is gathered. I don't know how to implement a callback or anything which would alert me once all the data is retrieved and ready for me to use. Is there any way to get alerted?
Code:
[query findObjectsInBackgroundWithBlock:^(NSArray* array, NSError* error)
{
    if(!error)
    {
        if([array count] > 0)
        {
            PFObject* relationship = [array objectAtIndex:0];

            if([relationship.objectId length] > 0)
            {
                if([[relationship objectForKey:@"initiatedBy"] isEqualToString:parseID]) // relationship initiated by current user -youLike
                {
                    [youLike addObject:relationship];
                    NSLog(@"youLike added");
                }
                else
                {
                    [likeYou addObject:relationship];
                    NSLog(@"likeYou added");
                }
            }
            else NSLog(@"Custom error when cycling through user relationships: objectId is nil");
            }
        else
        {
            NSLog(@"Custom error when cycling through user relationships: Relationship at index %d could not be found in database", i);
        }
    }
    else
    {
        NSLog(@"Error when cycling through user relationships: %@", error);
    }
}

A: You need to use Blocks
Declare the Block (Here you choose your block types)
typedef void (^YourBlock)(NSArray *array, NSError *error);

Add the block and the findObjectsInBackgroundWithBlock in a method.
- (void) yourMethod:(YourBlock)block {
    [query findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        //Do your things here if you want change something.
        //For instance: convert types, convert errors.
        block(array, error); //Is called when every thing is retrieve.
    }
}

Call your method in the Application
SomeClass *someClass = [SomeClass alloc]init];
[[object getScoresFromParse:^(NSArray *array, NSError *error) {
    //Everything complete here.
}];

A: You can use blocks.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{

    [query findObjectsInBackgroundWithBlock:^(NSArray* array, NSError* error)
    {
        if(!error)
        {

            if([array count] > 0)
            {
                PFObject* relationship = [array objectAtIndex:0];

                if([relationship.objectId length] > 0)
                {

                    // It will be called when Parse finishes.
                    dispatch_async(dispatch_get_main_queue(), ^{

                        if([[relationship objectForKey:@"initiatedBy"] isEqualToString:parseID]) // relationship initiated by current user -youLike
                        {
                            [youLike addObject:relationship];
                            NSLog(@"youLike added");
                        }
                        else
                        {
                            [likeYou addObject:relationship];
                            NSLog(@"likeYou added");
                        }

                        // [...yourcode...]

                    });

                }
                else {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        NSLog(@"Custom error when cycling through user relationships: objectId is nil");
                    });
                }

            }

        }

    }];

}];


text:
Q: How do you troubleshot google analytics code? Can anyone share best practices for troubleshooting google anlytics code?
Has anyone built a debugging tool?  Does google have a linter hidden somewhere? Does anybody have a good triage logic diagram?
I'll periodically set up different parts of GA and it seems like every time I do it takes 4 or 5 days to get it working.
The workflow looks like this:
Read the docs on the feature (e.g. events, custom variables).
Implement what appears to be the correct code based on the docs.
Wait a day.
See no data.
Google every version of the problem I can imagine.  Find what may be a solution.
Change my code.
Wait a day.
See no data.
Loop:
    Randomly move elements of the tracking code around.
    Wait a day.
    If other parts break, tell ceo, get yelled at, revert changes.
    If data appears, break.
Pray it continues to work/I never have to change the tracking code again.

For obvious reasons, I'm not satisfied with this workflow and hoping someone has figured out something I haven't.

A: To begin with, this answer isn't at odds with any portion of either of the two answers before mine--i.e. you could certainly implement them all without conflict.
My answer just reflects my own priority, which is that the latency issue. Latency makes debugging far more difficult than it should be. Ten minutes of latency while waiting for the compiler to finish is irritating, four hours (minimum GA latency) is painful.
So for me, the first step in building a GA de-bugging framework was to somehow get the GA results in real-time--in other words, if i changed a regular expression filter, i needed to catch the traffic processed by that filter. So removing the 4-24 hour latency in getting results from the GA server was critical.
The easiest way i have found so far to do this is to modify the GA tracking code on each page of your Site so that it sends a copy of each GIF Request to your own server.
To do this, immediately before the call to trackPageview(), add this line:
pageTracker._setLocalRemoteServerMode();

This will send the entire request header to your server access log, which you can parse in real time. (Specifically, your server writes to the access log one line at a time--one line corresponds to one request. All of the GA data is packaged and set as a request header, so there's perfect coincidence between the two.

A: yahelc answer is great, but I'd like to add my 2c here.
Get yourself a nice sniffer to see the hits flowing.
Nice options:

*

*Wasp

*Charles

*HTTPFox

*Fiddler
Then implement your changes on QA.
Test this new setup on QA. Things you should keep an eye on.

*

*Always make sure that the basic pageview fires. It should have at least an utmp value and no utmt set.

*Make sure the visitor Id doesn't get overwritten. This is the second number on the __utma cookie. This number should be your userid, if it changes then things are broken.

*Make sure your pageviews contain the page and session variables you set. If you set any. They are coded into the param utme.

*Make sure that any Visitor custom var is fired before your basic pageview. utmt=custom variable

*Make sure the source data is not overwritten (Campaign/medium/source/content/keyword) - These are set on the __utmz cookie. If it gets overwritten by direct or a referral of you own site there's something wrong.

*If you miss any event it may be due a reqired field missing or the last value being a float or string. The value of an event must be an integer.

*If you're using the ecomerce double check all your parameters. Make sure that you're firing everything as strings here and that unused parametrs are empty strings.

*triple check your account number. UA-XXXXX-X.

*If your doing something with custom JS make sure to test on all browsers, and try to get at least the basic tracking on a safe zone where you are sure things won't break.

*Send debug info about javascript code that might break GA to GA. Check this.

A: Everything I do, debugging GA code, stops and starts with the Google Analytics Debugger Chrome Extension. It prints out to the console a summary of the data it has sent to Google Analytics which, for all purposes except testing profile filters, is all you need. It'll eliminate the "wait a day" step.
If you're not a fan of Google Chrome, you can inspect the HTTP requests yourself to see how the data is parsing. You can use this guide to figure out what each paramater in the URL represents.
In terms of ensuring the features I've installed or the code itself is working, I'll open a fresh browser (cleared of cookies), and navigate to the site I'm testing via Google search. I'll proceed to navigate to all of the pertinent pages, and trigger all the pertinent events, all the while ensuring that the requests are being sent to Google, and that the session isn't broken at any point (by either keeping an eye on the Session Count, or ensuring that the traffic source doesn't change from organic/google to direct or a self-referral.
Screenshot:


text:
Q: Setting a pointer to Parse with Swift I have a user search for a school and then tap on the one they want. In cellForRowAtIndexPath I query for the school that was selected and get its objectId. I then set the objectId to the pointer, "school_name" in within PFUser.currentUser. The pointer goes to the "Schools" class where all of the schools are listed. I am getting an error that says, "invalid type for key school_name, expected *Schools, but got string (Code: 111, Version: 1.12.0)". I can't seem to get around it as the objectId is a string. I can even print the objectId getting the right one.
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{

    let spinningActivity = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
    spinningActivity.labelText = "Just a Moment"
    spinningActivity.detailsLabelText = "Adding Details"

    let schoolIndexPath = tableView.indexPathForSelectedRow!
    let selectedCell = tableView.cellForRowAtIndexPath(schoolIndexPath)! as UITableViewCell
    let school : String = String(selectedCell.textLabel!.text!)

    let schoolObjectIdQuery = PFQuery(className:"Schools")
    schoolObjectIdQuery.whereKey("school_name", matchesRegex: school)

    let query = PFQuery.orQueryWithSubqueries([schoolObjectIdQuery])

    if reachabilityStatus == kNOTREACHABLE {

        spinningActivity.hide(true)

        self.displayAlert("No Internet Connection", message: "Please connect to the internet before continuing.")

    } else {

        query.findObjectsInBackgroundWithBlock {
            (results: [PFObject]?, error: NSError?) -> Void in

            if error != nil {

                self.displayAlert("Error", message: error!.localizedDescription)

            }

            if let objects = results {

                self.searchResults.removeAll(keepCapacity: false)

                for object in objects {

                    let schoolObjectId = object.objectId!

                    let addDetails : PFUser = PFUser.currentUser()!

//                        let schoolObjectIdFormatted = PFObject(withoutDataWithClassName: "school_name", objectId: schoolObjectId)

                    addDetails.setObject(schoolObjectId, forKey: "school_name")

                    print(school)
                    print(schoolObjectId)

                    addDetails.saveInBackgroundWithBlock({ (success:Bool, error:NSError?) -> Void in

                        if error != nil {

                            spinningActivity.hide(true)

                            self.displayAlert("Error", message: error!.localizedDescription)

                        }

                        if success {

                            spinningActivity.hide(true)

                            self.dismissViewControllerAnimated(true, completion: nil)

                            print("Success")

                        }

                    })

                }

            }
        }
    }

}

A: Because you're trying to use a pointer... Not a string. Instead of saving the objectId you need to be saving the entire school object.

A: I think there is much more wrong with your code. Why do you have in your query.findObjectsInBackgroundWithBlock a saveInBackGround for each downloaded object.
If you want to store pointer, the syntax is this way
addDetails["school_id"] = PFObject(withoutDataWithClassName: "School", objectId: "\(schoolObjectId)")

school_id is a column name in Parse DB that is a type Pointer to the class School


text:
Q: How can torch.cat only have one tensor? I think there is an error in line 53 of the following code:
CycleGan, Buffer for Images
It says:
return_images = torch.cat(return_images, 0)  # collect all the images and return

What do you think, what should it read correctly? After having gone throught the code, I am unfortunately not sure what this specific line is supposed to do, but I think I understand the rest until line 52.

A: torch.cat's first argument is expected to be a sequence of tensors rather than a single tensor. So you pass in like:
torch.cat([tensor_1, tensor_2, tensor_3])       # the right way

instead of
torch.cat(tensor_1, tensor_2, tensor_3)         # not the right way

In the code you linked, they are forming a list called return_images which contains many tensors in it.
np.concatenate has the same behaviour too and PyTorch designers probably mimicked the choice from there. ("cat" is short for "concatenate" which is hard to write!).


text:
Q: Python: save attachments from .msg files So I have a folder with a ton of .msg files. I want to be able to save one of the attachments. My idea was automating clicking the files, then somehow extracting the file with a certain file name but I have yet to find any solutions to this.
How do I go about doing this? Or a better way?
Thanks!
Update:
I've got an idea to use os.startfile to open the file I want it to open...
How do I not open it in another window? But act like it did? If that makes any sense :/

A: This should work:
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
msg = outlook.OpenSharedItem(filename)        #filename including path
att=msg.Attachments
for i in att:
    i.SaveAsFile(os.path.join(Pathname, i.FileName))#Saves the file with the attachment name

Since you say you have a folder, this will automate the whole folder:
import win32com.client
import os
files = [f for f in os.listdir('.') if os.path.isfile(f)]
for file in files:
    if file.endswith(".msg"):
        outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
        msg = outlook.OpenSharedItem(file)
        att=msg.Attachments
        for i in att:
            i.SaveAsFile(os.path.join(Pathname, i.FileName))#Saves the file with the attachment name

A: Adding to Harish answer because, for me, the method didn't work, as OpenSharedItem() requires an absolute path.
As such I recommend the following for an entire folder:
import win32com.client
import os
inputFolder = r'.' ## Change here the input folder
outputFolder = r'.' ## Change here the attachments output folder

for file in os.listdir(inputFolder):
    if file.endswith(".msg"):
        outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
        filePath = inputFolder  + '\\' + file
        msg = outlook.OpenSharedItem(filePath)
        att = msg.Attachments
        for i in att:
            i.SaveAsFile(os.path.join(outputFolder, i.FileName))#Saves the file with the attachment name

A: I'm not sure if that will solve your problem but Python comes with  email.parser. This will at least help you read the msg file (assuming it's in proper format)
import email
with open('/path/to/your/file.msg') as fl:
    msg = email.message_from_file(fl)

That will give you a Message object. You should be able to get the file using msg.walk() which will give you all the attached content.
for part in msg.walk():
    if part.get_content_type() == "image/png":
        with open('out.png', 'w') as fl:
            fl.write(part.get_payload(decode=True)))


text:
Q: Default missing Autolayout constraints when added programmatically I forgot to add an x-component to my autolayout, but I was still able to see the view. I was wondering how/if autolayout generates default constraints when used programatically because in IB, there would be errors. No errors are printed in the debug console for this either.
I notice that when I do not specify an x-component, the view will always be left anchored to its parent view. Is there documentation which states what the default values are when a constraint is missing?

import UIKit
import PlaygroundSupport
//
class MyViewController : UIViewController {

    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white
        self.view = view
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let outBox = UIView()
        outBox.backgroundColor = UIColor.blue
        view.addSubview(outBox)
        outBox.translatesAutoresizingMaskIntoConstraints = false
        outBox.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        outBox.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        outBox.widthAnchor.constraint(equalToConstant: 200).isActive = true
        outBox.heightAnchor.constraint(equalToConstant: 200).isActive = true

        let inBox = UIView(frame: CGRect(x: 100, y: 2000, width: 10, height: 10))
        inBox.backgroundColor = UIColor.red
        outBox.addSubview(inBox)
        inBox.translatesAutoresizingMaskIntoConstraints = false
        inBox.topAnchor.constraint(equalTo: outBox.topAnchor).isActive = true
        inBox.bottomAnchor.constraint(equalTo: outBox.bottomAnchor).isActive = true
        inBox.widthAnchor.constraint(equalToConstant: 25).isActive = true
        // NO x-constraint component.. Should raise missing constraints error.
    }
}

PlaygroundPage.current.liveView = MyViewController()

A: The key isn't in setting frame here
let inBox = UIView(frame: CGRect(x: 100, y: 2000, width: 10, height: 10))

but it's here
inBox.translatesAutoresizingMaskIntoConstraints = false

that line ignores the internal conversion of frame to constraints and defaults them to zero based , insuffieicent constraints don't mean you can't see the view , for example you can do the same in IB and still see the view with red border and after run also but it doesn't mean it's properly set , and this as finally constraints will be converted to frame so it's a coincidence regarding zero-based


text:
Q: How do I find the last character of an array name in JavaScript? So if I've got a few arrays, let's call them person1, person2, person3 and person4 and I've got a function that has an argument between 1 and 4, how can I select that specific array?
For example:
var person1 = ["Steve", "McStevey"];
var person2 = ["Mike", "McMikey"];
var person3 = ["Dave", "McDavey"];
var person4 = ["Joe", "McJoey"];

And if I run the function
getPerson(3);

and pass the argument to
function getPerson(x) {...}

the function uses to argument to determine that the array I'm looking for is person3.

A: Make an array of your person arrays:
var persons = [person1, person2, person3, person4];
persons[x] will then give you the right array. And as Redu mentioned, you can access person1 as persons[0].

A: You should better define a map by ID with the persons.
var persons = {
  "1": ["Steve", "McStevey"],
  "2": ["Mike", "McMikey"],
  "3": ["Dave", "McDavey"],
  "123": ["Joe", "McJoey"]
}

function getPersonById(id) {
  return persons[id]
}

A: Another option would be to put your arrays in a lookup object.

var object = {
  person1: ["Steve", "McStevey"],
  person2: ["Mike", "McMikey"],
  person3: ["Dave", "McDavey"],
  person4: ["Joe", "McJoey"],
};

function getPerson(x) {
  return object['person' + x];
}

console.log(getPerson(1));


text:
Q: How to manupulate {{#each something}} in the view ,where "something" is comming from database Actually I am new to meteor . I want to manupulate {{#each something}} in my view, without manipulating database. Is there something like i treat it like an array. actually  its returning the list of elements.
<select name="field">
  <option value="">Lists</option>
  {{#each something}}
    <option value="{{_id}}">{{name}}</option>
  {{/each}}
</select>

JUST I WANT TO SHOW ALL THE ELEMENT within "options" except the LAST element.
Any Help would be appreciated .

A: if you want to show everything in "something" except the last thing, you can use @index in Blaze to detect when you're at the end. i'm using the each/in construct because i think it's easier to read.
<select name="field">
    <option value="">Lists</option>
    {{#each thing in something}}
        {{#if showThing @index}}
            <option value="{{thing._id}}">{{thing.name}}</option>
        {{/if}}
    {{/each}}
</select>

for the JS, i'm making assumptions about how you get your data, but the helpers would look something like this:
Template.Foo.helpers({
    something() {
        return Somethings.find({});
    },

    showThing(index) {
        let somethingsCount = Somethings.find({}).count();

        return (index != (somethingsCount - 1));
    }
});


text:
Q: How to Loadtest ActiveMQ with NMS –Publisher and subscriber? How to Loadtest ActiveMQ with NMS –Publisher and subscriber?
in JMeter I Could JMS Subscriber and JMS publisher.
Is there any tool or plug in to test through JMeter .. ?
(Trying to publish and subscribe in .NetFrame work (C#)

A: Have you seen JMeter Performance Tests page at the ActiveMQ website? I believe it contains all the answers.

*

*Add ActiveMQ client jars to JMeter classpath

*Restart JMeter to pick the .jars up

*Add JMS Publisher and JMS Subscriber to the Test Plan and configure them according to your test scenario.

Check out Building a JMS Testing Plan - Apache JMeter article for more details if needed


text:
Q: APNs Key (.p8 file) for Development/Sandbox I'm trying to set up Apple Push Notifications (APNs) on my server, but I can't seem to figure out how to download a .p8 file that's for a development environment. It's easy enough to register and download a .p8 file, but there isn't an option to configure it for development/sandbox.

When using this key, I get a 400 -- BadDeviceToken response from the APN server, which I've been led to believe means it's an environment mismatch. I was able to find a few tutorials that led me to register a Certificate instead, but in those cases, I ended up with a .p12 file instead.

Any advice on this would be much appreciated. I'm running a Rails server, and using the Apnotic gem to manage APNs. I'm happy to update to include my code if someone thinks that might be the problem.

A: One p8 file should work for both sandbox and production builds


text:
Q: Is Design by Contract the same as using Interfaces to create a "contract"? Does an OOP design that uses a Design by Contract mean the designer is using interfaces to create a "contract."  The term "contract" is used quite often when discussing OOP interfaces, so I didn't know if these were talking about the same concept when using the word "Contract."
What I want to do in one of my designs is to force the class sending a message to do so based upon implementing an interface.  For example,
class MyClass
{
  IMyInterfact someKindOfThing;
  public MyClass(IMyInterface something)
  {
        this.someKindOfThing = something;
  }

}

A: Not quite.  Interfaces are rather limited in the amount and kind of contract information they can provide.
For example, the interface:
interface ISizeable
{
    public int Size;
}

tells you that the "contract" has a Size member, but doesn't tell you anything else about that value, like how big or small it is allowed to be.
Normally, size is not negative.  You could solve this problem by making it an unsigned int, but that only works for sizes, and doesn't constrain the positive value.  You can create a specific type that will only accept values within a specified constraint range, but now you're just pushing the problem somewhere else.
Microsoft Code Contracts takes a different approach:
Contract.Requires( x != null );
Contract.Ensures( this .result > 0 );

Code Contracts contains a static analyzer, so the compiler can actually identify conditions under which contracts will never be fulfilled.