text:
Q: Could not load file or assembly 'Microsoft.Bot.Builder, Version=3.4.0.0, The system cannot find the file specified.",  public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
        {
            if (activity.Type == ActivityTypes.Message)
            {
                await Conversation.SendAsync(activity, () => new DialogsHelper.EchoDialog());
            }
            else
            {
                this.HandleSystemMessage(activity);
            }

            var response = Request.CreateResponse(HttpStatusCode.OK);
            return response;

I am using visual studio 2015 and microsoft bot simulator.
This is response from bot simulator.
I tried to install
Install-Package Microsoft.Bot.Builder

I am getting this error :

Install-Package : Could not install package 'Microsoft.Bot.Builder
  3.4.0'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.5', but the package does not contain
  any assembly references or content files that are  compatible with
  that framework. For more information, contact the package author. At
  line:1 char:1
  + Install-Package Microsoft.Bot.Builder
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : NotSpecified: (:) [Install-Package], Exception
      + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand

when this line is commented,
await Conversation.SendAsync(activity, () => new DialogsHelper.EchoDialog());

simulators response is 200, that is OK.
in this dialogshelper namespace, i have this simple class :
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;

namespace MessengerBot.Helpers
{
    public class DialogsHelper
    {
        [Serializable]
        public class EchoDialog : IDialog<object>
        {
            public async Task StartAsync(IDialogContext context)
            {
                context.Wait(MessageReceivedAsync);
            }
            public async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> argument)
            {
                var message = await argument;
                await context.PostAsync("You said: " + message.Text);
                context.Wait(MessageReceivedAsync);
            }
        }

    }
}

The idea : I want to use Microsoft Bot Dialogs.
I am following this tutorial here.
How to solve this ?

A: Go the properties of your csproj and change the Target Framework of the project to .NET Framework 4.6


text:
Q: Retrieving data from mysql database after logging in I'm trying to create a profile page for users. I want to be able to display data from a mysql database after the user has logged in to the website.
The PHP I've used on the member's profile page to try and retrieve the data is as follows:
 $link = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE);

 if (mysqli_connect_error()) {

         die("Could not connect to database");

 }

$query = "SELECT * FROM user1 WHERE id ='$_SESSION['id']'";
    if ($result=mysqli_query($link, $query)) {

        $row = mysqli_fetch_array($result);

          echo "
Name: " .$row[name];
          echo "
Email: " .$row[email];
          echo "
".$row[band];
    }

If anyone has any ideas I'd be really grateful.

A: update your query to be:
$query = "SELECT * FROM user1 WHERE id ='".$_SESSION['id']."'";

and you can read data by this, putting key between 2 ' :
echo "
Name: " .$row['name'];
echo "
Email: " .$row['email'];
echo "
".$row['band'];

A: You need to check first the session id echo $_SESSION['id'];
may be you don't set session after user log in

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible for ubuntu panel window groups to not order according to number of windows open? I prefer to have my windows grouped in the bottom panel.
Ubuntu orders the groups of windows from left to right in descending order of number of windows open in the group.
The problem is that when you close a window in a group, the number windows in the group changes and the location of the group changes in the panel which can be very disorienting.
I would like it so that when a window is grouped it always remains in the same order in the bottom panel
Is it possible that you can set the window groups to not order according to number of windows open in the ubuntu bottom panel?

A: In my experience, no this is not possible. The grouping is not strictly in descending order - it is a curious mix of different factors. On my setup, firefox always gets top spot even when it has less windows than the following group. Except when there's only 1 firefox window. I still haven't figured out how the grouping works.
What is certain though is that for groups that have only 1 window in them, the ordering is controlled by the same value used by nautilus: /apps/nautilus/icon_view/default_sort_order key. To test this, run gconf-editor, navigate to the key and change it to one of the few options available:

*

*name (Default)

*size

*type

*modification_date

*emblems

You should see the windows shift around to reflect this change. Note that this also impacts the ordering of icons in Nautilus. Not terribly clever design imho. As for window grouping remaining unchanged, your best bet is to file a bug against the gnome bugzilla issue tracker for the libwnck component ("Window List" applet).

A: I'd like to thank you for posting this question; I've learned a lot and changed my local setup as a result.  I started looking around for the source code for the Window List applet, and looking at alternatives.  Didn't actually find the source, but what I did find really ROCKS.
First a little perspective.  The "Window List" applet is just an applet - nothing special, just an applet, in a panel.  It's not especially blessed, or an integral part of Gnome, or anything like that.  Heck, the bottom panel itself is nothing special either - it's just a panel.  I used to use 2 panels, (top and bottom) but now I only use one, and (arbitrarily) it's the top one.
So, on to what I found: Gnome-Do.  It's a "dock" app (when configured with the "Docky" look-n-feel) and it gives Gnome a vaguely Macintosh-y feel.  I've installed Gnome-Do, and used it for the past couple of days, before writing about it here.  I'm pretty sure it'll permanently replace the "bottom bar" for me in Gnome.
So, if you're ready for a change to how you manage your windows, google "Gnome do", or dive straight in: http://do.davebsd.com/wiki/index.php?title=Installing_Do#Ubuntu
Hope this helps!-pbr


text:
Q: Crystal Reports error when deployed..Could not load file or assembly 'log4net Please help.  I have a web application that was built in VS2010 and we are using the CR plugin for 2010 and everything works perfect on our local machines.  When we go to deploy the web application to Server 2008 the application runs fine until we try to get to a report.  When we get to a report we receive...
Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=692fbea5521e1304' or one of its dependencies. The system cannot find the file specified.

We have installed the CR2010 runtimes and the file log4net.dll version 1.2.10.0 is in the GAC so we are not referencing it in the application.  When we add it as a reference we get this error no matter where we are in the application, not just on the report pages.  Please help!

A: We also had the same issue with the 64-bit redistributable installed. In our case, we set the "Enable 32 Bit Applications" setting to FALSE in the advanced Application Pool properties and that resolved the issue.

A: If you have a x86 development machine and your web server is a 64-bit machine, you may be running into the problem discussed here:
http://social.msdn.microsoft.com/Forums/en-US/vscrystalreports/thread/546059a6-7179-4027-8f16-822ac6dc189a/
Visual Studio is automatically deploying a 32-bit log4net.dll into the 64-bit web server, even if you don't have it referenced in your project. Just delete the log4net.dll from your bin directory once deployment has finished because it's not actually required by the CR runtime to work.

A: I received the same error message after accidently installing the x86 version of the crystal reports redist on a x64 machine.
Installing the correct x64 redist fixed the problem - http://downloads.businessobjects.com/akdlm/cr4vs2010/CRforVS_redist_install_64bit_13_0.zip

A: We just ran into the same problem and it turned out to not (in our case) be the version of the Crystal Reports redist (we installed the 32 bit versions on our 64 bit machines.  The way we were able to fix the problem was to

Navigate to your virtual directory Application Pool -> Advanced Settings -> Set Enable 32-Bit Applications to True

and changed the managed pipeline mode from Classic to Integrated.  After that we no longer got errors of the missing log4net dll.

A: For me I had a VB Application project and under Compile options, I had "Any CPU" selected for Target CPU and I also had the "Prefer 32-bit" checked.  When the compiled app ran on a 64 bit machine, which only had the x64 runtime installed it could crash with this error, because it tried running as a 32 bit app and wanted the 32 bit runtime.  Unchecking this option and recompiling made it work correctly.

A: Install Crystal Reports for Visual studio Runtime engine for .NET Framework 64 bit

A: Solved my problems.
I have 2 NLB 2008 R2 Servers, my IISs are configured to run in x32.
In one server I have installed x64 and x32 SAP redist and I have the error, in second server only the x32 and works.
To get the first server work I uninstalled all versions and reinstalled only x32, but the server start work only after a reboot.
Bye

A: In my case I had the error while developing with Visual Studio 2022. I did what the other answers here say, installed Runtime 64-bit, because my machine is 64 bit, and then:

*

*(in Visual Studio) Project Debug Properties > Web > Servers > Change Bitness to x64 (using IIS Express)


text:
Q: Share Python code when handling multiple exceptions I've written a program that needs to deal with a function that can throw multiple exceptions. For each exception I catch I have some code that will handle it specifically.
However, I also have some code I want to run no matter which exception was caught. My current solution is a handle_exception() function which is called from each except block.
try:
    throw_multiple_exceptions()
except FirstException as excep:
    handle_first_exception()
    handle_exception()
except SecondException as excep:
    handle_second_exception()
    handle_exception()

Is there a better way to do this?
I would like the code to look like this:
try:
    throw_multiple_exceptions()
except FirstException as excep:
    handle_first_exception()
except SecondException as excep:
    handle_second_exception()
except Exception as excep:
    handle_exception()

A: You could do something like:
try:
    throw_multiple_exceptions()
except FirstException, SecondException as excep:
    if isinstance(excep, FirstException):
        handle_first_exception()
    else:
        handle_second_exception()
    handle_exception()

A: In case there are a lot of exceptions to handle, I suggest the way as follows:
from exceptions import ZeroDivisionError, AssertionError, Exception

def handle_first_exception():
    print "First exception occurred"

def handle_second_exception():
    print "Second exception occurred"

def handle_exception():
    print "Exception occurred"

def throw_multiple_exceptions():
    3/0                 # |-> will output "First exception occurred"
    assert 2 > 3        # |-> will output "Second exception occurred"
    [1, 2, 3].index(0)  # |-> will output "Exception occurred"

if __name__ == '__main__':
    # more types of exceptions could be added to this dict
    exceptions = { ZeroDivisionError: handle_first_exception, AssertionError: handle_second_exception }

    try:
        throw_multiple_exceptions()
    except Exception as excep:
        if type(excep) in exceptions.keys():
            exceptions[type(excep)]()
        else:  handle_exception()

A: how about PEP 0443? its awesome, and very scalable because all you have to do is code and register new handlers
from functools import singledispatch
@singledispatch
def handle_specific_exception(e): # got an exception we don't handle
    pass

@handle_specific_exception.register(Exception1)
def _(e):
    # handle exception 1

@handle_specific_exception.register(Exception2)
def _(e):
    # handle exception 2

try:
    throw_multiple_exceptions()
except Exception as e:
    handle_specific_exception(e)
    handle_exception()

A: You may create a generic routine and pass additional callable object (function), depending on raised exception type.
def handle_first_exception():
    pass

def handle_second_exception():
    pass

handlers = {
    FirstException: handle_first_exception
    SecondException: handle_second_exception
}

def empty_handler():
    pass

def handle_exception(f):
    f()  # call passed handler
    # common code goes here

try:
    throw_multiple_exceptions()
except Exception as e:
    handle_exception(handlers.get(type(e), empty_handler))

Although I'll agree on comment discussion, a lot of exceptions with a lot of different except clauses seems a little bit like a code smell.


text:
Q: Class resulted from NSClassFromString does not associate with class defined in header file In the following code, I used NSClassFromString to convert say an NSString "ColorFilter" to class name ColorFilter.  The result ColorFilter class does not seem to associate with the class defined in my header file in the import statement with the same name.
in my .h file:
#import "ColorFilter.h"   //ColorFilter is a subclass of UIViewController which also has an iVars name imageView of UIImageView class

in my .m file:
NSString *filter = @"ColorFilter";
UIViewController *myFilterClass = [[NSClassFromString(filter) alloc] initWithNibName:filter bundle:nil];

The error I got from the line above was [ColorFilter initWithNibName:bundle:]: unrecognized selector sent to instance...
For testing, I modified the last line to be:
UIViewController *myFilterClass = [[NSClassFromString(filter) alloc] init];
myFilterClass.imageView = .....;

Now the error I got was -[ColorFilter setImageView:]: unrecognized selector sent to instance...
My conclusion is that the ColorFilter class that was produced by NSClassFromString does not know anything about this #import "ColorFilter.h".
Any idea what my mistake was?

A: ColorFilter.m might not be compiled with your app. In the build sources tab of your project, under compile sources, do you see "ColorFilter.m"? If not, drag it into that list.

A: I discovered that one of my static library already has the "ColorFilter" class defined.
It looked like at compile-time, one can overwrite a existing class in the static library.  But at run-time, the classes in static library have precedence over dynamically generated classes.


text:
Q: Euclidean Dirac Lagrangian is NOT Hermitian? In $\mathbb{R}^4$ with the Euclidean metric, there are two entirely independent Dirac spinors, which I write as $\psi$ and $\overline{\psi}$.
This is because the universal double cover of the Euclidean group $E[4]$ is $SU(2) \times SU(2)$.
Also, the Euclidean Dirac operator $i \gamma^j\partial_j$ is known to be Hermitian (self-adjoint on a suitable domain, to be more precise).
For me, the naive Euclidean Dirac Lagrangian is
\begin{equation}
L_{E}=\overline{\psi}[i \gamma^j\partial_j+M]\psi
\end{equation}
where $M$ is some $4 \times 4$ mass matrix.
However, this Lagrangian $L_{E}$ is NOT Hermitian, since the two spinors are completely indepedent of each other.
The Minkowski Dirac Lagrangian is, on the other hand, Hermitian (up to a divergence term) since one spinor is the Dirac adjoint of the other.
Is my naive $L_{E}$ wrong? However, it clearly appears in textbooks and literature. Could anyone please clarify?


text:
Q: Writing out a list of strings to a file I have a list of abbreviations
Letters = ['Ala', 'Asx', 'Cys', ... 'Glx']
I want to output this to a text file that will look this like:
#Letters
Ala, Asx, Cys, ..... Glx
Noob programmer here! I always forget the simplest things! ah
please help and thanks!
import Bio
from Bio import Seq
from Bio.Seq import Alphabet

output = 'alphabetSoupOutput.txt'
fh = open(output, 'w')
ThreeLetterProtein = '#Three Letter Protein'
Letters = Bio.Alphabet.ThreeLetterProtein.letters
fh.write(ThreeLetterProtein + '\n')

  #Don't know what goes here

fh.close()

A: How about fh.write(', '.join(Letters))?

A: I don't know much about the bio package but I guess ...
for letter in letters:
    fh.write(letter + ',')

or
fh.write(",".join(letters))


text:
Q: Is it possible to convert 7z to tar directly? I have a .7z file containing ~360,000 images in multiple directories. I'd like to convert it to a .tar so that I can open it in another computer. Is there a better way than extracting it to files and compressing them again? Is it possible to do the conversion directly?

A: It's not too hard to write something to do the job. Here's an example Perl script (requires the module Archive::Libarchive::XS).
#!/usr/bin/perl
use strict;
use warnings;
use Archive::Libarchive::XS qw(:all);

die "Usage: $0 in.7z out.tar" unless @ARGV == 2;
my ($infile, $outfile) = @ARGV;

my $in = archive_read_new();
archive_read_support_filter_none($in);
archive_read_support_format_7zip($in);

archive_read_open_filename($in, $infile, 10240) == ARCHIVE_OK
  or die "Error opening $infile: ", archive_error_string($in);

my $out = archive_write_new();
archive_write_set_format_ustar($out);
archive_write_open_filename($out, $outfile) == ARCHIVE_OK
  or die "Error opening $outfile: ", archive_error_string($out);

while (archive_read_next_header($in, my $entry) == ARCHIVE_OK) {
  archive_write_header($out, $entry) == ARCHIVE_OK
    or die archive_error_string($out);
  while (1) {
    my $size = archive_read_data($in, my $buff, 65536);
    die archive_error_string($in) if $size < 0;
    last if $size == 0;
    archive_write_data($out, $buff) >= 0
      or die archive_error_string($out);
  }
}

archive_read_free($in);
archive_write_close($out);
archive_write_free($out);

If you wanted a tar.gz / tar.bz2 / tar.xz archive, add the line archive_write_add_filter_gzip($out); or archive_write_add_filter_bzip2($out); or archive_tar_add_filter_xz($out); after the archive_write_set_format line.
This uses no temporary disk space (just the space for the output tar file) and very little RAM (just a few MB for perl, but it works with the files a block at a time, so it's not a problem if your files are bigger than your RAM).

A: .7z archives are archives often compressed with some kind of algorithm, while .tar archives are just archives.
They differ in their scope, and in most cases a conversion would require an optional decompression always followed by an extraction of the source archive. Even if a .7z archive wouldn't use any compression it would still require an extraction.
That being said, If you meant to [decompress] / extract / rearchive the source archive at once, the answer is you can't, at least not using Ubuntu's default tools because tar can't read from stdin, so you can't pipe 7z and tar. Anyway it's very easy to automate everything in a single command:
mkdir tmp && 7z x <path_to_source_archive> -otmp && tar cf archive.tar tmp && rm -rf tmp

* <path_to_archive> = path to the source .7z archive
Also the time required for the source archive's files to be written to the disk and for the extracted files to be read in order to [decompress] / extract / rearchive the source archive in two steps is a bottleneck for the whole task mostly (altough not only) because of a potential disk's low I/O speed, so a partial solution would be to store the temporary files to a ramdisk in order to almost void the overall bottleneck:

*

*Create the mount point for the ramdisk's filesystem: sudo mkdir /mnt/tmpfs

*Mount the ramdisk's filesystem: sudo mount -t tmpfs -o size=<tmpfs_size> tmpfs /mnt/ramdisk* <tmpfs_size> = size of the filesystem in bytes * 103 (1, 1K, 1M, 1G, ...)

*Run mkdir /mnt/tmpfs/tmp && 7z x <path_to_source_archive> -o/mnt/tmpfs/tmp && tar cf archive.tar /mnt/tmpfs/tmp && rm -rf /mnt/tmpfs/tmp* <path_to_archive> = path to the source .7z archive

*Unmount the ramdisk's filesystem: sudo umount

*Remove the mount point for the ramdisk's filesystem: sudo rmdir /mnt/tmpfs


text:
Q: Copying found directory to path built using specified argument and found directory I have the following bash script:
cd root_folder && find folder1 folder2 -name "doc" -exec cp -r --parents {} $1{} \;

The idea is to find all folders named doc under folder1 and folder2 and copying the structure starting from root_folder to the path which is specified by the user's argument (along with all the content of doc).
So for example
root_folder/folder1/other_folder/doc

becomes:
$1/folder1/other_folder/doc

This script works as long as I don't have the user specify the folder to be copied to, i.e. if I don't have the $1. However when I do have it, I get the error:
cp: with --parents, the destination must be a directory
Try `cp --help' for more information.

This despite the fact that 1) I have assured that the specified folder exists beforehand, and 2) If I output the full path to be copied to, it looks exactly as it should, i.e. $1/folder1/other_folder/doc.
I have also tried adding a / after $1 to make $1/{}, but that gives a forward slash too many, making the path contain // which is obviously wrong.
What am I missing here?

A: The answer was adding dirname to the destination path:
cd root_folder && find folder1 folder2 -name "doc" -exec cp -r --parents {} `dirname $1/{}` \;


text:
Q: TCP client making first connection Say I have a Node.js TCP client
https://nodejs.org/api/net.html#net_socket_connect_path_connectlistener
I have a library, and the library takes an array of host/port combinations to connect to. I want the client to make only one connection.
const endpoints = [
 {host: h1, port: p1},
 {host: h2, port: p2},
 {host: h3, port: p3},
];

How can an I implement a simple mechanism to try connecting to these?
My guess is that the simplest way is to connect to them serially, one by one, until first connection.
What I am concerned about, is clients that are connected somehow to two different endpoints. Is that possible?
Upon second thought - it seems no better or safer to try to connect them serially with a timeout, then to try to connect to them all in parallel.
It just seems to be a matter of properly cleaning up connections or half-connections that you don't need after first "real" connection.

A: I believe that generally, each connection lasts only long enough to send a single request and get the response to it.  So connecting to multiple endpoints is indeed possible; if you want to connect to only one, you'd need to connect serially.  (Or you could connect asynchronously and simply "accept" the first to respond, though then you'd get that first connection attempt even to the ones that don't get accepted; whether that's a problem or not depends on why you want to connect to only one.)


text:
Q: wpn-xm.exe fails to start after Windows 10 update My Windows10 machine has just installed its Windows10 April 2018 upgrade.
Now wpn-xm.exe fails to start with message "This application failed to start because it could not find or load the Qt platform plugin "windows".  I downloaded and ran the latest WPNXM-0.8.6 installer, but it made no difference.
Has anyone else experienced this or can give any clue what to try next?
Thanks

A: I had the same issue on my Windows 10 x64. I overwritten the files using this zip file: https://github.com/WPN-XM/server-control-panel/releases/download/v0.8.6/wpnxm-scp-0.8.6-x86_64.zip
That solved my problem to start wpn-xm.exe

A: I had the same problem and looked on the official GitHub bugs page where the bug appears to be still open (And the fix given there didn't work for me).
However, I've managed to get around it by simply not using the WPN-XM control panel and accessing everything directly in the folder on my machine.
You can start PHP/NGINX/ETC by clicking "start.bat" and also start "status.bat" to see what is running. To stop your local server just click "stop.bat". The WPN-XM console and browser interface can also be directly accessed this way until a working fix is released for the control panel.


text:
Q: How to retrieve textbox value and label from form through jquery I am newbie in jquery.
I want to retrieve each textbox value and label from the form. Here I am getting dynamic form in my DOM.
i am triggering form submit even in my DOM something like this and its working..
$('.wpc_contact').submit(function(event){
   // here i want textbox value and label
}

I have tried with doing each() but I didn't get..
<form method="POST" id="contact" name="17" class="form-horizontal wpc_contact">
    <fieldset>

            <legend class="">Demo</legend>

            Name

                <input type="text" placeholder="Name" class="input-xlarge">

           Email

           <input type="text" placeholder="Email" class="input-xlarge">

            <button class="btn btn-success">Send</button>

    </fieldset>
</form>

Can anyone help me?

A: Try this:
$('.wpc_contact').submit(function(event){
       // here i want textbox value and label
    $(this).find('input').each(function(){
      alert('text box value:'+$(this).val());
    });
    $(this).find('label').each(function(){
      alert('label text:'+$(this).text());
    });
});

Use of $(this).find('input'): It will find all input text boxes within the form having class wpc_contact. Similarly, $(this).find('label').
DEMO Link
Requirement to get both label and value together like { label : value } pair, you can try:
$('.wpc_contact').submit(function(event){
  var data = {};
  $('.control-group').each(function(){
    var key = $(this).find('label').text();
    var value = $(this).find('input').val();
    data[key] = value;
  });

  console.log(data);   // data contains label : value pair
});

DEMO Link2

A: Using jquery to retrieve the value easily
You have to give in html textbox id='email'
For textbox
eg.
$('#email').val('result');

For Label
eg.
$('#email').text('result');

A: $('form input[type="text"]').each(function(){
 // Do your magic here

});

If you got the form id:
$('#formId input[type="text"]').each(function(){ // Do your magic here });

A: if yo write $('.wpc_contact').each(function(){ alert($(this).attr("class")); })
it find all elements that have 'wpc_contact' class but you have one element!!!
you should use with find
   $('input').each(function () { alert($(this).attr("class")); })
        $.find('span').each(function () { alert($(this).attr("class")); })

if you want value:
//text box
$('input').each(function () { alert($(this).val()); })
//label
        $.find('span').each(function () { alert($(this).text()); })

A: check out this fiddle
you can use
$('.wpc_contact input').each(function () {
    alert($(this).val());
});

http://jsfiddle.net/8DMy4/2/


text:
Q: SSH copy 1000 files a time I have a folder with 30000 files. I want to copy 1000 files a time via SSH to another folder. I need to do that cause my script is timing out when I try to run it on all 30k.
Is that possible?
EDIT
Based on the comments.
I connect via putty. The script is executed from the user by clicking a button and it not the problem. I just want to move the files in batches and I don't want to do it via ftp.
Like the LIMIT command in SQL (LIMIT 0,1000 or LIMIT 1000,2000)

A: The best way to copy over ssh is by using scp (pscp in putty)
pscp.exe -r somedir me@server:/data/vol1

pscp.exe uses all settings from putty including authentication keys.


text:
Q: Exponentiation of vector in JAGS model, Bayesian analysis in R I have the following JAGS model for use in a Bayesian model in R. I am trying to estimate the posterior distribution for my variable "R". All variables but R are supposed to be deterministic nodes. Each variable, s_A, z_A, z_W, and d are vectors. While tau_s is a data.frame. TTD_aquifer and O2s_all are therefore expected to be a vector for each i.
model {
for (i in 1:N){
    y[i] ~ dnorm(mu[i], tau)
    mu[i] <- sum(O2s_all)/2

tau_s_bar[i] = (s_A[i]*z_A[i])/R[i]*log(z_A[i]/(z_A[i]-z_W[i]))

TTD_aquifer <- t((d[i]*sqrt(tau_s_bar[i]))/sqrt(4*3.14*d[i]*t(tau_s[,i]^3))*exp(-1*((d[i]*tau_s_bar[i])/(4*t(tau_s[,i])))*
                                                                      (1-t(tau_s[,i])/tau_s_bar[i])^2))

O2s_all <- t(O2_o[i]-k_o[i]*t(tau_s[,i]))*TTD_aquifer

# prior on R
 R[i] ~ dlnorm(-2, 1/(0.6)^2)
 }
# prior on tau and sigma
 tau <- pow(sigma, -2)
 sigma ~ dunif(0, 100)
}

When I run this in jags.model() I get the following error:   RUNTIME ERROR:
Invalid vector argument to exp. So it looks like I cannot input a vector into exp() like you can in R. The equations for TTD_aquifer and O2s_all run fine in R for a deterministic example. How should I write my equation for TTD_aquifer in JAGS to avoid the exp issue?

A: In JAGS, inverse link functions like exp only take scalar arguments. You could change your model to this in order to use exp. Note that you will need to include an object in your data list that denotes how many rows are in the tau_s data frame. Since I do not know what your model is doing I have not checked to determine if your parentheses are in the correct location across all of your divisions and multiplications.
model {
for (i in 1:N){
    y[i] ~ dnorm(mu[i], tau)
    mu[i] <- sum(O2s_all[,i])/2

tau_s_bar[i] <- (s_A[i]*z_A[i])/R[i]*log(z_A[i]/(z_A[i]-z_W[i]))

for(j in 1:K){ # K = nrow of tau_s

TTD_aquifer[j,i] <- t((d[i]*sqrt(tau_s_bar[i]))/
sqrt(4*3.14*d[i]*t(tau_s[j,i]^3))*
exp(-1*((d[i]*tau_s_bar[i])/(4*t(tau_s[j,i])))*
(1-t(tau_s[j,i])/tau_s_bar[i])^2))

O2s_all[j,i] <- t(O2_o[i]-k_o[i]*t(tau_s[j,i]))*TTD_aquifer[j,i]

} # close K loop
# prior on R
 R[i] ~ dlnorm(-2, 1/(0.6)^2)
 }
# prior on tau and sigma
 tau <- pow(sigma, -2)
 sigma ~ dunif(0, 100)
}

As TTD_aquifer and 02s_all should be a vector for each i, they should then be a two dimensional matrix of the same size as tau_s for each step in an MCMC chain. If you have a big dataset (i.e., big N and K) and are running this model for many iterations, tracking those derived parameters will take up considerable memory. Just something to keep in mind if you are running this on a computer without sufficient RAM. Thinning the chain is one way to help deal with the computational intensity of tracking said parameters.


text:
Q: practical use of `\noexpand` outside`\edef`(`\xdef`) and `\write`(`\messge`)? After reading (and searching through) TeXbyTopic.pdf I have the impression that practical use of \noexpand falls into one of the following three cases,

*

*Inside \edef or \xdef, including the cases where macros are defined so that they are used in the context of \edef, such as
\def\protect{\noexpand\protect\noexpand}

*Inside \write and \message, including the case of movable texts in LaTeX

*In the special construction \if\noexpand#1\relax
Are there any other practical uses of \noexpand? Are there any practical use of \noexpand that is not in the expansion-only context, except for #3 listed above? I am new to plain and hope to understand plain better (especailly, the expansion-only context) by understanding various usages of \noexpand.

A: There are lots of tex primitives that expand tokens looking for arguments like \if and \ifcat. \noexpand would have a similar effect with any of them but whether or not that is useful is harder to say.
for example
\def\zz{hello}

\input s\noexpand\zz

\bye

inputs the file s.tex and then typesets hello whereas
\def\zz{hello}

\input s\zz

\bye

produces
! I can't find file `shello'.

But you could more easily have used a space after s than \noexpand to stop the scan for a filename.
As indicated by Henri in comments there is also the use to nullify the end of file token in input or \scantokens
\edef\zz{\scantokens{z}}

is the error
! File ended while scanning definition of \zz.

but
\edef\zz{\scantokens{z\noexpand}}

or
\everyeof{\noexpand}
\edef\zz{\scantokens{z}}

are error free.


text:
Q: Why the component(s) are not rendered which are added after the first empty element(or self-closing) component | Vue 3 I was doing some experiments with Vue. When I add the same component multiple times with different properties it renders only once. I investigated and come to know that it didn't render the component after adding the first self-closing style component.
I don't know what is going on here.
FYI- I am using Vue 3. but I think it is also not working with Vue 2.
here is the code.

let Counter = {
    props: {
        count: {
            type: Number,
            required: true
        }
    },
    template: `
        {{ count }}
    `
}
const app = Vue.createApp({
    components: {
        'counter': Counter
    },
});

const vm = app.mount("#app");

    <counter :count="1"></counter>

    <counter :count="2" />

    <counter :count="3"></counter>

In this code, the app will only render 1 and 2 but as soon it reached the first self-closing component then the next component will never be rendered. i.e 3 is not render.

A:
Components with no content should be self-closing in single-file components, string templates, and JSX - but never in DOM templates.
Components that self-close communicate that they not only have no content, but are meant to have no content. It's the difference between a blank page in a book and one labeled "This page intentionally left blank." Your code is also cleaner without the unnecessary closing tag.
Unfortunately, HTML doesn't allow custom elements to be self-closing - only official "void" elements. That's why the strategy is only possible when Vue's template compiler can reach the template before the DOM, then serve the DOM spec-compliant HTML.

https://v2.vuejs.org/v2/style-guide/#Self-closing-components-strongly-recommended

Also note, that counter is not a legal component tag name, component tag names must be at least two-word.


text:
Q: Websphere application server 8.5 can be installed on Ubuntu 12.04? and how? If WAS can be installed on Ubuntu, how to config & install?

A: In the next link you have the Linux distributions offically supported by WebSphere Application Server 8.5
http://pic.dhe.ibm.com/infocenter/prodguid/v1r0/clarity-reports/report/html/softwareReqsForProduct?deliverableId=1307977887217&osPlatform=Linux
Only AsianLinux, Red Hat Enterprise Linux and Suse Linux Enterprise are officialy supported, not Ubuntu.

A: Though Ubuntu to is not an supported OS by IBM for WebSphere, it is possible to install WebSphere Application Server (WAS) 8.5 on Ubuntu for development environment.

*

*Prerequisites

You need to install some prerequisites packages. Run following command to install the same.

sudo apt-get install libxtst6 libgtk2.0-0 libc6:i386 libgcc1:i386
  libgtk2.0-0:i386 libswt-glx-gtk-3-jni:i386 libswt-gnome-gtk-3-jni:i386
  libstdc++6:i386

Change the default shell.
sudo mv /bin/sh /bin/sh.org
sudo ln -s /bin/bash /bin/sh

*Download the binaries from IBM Web site.

*Extract the binaries to a temp location.

*Start Installation Manager.

*Add repository.config file.You will get this file in the extracted binaries.

*Click on Install button to start the installation

Source : How to Install WebSphere Application Server on Ubuntu

A: Looks like IBM Websphere Application Server Network Deployment now supports for Ubuntu 14.04 LTS since version 8.5.5.5
http://www-969.ibm.com/software/reports/compatibility/clarity-reports/report/html/softwareReqsForProduct?deliverableId=1345529544358&osPlatform=Linux


text:
Q: Where can I acquire skills to implement online maps? I'm interested in creating maps and map "mashups" online, and have been pointed to Leaflet as a great tool to help me do what I want.
Leaflet's documentation is clear and easy to follow, but it demands pre-existing knowledge of how to use tools like CloudMade. For instance, Leaflet documentation starts by telling the user something like:
// initialize the map on the "map" div with a given center and zoom
var map = L.map('map', {
    center: [51.505, -0.09],
    zoom: 13
});

Which I sort of understand, but I don't know how to get the map, point to the map, create the map, etc. There seems to be a huge "how to make maps work on Web sites" chunk of knowledge that's required before diving into Leaflet.
CloudMade also throws you in at the very deep end.
Where do I pick up the Maps 101 knowledge I need to make sense of how all this works?

A: I assume you were following the Quick-Start Tutorial on Leaflet's website?  You can look at the source of the example for the full break down on how it works internally.  Leaflet doesn't use any Cloudmade specific stuff other than itself, so you shouldn't have to refer to the Cloudmade tool.
If you're looking for some basic Javascript tutorials (the language that Leaflet uses), there are some mentioned on Language Books/Tutorials for Popular Languages.

A: Leaflet by itself doesn't include any maps (as opposed to Bing Maps and Google Maps for example). All the examples they display with Cloudmade are exactly that, just examples.
For instance, instead of using Cloudmade you could use OpenStreetMap (OSM) tiles directly, like this:
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png').addTo(map);

Or use tiles from other sources, or even your own tiles.
I'm guessing that what threw you off on the quick-start was the reference to Cloudmade. Don't mind that. Instead of going through the fuss of getting a Cloudmade key just create the layer as I've shown above. Everything will work the same and the only thing that will differ is the imagery on the background.


text:
Q: How to allow underscore in self-defined command? For example, those lines works perfectly fine.
\includegraphics[scale=1.1]{9709_s10_qp_11_Q3} \\
\flushright \verb=9709_s10_qp_11_Q3= \\[2ex]
\includegraphics[scale=1.1]{9709_s10_qp_12_Q7} \\
\flushright \verb=9709_s10_qp_11_Q3= \\[2ex]
\includegraphics[scale=1.1]{9709_s10_qp_13_Q1} \\
\flushright \verb=9709_s10_qp_11_Q3= \\[2ex]
\includegraphics[scale=1.1]{9709_s11_qp_11_Q8} \\

To save time, I want to define a new command mytopic (to use in enumerate),
\newcommand{\mytopic}[1]{%
\item { \flushright \verb= {#1} = } \\
    \includegraphics[scale=1.1]{#1} \\[2ex]
}%

The problem arises as I have lots of underscore in my filenames, which I don't really want o rename.
How can I adapt it so that it take the filename as well as enabling the verb output on the filename? I tried to use \texttt{} but it seems to have the same problem.

A: The command \path from hyperref is handy here:
\newcommand{\mytopic}[1]{%
\item {\path{#1}} \\
    \includegraphics[scale=1.1]{#1} \\[2ex]
  }

\begin{enumerate}
   \mytopic{DSC_0942}
 \end{enumerate}

\path allows underscores and other characters used for file paths -- exactly what you need.


text:
Q: Elisp: can't get matched group from regex Code:
(if
      (string-match-p "\\(.*\\)/www/sites"
                      "/var/www/lwt/www/sites/all/modules/bundles/bundles.module")
      (match-string-no-properties 1
                      "/var/www/lwt/www/sites/all/modules/bundles/bundles.module")
      "false"
)

Here I expected to get "/var/www/lwt", but I get nil. What is wrong?

A: As its docstring tells you:

string-match-p is a compiled Lisp function in `subr.el'.
(string-match-p REGEXP STRING &optional START)
Same as `string-match' except this function does not change the match data.

So you should be using string-match.


text:
Q: How to handle network interrupts and connection pooling I'm facing a problem in JavaEE(Glassfish and also TomEE) with connection pooling. When the network/datatier is down and going up again, the JDBC pool seems to "hang". So there are always timeouts while trying to get a connection to the datatier. I'm sure there is something to handle this behaviour. Any suggestions?
Thanks!

A: you should configure the pool.
here the links: http://tomee.apache.org/datasource-config.html and http://tomee.apache.org/common-datasource-configurations.html
Take care of XXXevictionXXX, validationquery and testXXX properties


text:
Q: Is there a GDB backend for ARM Debug Architecture? ARMv7-A&R architecture manual (DDI0-406B) section C1 defines a debug interface through a series of memory mapped (or CP14 mapped) registers. Features include hardware breakpoints, hardware watchpoints, vector catch, and execution of ARM instructions in debug state. It seems like the perfect alternative to JTAG debugging which usually involves expensive cable and software.
From playing around with my Cortex A9 MPcore device, I found that it is possible for one core to enter debug state and have another core control it (step debugging, breakpoint set, etc). I was wondering if anyone has gone beyond that and implemented the GDB remote serial protocol with this interface?


text:
Q: RoR: Can you send an email with an inline form? Im using ROR to create this application.
So I've been asked by a client to create a survey for my web application. They want this survey to be emailed out to users under specific circumstances. Is it possible to have the survey actually inside of the email? so that the user can go ahead and fill out the fields in the email instead of sending a link and having the user redirect to the survey page on the website?

A: Forms can be embedded in emails, however the individual email client determines how it is handled and displayed. According to this blog:
"Given the sporadic support for forms in emails, we recommend linking to a form on a website in an email rather than embedding it therein. This is the safest, most reliable solution to pairing an email message with a form. More people will see it and be able to use it, and as a result participation will increase."
Hope this helps!


text:
Q: How do I copy a view from one viewContainerRef collection to another in angular4 I am attempting to load multiple components dynamically and only have one of them visible at one time. Basically I am building an application that may have 100 or more components and I want to dynamically load a subset of those components at runtime into my application. I only want to view one of the components at a time but I want each loaded component to remain in the DOM so users can be editing on each tab and not lose changes when they change tabs. I am attempting to implement this using dynamic component loading and the ViewComponentRef abstract class. Since I want all loaded components to stay in the DOM until I delete them, I have created two container components and plan to hide one of them. The second container component will only contain the loaded component I want to be visible. I tried to do this using the get() method on the master collection and the insert() method on the selected collection. The code is running without error but it does not do what I expected. It does not copy the actual component content (i.e. html) from the master collection to the selected collection. How do I copy views from one collection to another and is there a different way to display only a subset of the dynamically loaded components.
Typescript
      import { Component, Input, Output, EventEmitter, ComponentFactoryResolver, AfterViewInit, OnDestroy, ViewChild,Type, ViewContainerRef  } from '@angular/core';

  import { AppletContainer } from '../appletContainer/appletContainer.component';
  import { AppletCollection } from '../appletCollection/appletCollection.component';
import { AdComponent } from '../ad.component';
import { TestComponent } from '../test.component';

  export class AdItem {
constructor(public component: Type<any>, public data: any) {}
}

  @Component({
selector: 'applet-frame',
templateUrl: '/NetworkDesigner2/views/app/appletFrame/appletFrame.component.html',
styleUrls: ['NetworkDesigner2/views/app/appletFrame/appletFrame.component.css'],
entryComponents:[TestComponent]
  })

export class AppletFrame implements AfterViewInit, OnDestroy {

items: AdItem[] = [];
@Input() inputControlStructure:any;
@Output() updateControlStructure = new EventEmitter<any>();

currentIndex: number = 0;
counter:number = 0;

@ViewChild(AppletContainer) adHost: AppletContainer;
@ViewChild(AppletCollection) master: AppletCollection;

constructor(private componentFactoryResolver: ComponentFactoryResolver) {

  let newItem = new AdItem(TestComponent,{component:'sample manual component',description:'sample manaual component'})

  this.items.push(newItem);

}

ngAfterViewInit(){
}

ngOnDestroy(){}

loadComponent(){

  // Identify the current target component to load
  let adItem = this.items[this.currentIndex];
  // Create the component Factory object for the target component
  let componentFactory = this.componentFactoryResolver.resolveComponentFactory(adItem.component);
  // Declare a reference to the viewContainerRef object for the 'master' collection. This is the ng-template that will be hidden
  let viewContainerRef1 = this.adHost.viewContainerRef;
  // Declare a reference to the viewContainerRef object for the 'select' collection. This is the collection that will show the selected component
  let viewContainerRef2 = this.master.viewContainerRef;
  // Create the component
  viewContainerRef1.createComponent(componentFactory);
  // Clear the 'select' container so that I can copy over the targeted view only
  viewContainerRef2.clear();
  // Copy the targeted view into the 'select' container. For now this is hardcoded to copy the first element as an experiment
  viewContainerRef2.insert(viewContainerRef1.get(0),0);

  this.counter++;
}

loadSampleContentHandler(){
  this.loadComponent();
}

  }

basic html file

Revision Type:

{{inputControlStructure.activeRevisionType}}

Load

Submit

Close

<ng-template applet-collection></ng-template>

<ng-template applet-container></ng-template>


text:
Q: Detecting if a PDF file contains 3D element Is there any way to detect if a PDF contains 3D element (Universal 3D object embedded) without reading the file contents? Can this information be obtained from metadata?

A: AFAIK, there is no requirement to put any info into its metadata about the fact that 3D elements may be contained in the document.
Some U3D writing software may put some hint about it into the XML metadata though.
Long Answer
You'll have to parse the PDF page tree at least partially in order to find out.
Technically, 3D elements are implemented as annotations. To discover any annotation, you'd have to follow this parsing path:

*

*Read the trailer. It tells you the object number of the /Root indirect object of the document.

*Read the cross reference table. It tells you the byte offsets for each indirect object within the document.

*Go to the /Root indirect object. Read its /Pages key. This tells you which indirect object represents the root of the document's page tree.

*Go to the indirect object which represents the /Pages.  Read its /Kids key. This tells you which other indirect objects represent document pages.

*Go to each indirect object representing a document page. Look for any (optionally present) /Annots key. If present it will point to other indirect objects representing (possibly all sorts of) annotations.
Now you've found out if the PDF contains annotation(s) or not. If not, stop here. If yes, go on to determine the annotation type(s):

*

*Go to all indirect objects found in the last step. They are of /Type /Annot. See if they are additionally of /Subtype /3D. If yes, you have found a 3D annotation. (Attention, this may still not be a U3D one!)

*Within the lastly found indirect object(s) -- the one(s) with the /Subtype /3D key -- look for an additional key of /3DD. It points to this indirect object which contains the actual 3D stream.

*Go to the indirect object containing the 3D stream. Its object dictionary should again contain a key:value pair of /Type /3D. Look at its /Subtype key. If it says /U3D you have found what you looked for...
Short Answer
You may be lucky and harvest some low-hanging fruits by using good old grep like this:
$> grep -a U3D cc-7-july09.pdf

  /Subtype /U3D
  /MS /U3D
  /U3DPath [ <135BB3D42FBD85F7C2E178> <056D9A891FB5FDCE8E> ]
  /MS /U3D
  /U3DPath [ <5FFAF35CE3CBD34FAE5360> <4DDFD6048FC6DA05> ]
  /MS /U3D
  /U3DPath [ <2E4E4FD7FEC771038BC5EA> <2A6579CC91BE0B> ]
  /MS /U3D
  /U3DPath [ <6F303AF9850721D5D1FC6C> <7D1B08BEAE4A5A9BEDBB> ]
  /MS /U3D
  /U3DPath [ <F270A04603F0DE08B8AA29> <EE5180016FFBD542> ]
  /MS /U3D
  /U3DPath [ <A1D5848F6841ADA9A3583C> <A3F8A5D45849D392EF> ]
  /MS /U3D
  /U3DPath [ <34B8650D178BBDFF61DC03> <2D8F4C7D3CD980F976> ]
  /MS /U3D
  /U3DPath [ <843CD0339FD1852CCA235B> <9719FB65A990897F> ]

However, this will not work for all 3D PDF documents, especially if the 3D elements are part of an object stream.

A: For anyone having the same problem as us, this is an approach we come up with using "iText" (free version is still avaiable).
The downside is that you will need to iterate every page through the file to check the content but it's still fast enough for us.
        PdfReader reader = new PdfReader(contents);
        int pages = reader.getNumberOfPages();
        boolean pdf3D = false;
        for (int i = 1; i <= pages; i++) {
            PdfDictionary page = reader.getPageN(i);
            PdfArray array = page.getAsArray(PdfName.ANNOTS);
            if (array == null) {
                continue;
            }
            for (ListIterator<PdfObject> iter = array.listIterator(); iter.hasNext();) {
                PdfDictionary annot = (PdfDictionary) PdfReader.getPdfObject(iter.next());
                PdfObject pdfObject = annot.get(PdfName.SUBTYPE);
                if (pdfObject != null) {
                    if (PdfName._3D.equals(pdfObject) || PdfName.GOTO3DVIEW.equals(pdfObject)) {
                        pdf3D = true;
                        break;
                    }
                }
            }
            if (pdf3D) {
                // if we already any of 3D element, we can break the loop
                break;
            }
        }

A: For cases where it is sufficient to know if a PDF contains any 3D content (including, but not being exclusive to Universal 3D objects), you could also use the VeraPDF software in feature extraction mode. Follow the steps below to get a list of all Annotation types (including 3D annotations).
First edit VerapDF's "features.xml" configuration file as explained here:
https://docs.verapdf.org/cli/config/#features.xml
Make sure that <feature>ANNOTATION</feature> is included in the enabledFeatures element.
Using this file as an example, run:
verapdf --off --extract action_goto3dview.ar10.pdf > action_goto3dview.ar10.xml

In the output, check the "annotations" element, which lists all annotations that are present in the file, and look for annotations with subType "3D" (which indicates a 3D annotation):
<annotation id="annotIndir186">
<subType>3D</subType>
<rectangle lly="129.348" llx="163.939" urx="437.813" ury="331.861"></rectangle>
<width>273.874</width>
<height>202.513</height>
<contents>3D Model</contents>
<annotationName>3D3</annotationName>
<resources>
    <xobject id="xobjIndir187"></xobject>
</resources>
<invisible>false</invisible>
<hidden>false</hidden>
<print>true</print>
<noZoom>false</noZoom>
<noRotate>false</noRotate>
<noView>false</noView>
<readOnly>true</readOnly>
<locked>false</locked>
<toggleNoView>false</toggleNoView>
<lockedContents>false</lockedContents>
</annotation>

This corresponds to Step 1 in @kurt-pfeifle's answer above. As VeraPDF doesn't drill down to the level required to identify U3D streams, I'd suggest @kurt-pfeifle's answer for cases where that level of detail is needed.


text:
Q: Rendered rectangles do not move with chart when scrolling I want to draw a rectangle on a chart and have it move with the rest of the chart.  However, it stays where it was originally rendered in pixel coordinates.
I would have thought there would be a way to add annotations such as this in world coordinates rather than screen coordinates, but I was not able to find a way.  Is such a thing possible?
Assuming I am stuck with annotating in screen coordinates, what event(s) do I need to handle to redraw the rectangle when the user zooms or scrolls?
Simple example:
chart.renderer.rect(chart.xAxis[0].toPixels(1432897200000),chart.yAxis[0].toPixels(1.09674),14,14, 0)

http://jsfiddle.net/bz3t79p5/
Also, I have had no luck with using axis.toPixels() for setting the rectangle's width and height.  I was getting values that were way out of whack.  Is there a trick to converting width and height from world coordinates to pixels?


text:
Q: convertir csv a tabla javascript tengo el siguiente csv recogido con un fetch en un API rest:
animales;numeros;nombres;
leon;21,5;Paula;
perro;32,4;Guillermo;
zebra;44;Elena;
gorila;100,4;Pepe;

Este csv lo guardo en una variable en un sessionStorage llamado datos.
Deseo convertirlo en tabla html con javascript:

animales
numeros
nombres

leon
21,5
Paula

perro
32,4
Guillermo

zebra
44
Elena

gorila
100,4
Pepe

Pero con la pega de que no deseo todos los campos, es decir me gustaría que solo fuera:

animales
numeros

leon
21,5

perro
32,4

zebra
44

gorila
100,4

o solo:

animales
nombres

leon
Paula

perro
Guillermo

zebra
Elena

gorila
Pepe

Es decir necesito seleccionar los campos que deseo utilizar.
He probado a tranformarlo en json:
function convCsvAJson(datos){

      var lines=datos.split("\n");

      var result = [];

      var headers=lines[0].split(",");

      for(var i=1;i<lines.length;i++){

        var obj = {};
        var currentline=lines[i].split(",");

        for(var j=0;j<headers.length;j++){
          obj[headers[j]] = currentline[j];
        }
        result.push(obj);

      }

      //return result; //JavaScript object
      return JSON.stringify(result); //JSON
    }

    console.log(convCsvAJson(datos));

dando como resultado:
{"animales;numeros;nombres;":"leon;21,5;Paula;"}
{"animales;numeros;nombres;":"perro;32,4;Guillermo;"}
{"animales;numeros;nombres;":"zebra;44;Elena;"}
{"animales;numeros;nombres;":"gorila;100,4;Pepe;"}

Pero nose si es exactamente lo que necesito ya que debo realizar una columna de cada resultado con un header para cada dato y no necesito todos los datos que se guardan en el csv ya que debo seleccionar solo los que necesito.
También he probado a separar cada columna en un array o json distinto:
he preguntado anteriormente pensando que esta podría ser la solucion
Dando como resultado a la pregunta:

/* Datos obtenidos del servicio web */
let datos_crudos = `animales;numeros;nombres;
leon;21,5;Paula;
perro;32,4;Guillermo;
zebra;44;Elena;
gorila;100,4;Pepe;`;

/* Elementos separados por líneas */
let datos_separados = datos_crudos.split('\n');

/* Obtengo el primero para conocer los nombres de las columnas */
let cabeceras = datos_separados.shift().split(';');

/* Predefinimos la salida y sus propiedades */
let datos = {};
cabeceras.forEach(cabecera => {
  datos[cabecera] = [];
});

/* Iteramos por el resto de datos */
while (elementos = datos_separados.shift()) {
  /* Iterams cada elemento del registro */
  elementos.split(';').forEach((elemento, indice) => {
    /* Lo agregamos a la cabecera dada por su índice */
    datos[cabeceras[indice]].push(elemento);
  });
}

/* Mostramos el resultado */
console.log(datos);

Pero tampoco he conseguido realizar lo que busco, alguien sabría como puedo resolverlo?? He estado buscando en internet pero no consigo encontrar el resultado adecuado, ya que la gran mayoría de resultados se basan en un csv subido por un usuario o tratan diferentes resultados que poco tienen que ver con lo que necesito. Así que después de muchas horas de darle al coco y de no saber que hacer ya me gustaría pediros ayuda a ver si alguien sabría decirme, Gracias.

A: Podemos separar el string de respuesta por líneas, usando split, lo cual nos daría (más concretamente split("\n"))
[
    "animales;numeros;nombres;",
    "leon;21,5;Paula;"
    "perro;32,4;Guillermo;"
    "zebra;44;Elena;"
    "gorila;100,4;Pepe;"
]

Entonces, volveríamos a hacer un split, para separar los elementos por cada punto y coma
result = result.split(";")

Haremos split a la primera línea para obtener los datos
Nos quedaría
[
    "animales",
    "numeros",
    "nombres"
]

Basado en ese, simplemente podemos convertirlo a un Array de objetos, basándonos el en split de la primera línea

var data = `animales;numeros;nombres;
leon;21,5;Paula;
perro;32,4;Guillermo;
zebra;44;Elena;
gorila;100,4;Pepe;`.split("\n");

const names = data[0].split(";");
let result = [];

data.forEach((el,i) => {
  if (i === 0) return;
  const d = el.split(";").join(" ").split(" ");
  const obj = {};
  d.forEach((el,i) => {
    if (el === "") return
    obj[names[i]] = el;
  })
  result.push(obj);
});

console.log(result);

Entonces podríamos dibujar la tabla usando result.forEach

var data = `animales;numeros;nombres;
leon;21,5;Paula;
perro;32,4;Guillermo;
zebra;44;Elena;
gorila;100,4;Pepe;`.split("\n");

const names = data[0].split(";");
let result = [];
const table = document.createElement("TABLE");
const tr = document.createElement("TR");

names.forEach(el => {
  if (el === "") return;
  const th = document.createElement("TH");
  th.innerHTML = el;
  tr.appendChild(th);
});

table.appendChild(tr);
data.forEach((el,i) => {
  if (i === 0) return;
  const d = el.split(";").join(" ").split(" ");
  let tr2 = document.createElement("TR");
  const obj = {};
  d.forEach((el,i) => {
    if (el === "") return
    obj[names[i]] = el;
    let td2 = document.createElement("TD");
    td2.innerHTML = el;
    tr2.appendChild(td2);
    table.appendChild(tr2);
  });
  result.push(obj);
});
document.body.appendChild(table);

const soloAnimales = () => {
  const r = [];
  result.forEach(el => {
    r.push(el.animales);
  });
  return r;
};

console.log("Animales", soloAnimales());
td, th {
  border: 1px solid #ddd;
  padding: 8px;
}

tr:nth-child(even){background-color: #f2f2f2;}

th {
  padding-top: 12px;
  padding-bottom: 12px;
  text-align: left;
  background-color: #4CAF50;
  color: white;
}

table {
  border-collapse:collapse;
}

A: Creo que has probado todas las posibilidades menos las que a mí me parece más obvia: crear un array de objetos, donde cada objeto es una línea:

let datos_crudos = `animales;numeros;nombres;
leon;21,5;Paula;
perro;32,4;Guillermo;
zebra;44;Elena;
gorila;100,4;Pepe;`;

function csvToObjects(csv,separator) {
  const lines = csv.split('\n');
  //sacamos el primer elemento, los headers
  const headers = lines.shift().split(separator);

  const data = lines.map(line => {
    // para cada línea obtenemos los campos o columnas
    // y rellenamos un objeto con los valores
    const columns = line.split(separator);
    const obj = {};
    columns.forEach((column,index) => {
      // después del último separador puede haber un vacío,
      // en ese caso no lo guardamos
      if (column) {
        obj[headers[index]] = column;
      }
    });
    return obj;
  });
  return data;
}

console.log(csvToObjects(datos_crudos,";"));

A: Creo que te estás complicando en la forma de armar la estructura, no necesitas que sea muy descriptiva, solo saber qué hacer con los datos y tener en cuenta que la primera línea es la que se usará para crear títulos.
Revisa comentarios en el código para ver qué se hace en cada paso y no dudes en preguntar si algo no quedó claro.

let txt = `animales;numeros;nombres;
leon;21,5;Paula;
perro;32,4;Guillermo;
zebra;44;Elena;
gorila;100,4;Pepe;`;

// Poner aquí los índices de columnas a mostrar
// 0 = animales
// 1 = numeros
// 2 = nombres
let columnas = [0, 2]; // No mostrar números

// Separar por líneas: .split('\n')
// Recorrer .map()
// Eliminar ; del final de la línea item.substring(0, item.length - 1) evita un elemento vacío
// Separar por ; .split(';')
let data = txt.split('\n').map(item => item.substring(0, item.length - 1).split(';'));

// No necesitas una estructura muy elaborada:
console.log(data);

// Crear tabla, encabezado (thead) y cuerpo (tbody)
let table = document.createElement('table');
let thead = document.createElement('thead');
let tbody = document.createElement('tbody');

// Crear encabezados con datos de la primera fila
let tr = document.createElement('tr');
// Recorrer por elemento e índice
data[0].forEach((titulo, index) => {
    // Verificar que el índice está en el arreglo de columnas
    if(columnas.includes(index)) {
        // Crear celda de título, asignar contenido y agregar a fila
        let th = document.createElement('th');
        th.textContent = titulo;
        tr.appendChild(th);
    }
});
// Agregar fila a encabezado
thead.appendChild(tr);

// Recorrer resto de arreglo para agregar a cuerpo de tabla
for(let i = 1; i < data.length; i++) {
    let tr = document.createElement('tr');
    // Recorrer cada elemento para crear celda
    data[i].forEach((texto, index) => {
        if(columnas.includes(index)) {
            let td = document.createElement('td');
            td.textContent = texto;
            tr.appendChild(td);
        }
    });
    // Agregar fila a cuerpo
    tbody.appendChild(tr);
}

// Agregar encabezados y cuerpo a tabla
table.appendChild(thead);
table.appendChild(tbody);

// Agregar tabla al documento
document.body.appendChild(table);

También puedes filtrar las columnas usando títulos en lugar de índices:

let txt = `animales;numeros;nombres;
leon;21,5;Paula;
perro;32,4;Guillermo;
zebra;44;Elena;
gorila;100,4;Pepe;`;

// Poner aquí los índices de columnas a mostrar
let columnas = ['numeros', 'nombres']; // No mostrar animales

// Separar por líneas: .split('\n')
// Recorrer .map()
// Eliminar ; del final de la línea item.substring(0, item.length - 1) evita un elemento vacío
// Separar por ; .split(';')
let data = txt.split('\n').map(item => item.substring(0, item.length - 1).split(';'));

// No necesitas una estructura muy elaborada:
console.log(data);

// Crear tabla, encabezado (thead) y cuerpo (tbody)
let table = document.createElement('table');
let thead = document.createElement('thead');
let tbody = document.createElement('tbody');

// Crear encabezados con datos de la primera fila
let tr = document.createElement('tr');
// No se necesita recorrer por índice
data[0].forEach(titulo => {
    // Verificar que el título está en el arreglo de columnas
    if(columnas.includes(titulo)) {
        // Crear celda de título, asignar contenido y agregar a fila
        let th = document.createElement('th');
        th.textContent = titulo;
        tr.appendChild(th);
    }
});
// Agregar fila a encabezado
thead.appendChild(tr);

// Recorrer resto de arreglo para agregar a cuerpo de tabla
for(let i = 1; i < data.length; i++) {
    let tr = document.createElement('tr');
    // Recorrer cada elemento para crear celda, aquí sí se necesita el índice
    data[i].forEach((texto, index) => {
        // Con el índice se obtiene el título para ver si está en columnas y mostrar
        if(columnas.includes(data[0][index])) {
            let td = document.createElement('td');
            td.textContent = texto;
            tr.appendChild(td);
        }
    });
    // Agregar fila a cuerpo
    tbody.appendChild(tr);
}

// Agregar encabezados y cuerpo a tabla
table.appendChild(thead);
table.appendChild(tbody);

// Agregar tabla al documento
document.body.appendChild(table);


text:
Q: Passing parameter to object data provider in wpf I am passing int value to my dataprovider class but I am getting below error , could not able to make out what is the problem.
error says : Severity   Code    Description Project File    Line    Column  Source
Error       The text ' ' is not allowed after the closing '}' of a MarkupExtension expression. Line 13 Position 33. ObjectDataProvider  D:\Learing\WpfApplication1\ObjectDataProvider\MainWindow.xaml   13  33  Build
code is like below.
window.xaml
<Window x:Class="ObjectDataProviderExer.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:src="clr-namespace:ObjectDataProviderExer"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <ObjectDataProvider x:Key="Provider" ObjectType="{x:Type src:Student}"
                MethodName="GetStudents">
            <ObjectDataProvider.MethodParameters>
                <sys:Int32>20</sys:Int32>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </Window.Resources>
    <Grid>
        <DataGrid x:Name="MyGrid" ItemsSource="{Binding Source={StaticResource Provider}}"></DataGrid>
    </Grid>
</Window>

Student.cs
using System.Collections.ObjectModel;
using System.Linq;

namespace ObjectDataProviderExer
{
    public class Student
    {
        private ObservableCollection<Student> _studentsList;

        private int _age;

        public int Age
        {
            get { return _age; }
            set { _age = value; }
        }

        private string _name;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        public Student()
        {
            _studentsList = new ObservableCollection<Student>();
        }

        public ObservableCollection<Student> GetStudents(int age)
        {
            CreateStudentCollection();
            return (ObservableCollection<Student>)_studentsList.Where(x => x.Age == age);
        }

        private void CreateStudentCollection()
        {
            _studentsList.Add(new Student() { _age = 10, _name = "Arun" });
            _studentsList.Add(new Student() { _age = 20, _name = "Avinash" });
            _studentsList.Add(new Student() { _age = 14, _name = "Avith" });
            _studentsList.Add(new Student() { _age = 20, _name = "Baskar" });
        }
    }
}

A: Your issue is not reproducible. Are you sure that you have posted the correct XAML markup?
Anyway, your GetStudents method throws an exception because you are trying to cast an IEnumerble<Student> to an ObservableCollection<Student>. This won't work but you could create a new ObservableCollection<Student> and return this one:
public ObservableCollection<Student> GetStudents(int age)
{
    CreateStudentCollection();
    return new ObservableCollection<Student>(_studentsList.Where(x => x.Age == age));
}

If you copy the XAML markup you have posted into a new window and run the code with the above modifiction it should work just fine.


text:
Q: Why do changes to /etc/passwd not take effect? I've edited /etc/passwd by running usermod -s to change my shell. (chsh doesn't work, because it prompts for a password; we SSH in using keys.)
When I disconnect, and reconnect, the change doesn't take effect. I've restarted sshd too, and still nothing.

A: I use ControlMaster, and I wasn't actually disconnecting.
ControlMaster is an SSH configuration option that keeps connections open for a certain time, and can multiplex SSH sessions over the same connection (which avoids key exchanges, which are slow). However, if you ^D from a shell, and then re-run ssh, you've not killed the original connection.
Restarting sshd only restarts the listening process: any in-progress session remain alive, so that doesn't restart the connection either.
Apparently launching a new shell doesn't re-check /etc/passwd for changes.
Solution was just to kill the connection: ssh <hostname> -O exit, and log in again.


text:
Q: Disable Webform button after validation and before postback Using WebForms, how can I have a button, which is disabled, after only IT has been clicked, and also AFTER validation has been passed?
I know there is: Disable asp.net button after click to prevent double clicking
However, there are other postbacks on my page, before the final button press which confirms the booking, and I need these to be allowed.
It's only the final button press that I need to ensure passes validation, but only allows one press, before being disabled.
Code is as follows:
   protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        FinalButton.Attributes.Add("onclientclick", "if(Page_ClientValidate('vg')){this.disabled = true; }");
    }

}
protected void Button1_Click(object sender, EventArgs e)
{
    TextBox1.Text = "Hi";
}
protected void Button3_Click(object sender, EventArgs e)
{
    TextBox1.Text = "";
}

ASPX page:

    <asp:TextBox ID="TextBox1" runat="server" ValidationGroup="vg"></asp:TextBox>

    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Set TextBox1 to Hi" />
    <asp:Button ID="Button3" runat="server" OnClick="Button3_Click" Text="Set TextBox1 to Empty" />

    <asp:Button ID="FinalButton" runat="server" Text="Final Submit" ValidationGroup="vg" />
    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="RequiredFieldValidator" ValidationGroup="vg"></asp:RequiredFieldValidator>

So, the unless the textbox is populated, the "FinalButton" should not submit (this part works).  However, if the textbox is populated, then it should be disabled to prevent double clicks, before posting back - but it doesn't disable, so I presume my code here, is not correct:
FinalButton.Attributes.Add("onclientclick", "if(Page_ClientValidate('vg')){this.disabled = true; }");

The source on the page when it is rendered, shows the button as:
<input type="submit" name="ctl00$MainContent$FinalButton" value="Final Submit" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$MainContent$FinalButton", "", true, "vg", "", false, false))" id="MainContent_FinalButton" onclientclick="if(Page_ClientValidate('vg')){this.disabled = true; }" />

Thank you,
Mark

A: You can see in the rendered button HTML your single quotes are getting changed to ', which is an ASP.NET security feature.  Some posts on SO (like Stop the tag builder escaping single quotes ASP.NET MVC 2) have posted away to get around this, but I personally would NOT take that route.
Note, for both of these examples I added a return false to stop the form submission so you can see the button actually disable. Remove this when you are ready to continue testing your code.
You can either just put your code in the button itself:
<asp:Button ID="FinalButton" runat="server" OnClientClick="if(Page_ClientValidate('vg')){this.disabled = true; return false; }" Text="Final Submit" ValidationGroup="vg" />

This works, but looks nasty. It's cleaner to not have that OnClientClick just add the click event with Javascript:

Ok so once you see that working, and you remove the return false;, you are still going to have issues. Namely that a disabled button doesn't perform a postback in certain browsers. So some browsers will postback, others will act just like it did with the return false;. That's not good.
What is worse is regardless of the browser, ASP.NET is not going to run the click event of a disabled button (if you add something like OnClick="FinalButton_Click" to the button). You can test this out in IE9, since a disabled button will still post back, but you can see your OnClick event won't fire. Chrome on the other hand will just disable your button and not postback.

A: You can use the setTimeout trick to disable the button right after the postback is triggered:

A: After searching for hours I found out that you can use UseSubmitBehavior="false" to allow asp postback to handle the button instead of the normal browser submit. You can read the docs here
This also means your OnClientClick script does not have to return true
<asp:Button ID="btnSave" runat="server"
    Text="Save"
    OnClientClick="this.disabled=true" OnClick="btnSave_Click"
    UseSubmitBehavior="false"/>


text:
Q: Lapply para retirar resultados de teste ADF no R Essa é a minha lista:
mylist=dput(mylist)
list(list(c(30, 50, 35, 25, 45), c(40, 35, 35, 50, 45), c(40,
20, 40, 50, 25), c(35, 45, 45, 45, 40), c(20, 30, 50, 45, 20),
    c(40, 40, 50, 30, 40)), list(c(50, 50, 25, 40, 45, 40, 35,
40, 45, 20), c(40, 35, 40, 40, 45, 30, 20, 50, 35, 25), c(20,
30, 50, 35, 45, 40, 25, 50, 35, 50), c(20, 35, 30, 25, 40, 30,
50, 20, 25, 35), c(40, 25, 25, 20, 50, 30, 50, 40, 35, 35), c(50,
20, 45, 35, 50, 45, 30, 45, 35, 50)), list(c(45, 50, 25, 25,
30, 25, 35, 35, 35, 30, 50, 50, 30, 30, 20), c(40, 20, 35, 35,
50, 20, 25, 30, 35, 20, 40, 20, 45, 30, 20), c(50, 20, 25, 35,
35, 30, 50, 25, 40, 35, 45, 45, 35, 45, 25), c(50, 50, 25, 35,
25, 35, 20, 25, 45, 40, 35, 40, 50, 40, 30), c(50, 25, 20, 30,
40, 45, 40, 50, 35, 40, 30, 45, 35, 50, 40), c(35, 50, 35, 45,
25, 40, 50, 40, 50, 50, 50, 50, 35, 35, 40)), list(c(50, 50,
50, 40, 20, 25, 50, 40, 50, 50, 45, 40, 30, 50, 35, 45, 50, 30,
35, 45), c(45, 20, 25, 20, 25, 30, 20, 30, 45, 25, 50, 30, 30,
25, 50, 45, 20, 45, 45, 50), c(20, 40, 50, 25, 40, 45, 25, 30,
20, 20, 35, 45, 20, 40, 50, 45, 40, 40, 45, 35), c(40, 40, 20,
25, 50, 50, 35, 45, 50, 45, 50, 35, 30, 40, 35, 45, 25, 45, 45,
25), c(20, 25, 35, 45, 35, 40, 40, 35, 35, 40, 30, 30, 40, 50,
25, 40, 30, 25, 20, 40)), list(c(35, 25, 45, 20, 25, 30, 30,
35, 30, 40, 30, 20, 20, 30, 45, 40, 35, 35, 35, 35, 25, 45, 35,
20, 50), c(50, 35, 30, 30, 35, 45, 45, 50, 25, 25, 40, 25, 50,
45, 25, 30, 30, 25, 45, 45, 30, 20, 50, 30, 30), c(35, 40, 50,
25, 40, 45, 30, 25, 50, 25, 35, 50, 50, 50, 25, 50, 20, 50, 40,
25, 25, 35, 20, 20, 50), c(40, 35, 35, 40, 50, 35, 25, 40, 25,
25, 30, 45, 50, 35, 20, 50, 20, 20, 45, 50, 40, 30, 35, 50, 45
), c(40, 25, 50, 50, 20, 50, 25, 50, 40, 30, 30, 50, 45, 45,
40, 45, 20, 20, 45, 35, 45, 50, 40, 40, 35), c(40, 45, 35, 35,
30, 45, 40, 40, 20, 50, 50, 45, 40, 40, 45, 45, 35, 40, 20, 30,
35, 45, 30, 50, 25)))

essa lista tem 5 entradas. Em cada uma dessas 5 entradas eu tenho mais 6 entradas. No meu trabalho cada uma das 5 entradas representa amostras de 5,10, 15, 20 e 25 observações.
Em cada uma das posições mylist[[1]][[1]],mylist[[1]][[2]],mylist[[3]][[1]],mylist[[1]][[4]],mylist[[1]][[5]],mylist[[1]][[6]] (Até a mylist[[5]][[6]]) eu quero calcular um resultado estatistico que é o teste ADF e pegar o pvalue.
Eu consigo fazer isso +- para uma media simples:
resultlist <- lapply(mylist,
            function(x)
            lapply(x, function(y) rep(mean(y), length(y)))
            )

Eu digo +- pq se vcs repararem na resposta a media vem repetida, deveria vir somente um valor.
Como corrijo isso?
Da mesma forma, eu quero fazer o teste adf e retirar o pvalue, e levar somente um valor, e não esse valor repetido.
Abaixo o codigo incluindo o teste adf. Não esta saindo. Alguma ajuda?
 resultlist <- lapply(mylist,
                function(x)
                lapply(x, function(y) rep(adf.test(mylist)$p.value(y), length(y)))
                )

Bom, e o principal, eu preciso manter essa estrutura do Lapply. Meu codigo todo esta em Lapply.
Alguma ajuda?

A: Primeira questão: as médias vem repetidas porque você repete esse valor com a função rep(). Se tirar essa função irá retornar somente um valor por lista:
resultlist <- lapply(mylist,
              function(x)
              lapply(x, function(y) mean(y))
              )

Segunda questão: o resultado do adf.test() é uma lista de 3 tipos de testes (type1, type2, type3). E cada elemento da lista é uma matrix. Para obter então somente o p.value você precisa primeiro selecionar o type (que escolhi de forma arbritária) e depois a posição do p.value na matrix ([1, 3]):
resultlist <- lapply(mylist,
              function(x)
              lapply(x, function(y) aTSA::adf.test(y)$type1[1, 3])
              )


text:
Q: JavaFx: webview print with fit to size 100% To print my html page I use the following code:
  PrinterJob job = PrinterJob.createPrinterJob();
   if (job != null && job.showPrintDialog(null)){
      webView.getEngine().print(job);
      job.endJob();
  }

The problem is that webview changes the scale of printing page. For example, when I print this html page in IE with fit to size 100% I get 16.8 cm. When I print in my java application I get 11.4cm. The size in html file I set in pt - my width is 475pt(A4 width=595pt,so 475pt=16.8cm). How to print in webview with fit to size 100%? Is it possible to do?
P.S. If I understand something wrong->I am asking wrong question, please correct me.

A: There already is a bug report which may be related to your issue.
https://bugs.openjdk.java.net/browse/JDK-8088509
As far as I can tell there is no solution so far.
Michael


text:
Q: spring-amqp RabbitMQ dynamically change publisher-confirms Is there a way to change publisher-confirms per message? We have a rest layer that receives the message and publishes to RabbitMQ. Based on certain message properties, we decide whether publisher confirm is needed or not.
Is there a way to override, publisher-confirms while sending message?

A: No; we have to add a bunch of scaffolding to support returns. Also, channels are cached and there is no way to turn off confirms for a channel once set. We'd have to keep 2 different caches.
If you wish to use conditional confirms, you could define two connection factories (and templates), one with confirms enabled, one not, and select which template to use at runtime.
EDIT
@SpringBootApplication
public class So41131612Application {

    public static void main(String[] args) throws Exception {
        ConfigurableApplicationContext context = SpringApplication.run(So41131612Application.class, args);
        context.getBean("normalTemplate", RabbitTemplate.class).convertAndSend("foo", "foo");
        context.getBean("confirmingTemplate", RabbitTemplate.class).convertAndSend("", "foo", "foo",
                new CorrelationData("foo"));
        Thread.sleep(2000);
        context.getBean(RabbitAdmin.class).deleteQueue("foo");
        context.close();
    }

    @Bean
    public Queue foo() {
        return new Queue("foo");
    }

    @Bean
    @Primary
    public CachingConnectionFactory rabbitConnectionFactory() {
        return new CachingConnectionFactory("localhost");
    }

    @Bean
    public CachingConnectionFactory confirmingCf() {
        CachingConnectionFactory cf = new CachingConnectionFactory("localhost");
        cf.setPublisherConfirms(true);
        return cf;
    }

    @Bean
    public AmqpTemplate normalTemplate(@Qualifier("rabbitConnectionFactory") CachingConnectionFactory normalCf) {
        return new RabbitTemplate(normalCf);
    }

    @Bean
    public AmqpTemplate confirmingTemplate(@Qualifier("confirmingCf") CachingConnectionFactory confirmingCf) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(confirmingCf);
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setConfirmCallback((cd, ack, cause) -> {
            System.out.println("Correlation:" + cd + " ack: " + ack);
        });
        return rabbitTemplate;
    }

}


text:
Q: Perform an operation on a subset of columns where column name contains string? I have df1 and df2. I want to difference them, df_new = df1 - df2. However a few of the columns of df1 and df2 (they have the same columns), I want to do extra operations.
Something like:
df_new = df1 - df2 # element-wise on all rows and cols
df_new[df_new[columns where column.name.contains("price_")] *= 100 # mult every row for these cols by 100
df_new[df_new[columns where column.name.contains("spread_")] /= df1 # element-wise for those cols

I'm not sure if something like is possible or what the proper functions/syntax would be. Basically after forming df_new I just want to go in and conveniently edit some columns, which I identify by a string phrase.

A: You can try:
df_new.loc[:, df_new.columns.str.contains('price_')] *= 100
df_new.loc[:, df_new.columns.str.contains('spread_')] /= df1

Note you may find .str.startswith and .str.endswith helpful as well.

A: IIUC, you can use df.filter.
df.filter(like="price_")

With like it returns all columns that have price_ in their name (substring). For more complex patterns, use regex instead.

A: You need to use str.contains with loc to reach those columns:
df_new.loc[:, df_new.columns.str.contains("price_")] *= 100 # mult every
row for these cols by 100
df_new.loc[:, df_new.columns.str.contains("spread_")] /= df1


text:
Q: Is there any tips tricks , techniques, configurations to improve rendering time of sifr3-r436 text? Is there any tips tricks , techniques, configurations to improve rendering time of sifr3-r436 text?
What is best practices to use sifr3-r436 to get good performance and cross browser rendering?

A: A few tips:

*

*Load sIFR CSS & JavaScript first

*Minimize the Flash movie size by limiting the glyphs embedded in the movie

*Make sure to hide the HTML text to prevent an obvious replacement

*Calculate ratios to improve load experience


text:
Q: XML data to be sorted by HTML Form I would like to do a basic search functionality but the data I am using is XML - How would I got about making a search form that can filter the data from the XML and display it in HTML whether it meets the HTML form's criteria.
I have not yet tried to use a HTML form to display the XML data as I do not know how to do this, therefore I am asking for direction or examples that may be elsewhere in the web, as I ma having trouble doing so.
   <UKPRN>10004048</UKPRN>

   <ACCOMURL>http://www.londonmet.ac.uk/accommodation/</ACCOMURL>

   <PRIVATELOWER>5000</PRIVATELOWER>

   <PRIVATEUPPER>8300</PRIVATEUPPER>

   <COUNTRY>XF</COUNTRY>

   <NSP>1</NSP>

   <Q24>51</Q24>

   <Q24POP>2242</Q24POP>

   <KISCOURSE>

      <TITLE>FdSc Crime Scene and Forensic Investigation</TITLE>

      <UCASCOURSEID>F411</UCASCOURSEID>

      <VARFEE>10</VARFEE>

      <FEETBC>1</FEETBC>

      <WAIVER>0</WAIVER>

      <MEANSSUP>0</MEANSSUP>

      <OTHSUP>0</OTHSUP>

      <ENGFEE>5700</ENGFEE>

   </KISCOURSE>

There is just a basic look at my XML set up - any help is appreciated!
EDIT: Further to the question asked below, The XML data is structured as above, and I wish for some PHP or Html Form to search the Title of the title KISCOURSE and then display relevant searches.

A: Since this is rather a bigger project than a short question my answer just aims to give you some ideas on how I would approach this. Tell me whether you think it is helpful and if you have further questions.
Assuming that you have your data in one XML file, e.g. data.xml, and you have access to PHP and its XSLTProcessor class I would do the following:

*

*Create an HTML form with inputs for the fields you want to query

*Write an XSL transformation to filter data.xml on the wanted parameters

*Write a PHP script that gets parameters from the HTML form, applies them to the transformation, executes it and outputs the result

Tell me if you find this approach suitable for you and I can add more detail. Good luck!


text:
Q: Unclear why aptitude marks package as broken I have a situation where aptitude marks a package cgroup-bin as broken:
$ aptitude search '^cgroup-bin$'
pB  cgroup-bin ...

In its UI, aptitude provides the following explanation:
Some dependencies of cgroup-bin are not satisfied:
* cgroup-bin depends on cgroup-tools

Both dpkg -l cgroup-bin and dpkg -l cgroup-tools  issue dpkg-query: no packages found matching ... because neither package is installed.
Both apt-cache policy cgroup-bin and apt-cache policy cgroup-tools identify version 0.41-6 from the Debian repository as candidate versions.
aptitude show cgroup-bin lists these (relevant) dependencies:
Depends: cgroup-tools

aptitude show cgroup-tools lists those:
Breaks: cgroup-bin (< 0.40~rc1-3~)
Replaces: cgroup-bin (< 0.40~rc1-3~)

I have another machine which has the same properties but where the package is not marked as broken.
What is going on here? Why is package cgroup-bin marked as broken (when from the dependencies it would seem that versions 0.41-6 can live in unison) and how can I remedy the situation?


text:
Q: angular.js:13236 Error: [orderBy:notarray] Expected array but received: This HTML invites a button click:

<button class="btn btn-info" ng-click="ResetEventStation()">
    Choose a different station</button>

Which invokes this function:
$scope.ResetEventStation = function()
{
    localStorage.removeItem("stationId");
    localStorage.removeItem("stationName");
    localStorage.removeItem("isRegistrationStation");

    $scope.stationId = -1;
    $scope.stationName = '';
    $scope.isRegistrationStation = false;
}

I can breakpoint and one-step through the function, but when I step beyond the closing brace, I get

angular.js:13236 Error: [orderBy:notarray] Expected array but received: {"customer_id":97,"event_id":6,"station_id":7,"station_name":"St. Pancras","customer_name":"mawg","event_title":"Event one","token":"20000097-6ee02241-7231-4f8d-9956-5cf5022de147"}
      http://errors.angularjs.org/1.5.0/orderBy/notarray?p0=%7B%22customer_id%22%…%22%2C%22token%22%3A%2220000097-6ee02241-7231-4f8d-9956-5cf5022de147%22%7D
          at angular.js:68
          at angular.js:20410
          at fn (eval at compile (angular.js:14086), :4:200)
          at regularInterceptedExpression (angular.js:15213)
          at Scope.$digest (angular.js:16655)
          at ChildScope.$apply (angular.js:16928)
          at HTMLButtonElement. (angular.js:24551)
          at HTMLButtonElement.dispatch (jquery-2.1.1.min.js:3)
          at HTMLButtonElement.r.handle (jquery-2.1.1.min.js:3)

Googling shows it to be a filter error and, sure enough, the browsers console shows this function, which I presume Angular generated for me:
(function($filter,ensureSafeMemberName,ensureSafeObject,ensureSafeFunction,getStringValue,ensureSafeAssignContext,ifDefined,plus,text
/*``*/) {
"use strict";
var fn=function(s,l,a,i){var v0,v1,v2,v3=l&&('ResetEventStation' in l);v2=v3?l:s;if(!(v3)){if(s){v1=s.ResetEventStation;}}else{v1=l.ResetEventStation;}ensureSafeObject(v1,text);if(v1!=null){ensureSafeFunction(v1,text);v0=ensureSafeObject(v2.ResetEventStation(),text);}else{v0=undefined;}return v0;};return fn;
})

I don't really understand what is happening. Can someone tell me what I am doing wrongly, and how to fix the error?
I can see that {"customer_id":97,"event_id":6,"station_id":7,"station_name":"St. Pancras","customer_name":"mawg","event_title":"Event one","token":"20000097-6ee02241-7231-4f8d-9956-5cf5022de147"} is not an array, but an not sure why it is being referenced.

A: You should look for an orderBy filter in your code and change/remove it. Since, it is trying to sort your array but instead of array you are having that object.
There are two possible ways where you can use this filter:

*

*First, in HTML, using ng-repeat="something in someArray | orderBy: some"

*And, in your AngularJS code, with $filter('orderBy')(...)
Search for these and modify them to have array instead (or remove the filter) to get rid of this error!


text:
Q: Issues awaiting replies in public channel The following code is resulting in no errors to the console. After I type the command, the first message.reply line executes properly, but the bot doesn't seem to acknowledge someone types 'accept' or 'deny'. Been messing with this for quite a long time. I've done commands like this in private messages and it works. But for some reason since this is in a public channel, it doesn't seem to work.
module.exports.run = async(bot, message, args) => {

  //!endbrawl winner [username] loser [username]

  let messageArray = message.content.split(" ")
  let winner = messageArray[2]
  let loser = messageArray[4]

  message.reply(`${message.author} wants to close this brawl with ${winner} as the victor and ${loser} as the loser. \n ${winner}, do you accept the result? If yes, type 'accept'. If not, type 'deny'.`);
  let winnerUser = message.mentions.users.first();
  let filter = m => m.author.id == winnerUser.id;
  message.channel.awaitMessages(filter, {
    maxMatches: 1,
  }).then(collected => {
    if (message.author.bot) return;
    if (collected.first().content === "accept") {
      return message.reply(`${winner} has accepted the proposed result.`)
      // put in code asking loser to agree with proposed result
    } else if (collected.first().content === "deny") {
      return message.reply(`${winner} has denied the proposed result.`)
    } else {
      return message.reply(`${winner}, your reply was invalid.`)
    }
  })
}

I have looked for ways to solve this, but most involve private messaging or what was told doesn't work for me. No errors in any of those attempts. It just seems like it isn't even looking at the replies.
Thanks for any and all help! It is greatly appreciated!

A: message.channel.awaitMessages(filter, {
    max: 1,
  }).then(...);

That max means that the maximun number of messages that will be processed will be 1: that means that if the next message is not sent by the author the bot will stop listening for new messages. The other message could even be your bot's reply, since you're not waiting for that to be finished before setting the awaitMessages.
Try using maxMatches instead of max.
message.channel.awaitMessages(filter, {
    maxMatches: 1,
  }).then(...);

Reference: MessageCollectorOptions

With that said, you want the winner to be able to send that message and so you'll need to change your filter function.
You'll first need to get the User object of the winner, then make the filter so that it checks for their id.
let winnerUser = message.mentions.users.first();
let filter = m => m.author.id == winnerUser.id;

You could also match the id from the plain mention, but I find it easier to use the object instead.


text:
Q: Change grouping based on parameter My intangible asset needs to be grouped based on parameters. The end user will pick one of two options: Roll Forward or Book vs. Tax. These allow the user to toggle between two views based on how they want the data presented.
When Roll Forward is selected the report should group like this:

*

*Company

*

*Amortizable/Unamortizable Assets

*

*Deductible/Non-deductible Assets

*

*Intangible type

When Book vs. Tax is selected:

*

*Company

*

*Intangible type

*

*Location

My understanding is that I am trying to use dynamic grouping. Is there a way to get this behavior into the report?

A: One way to handle this is to make two Subreports, one for each parameter. Design each subreport to display your data and group based on the above structure. Then place them both into their own section. (I put them in Report Footers for this example:)

Then set the Report Footers to Suppress based on what parameter is submitted. For example, Report Footer A would use this code in the Suppress section:
{?MyParameter} <> "Roll Forward"


text:
Q: How to upload an array of images URLs to Firestore? hello how to upload an array of images urls to firestore in react native
i tried this
 state = { photos: [] };

buttonPress() {

const { photos } = this.state;

firebase.firestore().collection('users').doc('images')
.add({ photos });
}

but the image would show like this in firestore database
{
"book": "Robin hood",
"photos": "https://picsum.photos/id/1001/5616/3744",
 }

i would like it to instead show in an array like this in firestore database
{
"book": "Robin hood",
"photos":  [ "https://picsum.photos/id/1001/5616/3744"],
 }

A: This can be achieved by wrapping the photos inside []. Therefore your code would be;
firebase.firestore().collection('users').doc('images')
  .add({ [photos] });
}

Also, incase you want the user to add later and not overwrite the array, I would suggest using set with merge: true.
firebase.firestore().collection('users').doc('images')
  .set({ [photos] }, { merge: true });
}


text:
Q: How to use the data from a list of a class? Currently I'm working on a quiz game using windows form application.
So what I'm confused on is how to assign the data I read from Trivia.cs (from the ListOfData method) to the variables (questionText) and (answers) in TriviaForm, so that it can be passed to the Question.cs to process the data and to figure out which one is the right answer.
I'm just a beginner and this is my high school introductory class so I'd really appreciate the help.
So I made a Trivia class (Trivia.cs) to read the data.
namespace D4
{
    class Trivia
    {
        // Fields
        private const string FileName = "WumpusTrivia.txt";
        private string questionText;
        private string[] answers = new string[4];

        public Trivia()
        {

        }

        /// This method will return the list of data.
        public List<Question> ListOfData()
        {
            List<Question> ls = new List<Question>();
            using (StreamReader sr = new StreamReader(FileName))
            {
                while (!sr.EndOfStream)
                {
                    this.questionText = sr.ReadLine();
                    for (int i = 0; i < 4; i++)
                        this.answers[i] = sr.ReadLine();
                    sr.ReadLine();
                    ls.Add(new Question(this.questionText, this.answers));
                }
            }
            return ls;
        }
    }
}

A Question class (Question.cs) to process the data and to return the values to put into text boxes.
namespace D4
{
    class Question
    {
        private string question;
        private string[] answers = new string[4];
        private int correctAnswer;
        private string[] freeTrivia;
        private Trivia trivia;

        public Question(string question, string[] answers)
        {
            this.trivia = new Trivia();

            this.question = question;
            this.answers = answers;
            for (int i = 0; i < 4; i++)
            {
                if (answers[i].ToString().EndsWith("+"))
                {
                    this.correctAnswer = i;
                    answers[i].ToString().Replace('+', ' ');
                }
            }
        }

        public string QuestionText { get { return this.question; } }
        public string[] Answers { get { return this.answers; } }
        public int CorrectAnswer { get { return this.correctAnswer; } }
        public string[] Freetrivia { get { return this.freeTrivia; } }
    }
}

And a TriviaForm class (TriviaForm.cs) to display the data from the Trivia class in the textboxes.
namespace D4
{
    public partial class TriviaForm : Form
    {
        //// Fields
        private Trivia trivia;
        private Question question;
        private string questionText;
        private string[] answers = new string[4];
        private Question[] data;
        private const int wumpusMaxQuestions = 5;
        private const int hazardAndPurchaseMaxQuestions = 3;

        // Replace these later after finished connecting all objects.
        private bool hazardAndPurchase = false;
        private bool wumpus = false;

        public TriviaForm()
        {
            InitializeComponent();

            this.trivia = new Trivia();
            this.data = trivia.ListOfData().ToArray();
            this.questionText = data[0].ToString();
            for (int i = 0; i < 4; i++)
                this.answers[i] = data[i].ToString();

            this.question = new Question(questionText, answers);

            QuestionOutputter();
        }

        // Displays the questions and answers on the form.
        private void QuestionOutputter()
        {
            this.txtQuestion.Text = question.QuestionText;
            this.txtBoxA.Text = question.Answers[0];
            this.txtBoxB.Text = question.Answers[1];
            this.txtBoxC.Text = question.Answers[2];
            this.txtBoxD.Text = question.Answers[3];
        }
    }
}

Okay sorry for the bad question guys, but I finally figured it out. The problem I was having was with the Question class giving an error. This was due to the fact that I was passing a null to it with my questionText and answers variables in the TriviaForm class.
The code that I had:
this.data = trivia.ListOfData().ToArray();
        this.questionText = data[0].ToString();
        for (int i = 0; i < 4; i++)
            this.answers[i] = data[i].ToString();

was completely wrong. Apparently all I needed was to do a foreach loop instead.
My solution:
this.data = trivia.ListOfData().ToArray();
foreach (Question q in this.data)
        {
            this.questionText = q.QuestionText.ToString();
            for (int i = 0; i < 4; i++)
                this.answers[i] = q.Answers[i];
            this.question = new Question(questionText, answers);
        }

I tried this out and it worked out really well! Sorry for wasting your time.

A: Add a radio button next to each of the answer text boxes and add event handlers to those radio buttons to evaluate whether the selected answer is the correct one.

Something like this may work with your existing code, assuming you put radioButton2 next to txtBoxB, and radioButton3 next to txtBoxC etc:
    private void radioButton2_CheckedChanged(object sender, EventArgs e)
    {
        if (((System.Windows.Forms.RadioButton)sender).Text.Substring(11,1) = this.Question.correctAnswer + 1) {
            CorrectAnswer_DoSomethingHere();
        } else {
            Incorrect_DoSomethingElse();
        }
    }


text:
Q: phantomjs with selenium crypto mining not working hashes-per-second remains 0 H/s when running the script and takes positive if running it on local machine (laptop).  Hints?
library(wdman)
library(RSelenium)
pjs <- wdman::phantomjs(verbose = TRUE)
rd <- RSelenium::remoteDriver(port = 4567L, browserName = "phantomjs")
rd$open(silent = FALSE)
rd$navigate('https://www.monero.crypto-webminer.com/monero.html')

# adress
  w <- rd$findElement(using = 'xpath','//*[@id="wallett"]')
  rd$executeScript('document.getElementById("wallett").textContent="<my_wallet_adress>"', args=list(w))

# threads
  w <- rd$findElement(using = 'xpath','//*[@id="threads"]')
  rd$executeScript('document.getElementById("threads").textContent="<cores>"', args=list(w))

# start
  w <- rd$findElement(using = 'xpath','//*[@id="start"]')
  rd$executeScript('document.getElementById("start").click()', args=list(w))

# prints
  print(rd$findElement(using = 'xpath','//*[@id="hashes-per-second"]')$getElementText())
  print(rd$findElement(using = 'xpath','//*[@id="wallett"]')$getElementText())
  print(rd$findElement(using = 'xpath','//*[@id="threads"]')$getElementText())