text:
Q: Script error : "Uncaught SyntaxError: Unexpected identifier" I know this question has been asked several times, I tried to find a solution but I found nothing. I am trying to create a graph chart.js.
the part that contains the error is that of 'option:', because when I delete it all works well, but despite that I check well, I do not find the error
here is my error:
Uncaught SyntaxError: Unexpected identifier

here is my script:
<script>

var timeFormat = 'MM/DD/YYYY HH:mm:ss';
function newDateLabel(dateObject) {
    val_date = moment(dateObject).format(timeFormat);
    return new Date(val_date)
}

var config = {
    // The type of chart we want to create
    type: 'line',

    data: {
        labels: [
            %for time in list_date:
                newDateLabel('{{time}}'),
            %end
        ],

        datasets: [{
            label: 'Demo',

            fill: false,

            data: [
                %for val in list_valeurs:
                    {{val}},
                %end
            ],

            borderWidth: 1
        }]
    },

    options: {
        title: {
            text: 'Chart.js Time Scale'
        },

        scales: {

            xAxes: [{
                type: 'time',
                time: {
                    format: timeFormat,
                    tooltipFormat: 'll HH:mm'
                },
                scaleLabel: {
                    display: true,
                    labelString: 'Date'
                }
            }],

            yAxes: [{
                scaleLabel: {
                    display: true,
                    labelString: 'value'
                }
            }]

        },
    }

};

window.onload = function() {
    var ctx = document.getElementById('canvas').getContext('2d');
    window.myLine = new Chart(ctx,config);

};
</script>

could you help me please ?

A: missing a comma before options:
}

options: {


text:
Q: Buildfire - How to get rid of thumbnail component defaults I am using the BuildFire thumbnail component.  In the documentation it says that the constructor either takes a url string, or an object with optional properties to augment the presentation of the component.  Two of these properties in the settings object are title and dimensionLabel.
Are the defaults hardcoded currently to override anything passed in?  I have passed settings objects with different titles and dimensionLabels, and still get the defaults.  Is there a way to completely get rid of the title?

A: Here are the Docs: https://github.com/BuildFire/sdk/wiki/BuildFire-Thumbnail-Component
Here is the source code: https://github.com/BuildFire/sdk/blob/master/scripts/buildfire/components/images/thumbnail.js
looks like these are your 3 options
{
imageUrl : ""
title : ""
dimensionsLabel : ""
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to retrieve the full paths of javascript event.DataTransfer object passed into c++ npapi plugin's function? I have a function exposed to javascript:
bool handleDrop( const NPVariant * args, uint32_t argCount, NPVariant* result){
     //Extract the full paths from the DataTransfer object passed into args
}

which gets called from Javascript from an onDrop(event) handler:
plugin.handleDrop(event.DataTransfer);

I've had success with the ActiveX version with:
void handleDrop (IDispatch* arg){
     //Extract paths using QueryInterface for IID_IHTMLDataTransfer,
     // IID_IServiceProvider, IID_IDataObject  which gets dropfiles list
}

I want to do the same thing for the NPAPI version.
According to MDN: https://developer.mozilla.org/En/DragDrop/DataTransfer
The datatransfer object looks like it implements the nsIDOMDataTransfer interface.
Is this even possible to extract the full dropped files path from the datatransfer object with NPAPI, and how do you actually do the conversions to get there?
Thanks.

A: Well, the minor issue you run into here is that nsIDOMDataTransfer is not actually NPAPI. That's XPCOM, which is a different (but in some historical cases related) thing. If you look at the docs for NPN_GetValue you'll find that NPNVDomWindow, which once could give you a XPCOM reference to the DOM window, is no longer supported as of FireFox 3.6. Similarly, you can't pass in objects from javascript and get XPCOM references to them as of the same time period.
Part of the reason for this is that XPCOM as a method of implementing a scripting interface on a plugin has been deprecated for years and people were still trying to use it. No other NPAPI browser supports it, they all use NPRuntime.
Anyway, the long and short of things is that if you can't get the information you need with javascript you won't be able to with the plugin either.  The good news is that a plugin can be a drag and drop target. The bad news is I've never needed to so I don't know how =] That might be a reasonable choice for another question.
Sorry I can't be much help


text:
Q: How can i clear the Directory dropdown for Find in Files? I created an Autoit Script to assist me in my work by running a string in Notepad++'s File in Files against multiple directories.
during testing however it did enter some bugged text in some fields. while most are just text boxes and thus not a problem the Directory: dropdown/text box has saved some of these bugged entries in the dropdown like

BalanceRuleCatCodesD:_Work\Automation\ks\Azure\rptObjectAnalysis

aside from the start of that the \ks\ part is actually missing a chunk of the string that was supposed to be inputted
I want to know how i can clear the Directory dropdown for Find in Files without needing to uninstall and reinstall it

A: Open config.xml file (it is in the same directory as file which opens on menu Settings > Edit Popup ContextMenu) and delete all unnecessary Path entries, then save and restart Notepad++.
The following image shows where five of them near the beginning of the file:

*

*you are editing the config of the editor itself so make sure that (if this is not obvious)

*

*you exited the Notepad++ before editing its config file

*you are editing the file in some different editor

*you start Notepad++ only after you saved the updated config


text:
Q: setTimeLimit fails to terminate idle call in R I would like to use setTimeLimit to abort operations that are stuck waiting (idle) after n seconds. Below a toy example in which Sys.sleep is a placeholder call that is idle:
testlimit <- function(){
  setTimeLimit(elapsed=3, transient=TRUE);
  Sys.sleep(10);
}

system.time(testlimit());

However this is giving inconsistent results. On windows and in r-studio server (linux) the call is correctly aborted after 3 seconds win video. However, when I run this in a terminal session in either on linux or osx, the timeout is not triggered until after Sys.sleep() and the total script takes 10 seconds to complete.
What causes this difference? Is there something I can set in my terminal R session such that the time limit is triggered? I am using Ubuntu 13.04 amd64, R version 3.0.1 RC, and osx 10.8

A: The question was answered by Simon Urbanek on the r-devel mailing list. Below a copy of his response for future reference:

What causes this difference?

The time limit can only be checked in R_ProcessEvents() so for all practical purposes it can be only triggered by interruptible code that calls R_CheckUserInterrupt().
Now, it is entirely up to the front-end to decide how it will the the event loop. For example the terminal version of R has no other interrupts to worry about other than input handlers which trigger asynchronously, so it doesn't need to do any polling. Sys.sleep() only triggers on input handlers, so if you don't have any external event source hook as input handler, there is no reason to process any events so Sys.sleep() won't see any reason to check the time limit.

Is there something I can set in my terminal R session such that the time limit is triggered?

On OS X it's actually very easy: quartz(); dev.off() will do the trick. The reason is that Quartz needs to force the event loop in order to process events from the window asynchronously. It does so by installing a timer-based input handler. This handler will make sure that Sys.sleep() will wake up every 100ms (you can change the value using QuartzCocoa_SetLatency) so it will timeout with that resolution:
> testlimit <- function(){
+  setTimeLimit(elapsed=3, transient=TRUE);
+  Sys.sleep(10);
+ }
> system.time(testlimit());
Error in Sys.sleep(10) : reached elapsed time limit
Timing stopped at: 0 0.001 10.001
> quartz(); dev.off()
null device
          1
> testlimit <- function(){
+  setTimeLimit(elapsed=3, transient=TRUE);
+  Sys.sleep(10);
+ }
> system.time(testlimit());
Error in Sys.sleep(10) : reached elapsed time limit
Timing stopped at: 0.002 0.003 3.019

On Linux, there is no built-in timer, so you'd have to add an input handler that will pre-empt Sys.sleep(). If you want a constant timer, you can simply borrow the code from Quartz (have a look at QuartzCocoa_SetupEventLoop in src/library/grDevices/src/qdCocoa.m) or the CarbonEL package. It's really just a pipe that is added as an input handler into which you write asynchronously when you want to wake up the event loop. On top of my head I can't think of a built-in solution in R at this point (even though it could be argued that R might install a handler itself when the limit is set ...).
But note that this is really just a special case of of Sys.sleep(). If you actually run R code, then ProcessEvents is triggered automatically during the evaluation (or in interruptible C code).
Cheers,
Simon

A: This is an interesting problem, which I also encountered. Jereon's solution above does not work, however, if your function executes a subprocess, e.g. through system(). In that case, there are no time checks until after the full process has executed (which in my case can sometimes take hours).
However, I found an alternate solution for anyone else who might have the same issue. What I did was set wait = FALSE in the system() call, and then force an evaluation of whether or not the script was done every 1 s. It requires you adding some external side-effect to your script, such as creating a temporary file when it is complete.
An edited version of Jeroen's answer shows this below.
testlimit <- function() {
  setTimeLimit(elapsed = 3, transient = TRUE)
  system("sleep 10 && touch done", wait = FALSE)
  while (!file.exists("done")) {
    Sys.sleep(1)
  }
}
system.time(testlimit())
# Error in Sys.sleep(1) : reached elapsed time limit
# Timing stopped at: 0.008 0.005 3.009


text:
Q: Cocos2dx Android how to use .so instead of .jar library libcocos2dx.jar, use something like libcocos2dx.so Is it possible and if so how do you use/reference the .so version of the cocos2d-x library instead of the libcocos2dx.jar as most tutorials tell you to do. ie cocos2d-x has some project directory called Android and there's a project there with java code that will compile and create a libcocos2dx.jar file which I can then reference in my own project.
But my question is why reference .jar java library instead of .so library, so how do I reference in my own project so that I use something like libcocos2dx.so instead of referencing library project libcocos2dx.jar?
I guess I'm thinking the performance will be better if I use .so native library.

A: Forgot I even posted this, anyway in case helps others, you can simply extract JAR contents and get the .so from there and put it in libs and there edit the main activity java code to reference it that way. Related helpful links:
*.so library from included *.jar involves UnsatisfiedLinkError
How to bundle a native library and a JNI library inside a JAR?
Not really sure if there's any performance impact to bundling the .so inside jar or not and not sure what problem if any that may cause if the .so inside is too platform specific etc, so I prefer to keep .so's outside of jars, directly in lib folder.


text:
Q: What routing setting do to ping other machines on other subnets through VPN? To help explain my problem, I drew a diagram:
net draw
What I've managed to do so far is: I can ping the 192.168.200.101 machine from the 192.168.100.200/192.168.50.1 machine. To do this, I run the command on the 192.168.100.200/192.168.50.1 machine:
route add -net 192.168.200.0/24 gw 192.168.50.1

That actually seemed pretty strange to me, because I actually thought that as long as I didn't execute this command on 192.168.50.2/192.168.100.100
route add -net 192.168.50.0/24 gw 192.168.200.101

the ping described above shouldn't work. Why is that still working?
But what I can't definitely do is when I try to ping the 192.168.200.100 or 192.168.200.1 machine from the 192.168.100.200/192.168.50.1 machine. I've tried different commands but still fail, can anyone help me which command I have to execute in the routing table on 192.168.50.2/192.168.100.100/192.168.200.101 to get this working?

A: I don't understand why you have so many subnets in such a small network.
Your routers might perhaps be better configured as
bridge/access-path rather than as DHCP servers.
Anyway, to make everything into one big network doesn't require routes.
All you need to do is define all subnets with a netmask of 255.255.0.0.
This will convert everything into just one 192.168.x.x network.


text:
Q: Resize an Image that has been uploaded as multipart/form-data in a WebAPI controller I am getting an image which has been uploaded to a Web API method using multipart/form-data using await Request.Content.ReadAsMultipartAsync(provider) as follows:
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider);

foreach (MultipartFileData item in provider.FileData)
{
    string name = item.Headers.ContentDisposition.FileName.Replace("\"", "");
    newFileName = Guid.NewGuid() + Path.GetExtension(name);
    File.Move(item.LocalFileName, Path.Combine(rootPath, newFileName));
    Uri baseuri = new Uri(Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.PathAndQuery, string.Empty));
    string fileRelativePath = rootPath + newFileName;
    Uri fileFullPath = new Uri(baseuri, VirtualPathUtility.ToAbsolute(fileRelativePath));
    savedFilePath.Add(fileFullPath.ToString());
    Dictionary<string, string> dictionary = new Dictionary<string, string>();
    dictionary.Add(fieldID, newFileName);
    HttpContext.Current.Session[fieldID] = dictionary;
}

I need to resize the image before saving it to disk. I am not sure if I can do this at run-time. Any Ideas?


text:
Q: How do interact with a price-slider with 2 handle in Cypress? now i can  interact  with price-slider but price filtration not impacted as attached
- price-slider handle low
- price-slider handle high ,
site : https://www.tajawal.ae/en/flights/DXB-RUH/2019-03-30/Economy/1Adult
HTML

cypress step
 cy.get('#content-section div.horizontal-slider')
            .find('div.handle.handle-1').invoke('attr', 'style', "position: absolute; z-index: 1; left: 150.025px; will-change: left;").trigger('change')
        cy.get('#content-section div.horizontal-slider')
            .find('div.handle.handle-0').invoke('attr', 'style', "position: absolute; z-index: 1; left: 56.025px; will-change: left;").click()

A: It isn't related to Cypress. Basically, you're missing how a slider updates when you're interacting with it:

*

*(in the Javascript code of the page, not in Cypress) the script that needs to manage the slider registers some event listeners (such as mousedown, mousemove, mouseup or touchstart, touchmove, touchend etc.)

*when the user interacts (step 0) with the handle the event callbacks are invoked and they

*

*1 - calculate a percentage value that indicates how much the handle has been dragged

*2 - update the left property of the handle element itself

*3 - update the bar background

*4 - finally, they invoke the callback that the developer passed (to update the rest of the UI accordingly to the handle drag)

What you're doing with Cypress is basically changing the result of the handle drag. You're changing the result of step 4 but the result only... You, instead, need to hack step 1 or act as the user and replicate step 0 (that's what you're trying to accomplish in your example).
So: I can you accomplish it with Cypress? You need to trigger the events listened by the script of the app (mousedown, mousemove etc.). Take a look

*

*at the documentation

*at an example

*an issue about that with some more examples

Let me know if you need something more


text:
Q: Swapping out an array (nested?) for values from an XML doc (client side scripting only) I'm an absolute newbie with javascript, but I'm just trying to tweak JPlayer to use an XML file for the playlist instead of the hard-coded playlist. So, here's the bit of code that creates the playlist:
//<![CDATA[
$(document).ready(function(){

    var Playlist = function(instance, playlist, options) {
        var self = this;

        this.instance = instance; // String: To associate specific HTML with this playlist
        this.playlist = playlist; // Array of Objects: The playlist
        this.options = options; // Object: The jPlayer constructor options for this playlist

        this.current = 0;

        this.cssId = {
            jPlayer: "jquery_jplayer_",
            interface: "jp_interface_",
            playlist: "jp_playlist_"
        };
        this.cssSelector = {};

        $.each(this.cssId, function(entity, id) {
            self.cssSelector[entity] = "#" + id + self.instance;
        });

        if(!this.options.cssSelectorAncestor) {
            this.options.cssSelectorAncestor = this.cssSelector.interface;
        }

        $(this.cssSelector.jPlayer).jPlayer(this.options);

        $(this.cssSelector.interface + " .jp-previous").click(function() {
            self.playlistPrev();
            $(this).blur();
            return false;
        });

        $(this.cssSelector.interface + " .jp-next").click(function() {
            self.playlistNext();
            $(this).blur();
            return false;
        });
    };

    Playlist.prototype = {
        displayPlaylist: function() {
            var self = this;
            $(this.cssSelector.playlist + " ul").empty();
            for (i=0; i < this.playlist.length; i++) {
                var listItem = (i === this.playlist.length-1) ? "
" : "
";
                listItem += ""+ this.playlist[i].name +"";

                // Create links to free media
                if(this.playlist[i].free) {
                    var first = true;
                    listItem += "
(";
                    $.each(this.playlist[i], function(property,value) {
                        if($.jPlayer.prototype.format[property]) { // Check property is a media format.
                            if(first) {
                                first = false;
                            } else {
                                listItem += " | ";
                            }
                            listItem += "" + property + "";
                        }
                    });
                    listItem += ")";
                }

                listItem += "
";

                // Associate playlist items with their media
                $(this.cssSelector.playlist + " ul").append(listItem);
                $(this.cssSelector.playlist + "_item_" + i).data("index", i).click(function() {
                    var index = $(this).data("index");
                    if(self.current !== index) {
                        self.playlistChange(index);
                    } else {
                        $(self.cssSelector.jPlayer).jPlayer("play");
                    }
                    $(this).blur();
                    return false;
                });

                // Disable free media links to force access via right click
                if(this.playlist[i].free) {
                    $.each(this.playlist[i], function(property,value) {
                        if($.jPlayer.prototype.format[property]) { // Check property is a media format.
                            $(self.cssSelector.playlist + "_item_" + i + "_" + property).data("index", i).click(function() {
                                var index = $(this).data("index");
                                $(self.cssSelector.playlist + "_item_" + index).click();
                                $(this).blur();
                                return false;
                            });
                        }
                    });
                }
            }
        },
        playlistInit: function(autoplay) {
            if(autoplay) {
                this.playlistChange(this.current);
            } else {
                this.playlistConfig(this.current);
            }
        },
        playlistConfig: function(index) {
            $(this.cssSelector.playlist + "_item_" + this.current).removeClass("jp-playlist-current").parent().removeClass("jp-playlist-current");
            $(this.cssSelector.playlist + "_item_" + index).addClass("jp-playlist-current").parent().addClass("jp-playlist-current");
            this.current = index;
            $(this.cssSelector.jPlayer).jPlayer("setMedia", this.playlist[this.current]);
        },
        playlistChange: function(index) {
            this.playlistConfig(index);
            $(this.cssSelector.jPlayer).jPlayer("play");
        },
        playlistNext: function() {
            var index = (this.current + 1 < this.playlist.length) ? this.current + 1 : 0;
            this.playlistChange(index);
        },
        playlistPrev: function() {
            var index = (this.current - 1 >= 0) ? this.current - 1 : this.playlist.length - 1;
            this.playlistChange(index);
        }
    };

    var mediaPlaylist = new Playlist("1", [

        {
            name:"song1",
            mp3: "song1.mp3",
            poster: "http://www.jplayer.org/video/poster/Incredibles_Teaser_640x272.png"
        },
            {
            name:"song2",
            mp3: "song2.mp3",
            poster: "http://www.jplayer.org/video/poster/Incredibles_Teaser_640x272.png"
        },
            {
            name:"song3",
            mp3: "song3.mp3",
            poster: "http://www.jplayer.org/video/poster/Incredibles_Teaser_640x272.png"**
        }

    ], {
        ready: function() {
            mediaPlaylist.displayPlaylist();
            mediaPlaylist.playlistInit(false); // Parameter is a boolean for autoplay.
        },
        ended: function() {
            mediaPlaylist.playlistNext();
        },
        swfPath: "js",
        supplied: "ogv, m4v, oga, mp3"
    });
});

The part that starts with "var mediaPlaylist" is the only section i need to change. Instead of having the keys/values as name: songname, mp3: mp3, etc., I want it to pull these values from an XML file, or better yet, just push them into the array from an XML that looks like:
<song>songname</song>
<mp3>file.mp3</mp3>

The thing that's mostly confusing me here is how that function/array is set up...too many curly braces and brackets to wrap my head around. How do I get into this without breaking it?

A: If you have a server side XML playlist file in the form:
<?xml version="1.0" encoding="UTF-8"?>
<playlist>
  <entry>
    <song>songname</song>
    <mp3>file.mp3</mp3>
  </entry>
  <entry>
    <song>songname2</song>
    <mp3>file2.mp3</mp3>
  </entry>
</playlist>

then you can load this from the client via AJAX and create a JSON array from the XML. The following example uses the jQuery JavaScript framework and also the jquery-json plugin (only to format the Array nicely as JSON). You should be able to run this on Chrome or Firefox as both have a console (accessed by pressing F12 in the browser) in which I am outputting the JSON array.
Note: You could change console.log(...) to alert(...) if you don't use either of those browsers.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <title>Title</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

Credit to How to return an array from jQuery ajax success function properly? answer as I used that approach to return a value from the jQuery $.ajax success method.
You will have to refactor the var mediaPlaylist = new Playlist() constructor into the callback function though as you cannot return the playlist value from the callback (see How can I catch the return value from the result() callback function that I'm using?)
Hope this helps :-)


text:
Q: How do I properly configure a Golang gorilla/pat router to serve static asset folders? I have two html files that are parsed as follows:
var LoginTemplate = template.Must(template.ParseFiles(
    "views/_base.html",
    "views/login.html",
))

And executed as such:
func LoginFormHandler(w http.ResponseWriter, r *http.Request, ctx *models.Context) error {
    err := LoginTemplate.Execute(w, ctx)

    if err != nil {
        http.Error(w, err.Error(), 404)
    }
    return nil
}

Here are the contents of _base.html:
<!DOCTYPE html>
<html lang="en">

  <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <!-- Meta, title, CSS, favicons, etc. -->
      <meta charset="utf-8">

      <title>{{ template "title" . }}</title>

      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      {{ template "styles" . }}
      {{ template "scripts" . }}
  </head>

  {{ template "content" . }}

</html>

The templates specified above are all defined in login.html.  For example, "styles" wraps all of my CSS links, etc. In my main function, I use a gorilla/pat router to handle several page requests to the server.  Additionally, I want to serve my static assets folders like this:
router.PathPrefix("/assets/").Handler(http.StripPrefix("/assets/", http.FileServer(http.Dir("./assets/"))))

  if err := http.ListenAndServe(":"+settings.Server.Port, router); err != nil {
        panic(err)
  }

However, upon building and running my program, then navigating to local host, I see that none of the CSS or js appears to be rendering.  My css and js folders are in this tree:

ROOT/

assets/

css/
      js/


text:
Q: Read an encrypted value across machines I'm trying to write out encrypted data in such a way that the same user account (on a domain) can read the data from a different machine than the one that wrote it - but only that user can. It looks like the System.Security.Cryptography.ProtectedData class doesn't work that way. It's a command line tool.
var encryptedData = ProtectedData.Protect(data, null, DataProtectionScope.CurrentUser);

Is there another way to encrypt data with .Net that will allow such access?

A: You can use System.Web.Security.MachineKey but you have to make sure that the applications have the same configuration in their respective app.config/web.config files for the machineKey section. It can be found here in the configuration:
<configuration>
  <system.web>
    <machineKey decryption="[type]" decryptionKey="[value]" validation="[value]" validationKey="value" />

There are plenty of tools you can use to generate the values including IIS if you have an asp.net site configured.
Example with an actual key I generated from IIS in section ASP.NET => Machine Key.
static void Main(string[] args)
{
    var encrypted = Encrypt("this will be encrypted");
    Console.WriteLine("Encrypted base64: " + encrypted);
    Console.WriteLine();

    var unencrypted = Unencrypt(encrypted);
    Console.WriteLine("Decrypted: " + unencrypted);

    Console.ReadLine();
}

static string Encrypt(string valueToEncrypt)
{
    var toEncrypt = System.Text.Encoding.UTF8.GetBytes(valueToEncrypt);
    var encryptedData = System.Web.Security.MachineKey.Protect(toEncrypt, null);
    var result = Convert.ToBase64String(encryptedData);
    return result;
}

static string Unencrypt(string value)
{
    var toUnencrypt = Convert.FromBase64String(value);
    var deencryptedData = System.Web.Security.MachineKey.Unprotect(toUnencrypt, null);
    var originalValue = System.Text.Encoding.UTF8.GetString(deencryptedData);
    return originalValue;
}


text:
Q: What does the property losses of the Bayesian layers of TensorFlow Probability represent? I am running the example code on Bayesian Neural Network implemented using Tensorflow Probability.
My question is about the implementation of the ELBO loss used for variational inference.  The ELBO equals the summation of two terms, namely neg_log_likelihood and kl implemented in the code. I have difficulty understanding the implementation of the kl term.
Here is how the model is defined:
with tf.name_scope("bayesian_neural_net", values=[images]):
  neural_net = tf.keras.Sequential()
  for units in FLAGS.layer_sizes:
    layer = tfp.layers.DenseFlipout(units, activation=FLAGS.activation)
    neural_net.add(layer)
  neural_net.add(tfp.layers.DenseFlipout(10))
  logits = neural_net(images)
  labels_distribution = tfd.Categorical(logits=logits)

Here is how the 'kl' term defined:
kl = sum(neural_net.losses) / mnist_data.train.num_examples

I am not sure what neural_net.losses is returning here, since there is no loss function defined for neural_net. Clearly, there will be some values returned by neural_net.losses, but I don't know what is the meaning of returned value. Any comments on this?
My guess is the L2 norm, but I am not sure. If that is the case, we are still missing something. According to the VAE paper, appendix B, the authors derived the KL term when the prior is standard normal. It turns out to be pretty close to an L2 norm of the variational parameters except there are additional log variance terms and a constant term. Any comments on this?

A: The losses attribute of a TensorFlow Keras Layer represents side-effect computation such as regularizer penalties. Unlike regularizer penalties on specific TensorFlow variables, here, the losses represent the KL divergence computation. Check out the implementation here as well as the docstring's example:

We illustrate a Bayesian neural network with variational inference, assuming a dataset of features and labels.
  import tensorflow_probability as tfp
  model = tf.keras.Sequential([
      tfp.layers.DenseFlipout(512, activation=tf.nn.relu),
      tfp.layers.DenseFlipout(10),
  ])
  logits = model(features)
  neg_log_likelihood = tf.nn.softmax_cross_entropy_with_logits(
      labels=labels, logits=logits)
  kl = sum(model.losses)
  loss = neg_log_likelihood + kl
  train_op = tf.train.AdamOptimizer().minimize(loss)

It uses the Flipout gradient estimator to minimize the Kullback-Leibler divergence up to a constant, also known as the negative Evidence Lower Bound. It consists of the sum of two terms: the expected negative log-likelihood, which we approximate via Monte Carlo; and the KL divergence, which is added via regularizer terms which are arguments to the layer.


text:
Q: http request interceptor - restful web service using cxf Trying to add headers to every request that my restful service receives. The below inbound http interceptor gets invoked, but does not add the header.
    package com.client.interceptors;

    import java.util.Collections;
    import java.util.List;
    import java.util.Map;

    import org.apache.cxf.interceptor.Fault;
    import org.apache.cxf.message.Message;
    import org.apache.cxf.phase.AbstractPhaseInterceptor;
    import org.apache.cxf.phase.Phase;

    public class ClientInterceptor extends AbstractPhaseInterceptor<Message> {
        public ClientInterceptor() {
            super(Phase.PRE_INVOKE); // Put this interceptor in this phase
            System.out.println("inside constructor");
        }

        public void handleMessage(Message msg) throws Fault {
            // process the message

            System.out.println("inside interceptor");
            Map<String, List> headers = (Map<String, List>) msg
            .get(Message.PROTOCOL_HEADERS);

            headers.put("token",
            Collections.singletonList("abcd1234xyz56sa"));

            msg.put(Message.PROTOCOL_HEADERS, headers);

        }
    }

How can this be achieved?

A: Well ya i have one solution for the same. look this. it might help.
Client client = Client.create();
     WebResource webResource =client.resource("URL");

     MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
     queryParams.add("json", js); //set parametes for request

     appKey = "Addkey " + appKey; // appKey is unique number

     //Get response from RESTful Server get(ClientResponse.class);
     ClientResponse response = null;
     response = webResource.queryParams(queryParams)
                            .header("Content-Type", "application/json;charset=UTF-8")
                            .header("Authorization", appKey)
                            .get(ClientResponse.class);

     String jsonStr = response.getEntity(String.class);


text:
Q: RS485 IC Termination Resistor Configuration I've made a mistake on a design, that went into production...
It was built like the drawing on the left, with R702 to 5V and R703 to GND, it should have been backwards... like the drawing on the right.
The thing is... the board passed all the tests, the RS485 communication works fine.
I wan't to know if this difference could result in errors in communication/damage to the circuit if it is left unchanged, or if it's irrelevant.
This board was designed by several people, the desition to add R702 and R703 wasn't mine, and I don't understand why they are there (datasheet for SN75176B doesn't uses them in any case). So a second, and probably more interesting question, would be: why are those resistors there in the first place? What's their function?

A: Typically resistors disposed like that are intended to put a differential voltage (within the acceptable common mode range) on the RS-485 receiver that is large enough to drive the output into a known state with the bus open, however they are too large to reliably do that with the 75176, so they don't do much of value. For more appropriate value resistors Rf, the termination resistor Rt has to be increased such that:
\$\tfrac{1}{Z_0}= \tfrac{1}{R_T} + \tfrac{2}{R_F} \$
.. to match the characteristic impedance of the twisted pair.
The amount of offset they add (~30mV with the cable open) is less than the typical hysteresis of 50mV, let alone whatever offset the receiver has (<200mV) and noise immunity.
Since those resistors are the opposite of the usual bus idle state that may be an error. You can replace the 75176s in your system with similar devices (eg. SN65HVD12) that build in an offset voltage (of the usually desired polarity) if you want that functionality with your current layout (and simply don't populate the 10K resistors). Of course all the receivers have to have this bias built in.
Here is the usual connection scheme from this TI document:

A: The resistors are there as a Failsafe:

Failsafe
  For RS-485 receiver inputs between -200mV and +200mV, the output is undefined. That is, if the differential voltage on the RS-485 side of a half-duplex configuration is 0V, and no master transceiver is driving the line (or a connection has come loose), then a logic "high" output is as probable as a logic "low." To ensure a defined output under these conditions, most of today's RS-485 transceivers require failsafe bias resistors: a pullup resistor on one line (A) and a pulldown on the other line (B), as shown in Figure 1. Historically, the failsafe bias resistors on most schematics were labeled 560Ω, but to reduce power loss (when terminating one end only) this value can be increased to approximately 1.1kΩ. Some designers terminate both ends with resistor values between 1.1kΩ and 2.2kΩ. The trade-off is noise immunity versus current draw.

https://www.maximintegrated.com/en/app-notes/index.mvp/id/1090
But they do seem reversed of what is usually used, with A high and B low.

A: Presumably whoever put the resistors in the design wanted to prevent the lines floating when none of the drivers on the lines are enabled - essentially a 2.5V bias (rather than letting the lines theoretically go close to +5V or GND, which may help ensure correct operation of the IC, but in practice you might not notice a difference). It should not matter which one (A or B) is connected to +5 and which to GND. Either circuit should be fine.

it should have been backwards... like the drawing on the right

I'd question where this information came from...

A: Those resistors serve two basic functions:

*

*As a failsafe, to guarantee a particular line status when there is nothing connected.

By going against the general convention, it is clear that the designers intentionally wanted a particular state in this condition which is different from what is commonly used. Very likely to either (1) be able to distinguish this condition from an idle bus, or (2) set a defined condition with larger value resistors that exploits the noise margin behavior of the ICs.

*

*As bleed resistors, to control the differences in common mode without having to connect the grounds.

This is normally done in differential protocols to save an extra wire and avoid the presence of ground loops. Those resistors basically place a 10kohm impedance (5k in each side) between grounds. Modern RS485 transceivers can generally withstand common mode voltages several volts beyond their rails. So a relatively large impedance between grounds can be easily tolerated.
Given their large value (100:1 with respect to the termination) these would not affect communications at all. I would still look at the transceiver datasheet, and verify the specs on common mode voltage range and the behavior when the lines are left floating.

A: In some architecture of U(S)ARTS, when the line is floating, you might get data in MCU side, the pull up/down resistor imply that input voltage is zero and start bit is transferred, In this condition based on configuration of the module might send this data to MCU or discard it because the stop bit not set.
check that you MCU is not interrupted with a low voltage in Rx pin of MCU.


text:
Q: Putting two pieces of code together to make it function I have multiple pieces of code here and am having issues putting them together so my function will actually run.
I have a function:
def getGenes(spliced, infile, outfile):

that has an optional first parameter '-s', that when inputted by a user indicates a 'switch' calling for the 'spliced genes sequence. Therefore, I followed it with this (additionally, when run. sys.agrv[1] = spliced sys.argv[2] = infile and sys.argv[3] = outfile):
import sys
spliced = False
if '-s' in sys.argv:
    spliced = True
    infile, outfile = sys.argv[2:]

Now, whether or not the file contains the switch I want to write the following from the infile to the outfile:
fp = open(infile, 'r')
for line in fp:
    line = line.replace(',',' ')
    tokens = line.split()
    if '-s' in sys.argv and r:
        wp.write('>'+tokens[0]+'|'+tokens[1]+'('+tokens[2]+')'+':'+int(tokens[3])+'-'+int(tokens[4])+'|'+int(tokens[5])+'-'+int(tokens[10])+','+int(tokens[8])+'-'+int(tokens[11]))
    else:
        wp.write('>'+tokens[0]+'|'+tokens[1]+'('+tokens[2]+')'+':'+int(tokens[3])+'-'+int(tokens[4]))

the first statement should be written when the spliced parameter is given, the second (else part) should be written when the spliced parameter is not given). This code above creates the information line for the sequence that is to follow on the next line of the outfile.
Following this, depending on whether a line in the file contains a '+' or a '-' at a specific spot, another file is accessed to pull out a string at certain coordinates. This part that is taken out should be written directly under the corresponding line above. So, I should have a '+' and '-' part for both the spliced and unspliced parameters. I have the following code:
fp2 = open('chr22.fa', 'r')
for line in fp2:
    newstring = ''
    z = line.strip()
    newstring += z
for line in fp:
    fields = line.split('\t')
    gene_ID, chr, strand = fields[:2]
    start = int(fields[3])
    end = int(fields[4])
    bc = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'N':'N'}
    if strand == '+':
        wp.write(newstring[start:end])
    if strand == '-':
        newstart, newend = -(start + 1), -(end + 1)
        wp.write(bc[base.upper()] for base in newstring[newstart:newend])

As you can see, I have it pick a different part out of the file depending on whether a '+' or a '-' is present. That said, I need to use this for both the spliced and unspliced options. But each line(or string) pulled from this file should be placed with its corresponding information line(created in the last piece of code). The code here is pulling a sequence from another file and translating it.
I need to put these two pieces of code together somehow so the format of my outfile has:
An information
Corresponding sequence
Another info line
Corresponding sequence

A: Can't you just do one, then the other, like so:
for line in fp:
  # Info line
  line = line.replace(',',' ')
  tokens = line.split()
  if '-s' in sys.argv and r:
    wp.write('>'+tokens[0]+'|'+tokens[1]+'('+tokens[2]+')'+':'+int(tokens[3])+'-'+int(tokens[4])+'|'+int(tokens[5])+'-'+int(tokens[10])+','+int(tokens[8])+'-'+int(tokens[11]))
  else:
    wp.write('>'+tokens[0]+'|'+tokens[1]+'('+tokens[2]+')'+':'+int(tokens[3])+'-'+int(tokens[4]))

  # Sequence line
  fields = line.split('\t')
  gene_ID, chr, strand = fields[:2]
  start = int(fields[3])
  end = int(fields[4])
  bc = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'N':'N'}
  if strand == '+':
    wp.write(newstring[start:end])
  if strand == '-':
    newstart, newend = -(start + 1), -(end + 1)
    wp.write(bc[base.upper()] for base in newstring[newstart:newend])

Or am I missing something here?


text:
Q: No file or directory No matter what I do I can not get this to run from a script. It just keeps erroring out with the message:

mv: rename item to tempplc: No such file or directory

tempplc = '/mnt/Volume_1/USB_DRIVE/'
mvs = []
tvs = []
tds = []

for item in dwnlds:

    result = re.search(r"s\d\de", item, re.I)
    tdsrlt = re.search(r"the.daily.show", item, re.I)

    if result == None:
        if tdsrlt != None:
            tds.append(item)
        else:
            mvs.append(item)
    else:
        tvs.append(item)

os.chdir('/mnt/Data/jails_2/sabnzbd_1/var/db/sabnzbd/Downloads/complete')

for item in tds:
    os.system('mv -v  item tempplc') #<---- PROBLEM LINE

No matter what I do I can not get this to run from a script. It just keeps erroring out with the message:

A: Command 'mv -v  item tempplc' attempts to move file 'item' (sic!) into the folder 'tempplc'. Replace the variable names with their values:
'mv -v {} {}'.format(item, tempplc)


text:
Q: Pass array of CimInstance to CimMethod I am working with WMI API through Cim cmdlets. The problem is that I can't figure out how to pass wmi object to wmi method that accepts array of wmi objects.
Here are method parameters definition:
Name                                            CimType Qualifiers
----                                            ------- ----------
Path                                             String {ID, in}
Permissions                               InstanceArray {EmbeddedInstance, ID, in}
ResetChildren                                   Boolean {ID, in}

Path and ResetChildren are simple parameters. They accepts simple values like "/path" and $true respectively. But I have troubles with Permissions parameter.
Here is my code
#Acquiring object that I want to pass to method
$group = Get-CimInstance -Namespace "root\VisualSVN" -ClassName VisualSVN_Group -Filter "Name='Readers'"

#Acquiring object which method will be called
$repositories = Get-CimInstance -Namespace "root\VisualSVN" -ClassName VisualSVN_Repository

#Preparing method arguments
$args = @{
    Path = "/";
    Permissions = @($group[0]); #Trouble here
    ResetChildren = $true
}

#Invoking method with arguments
Invoke-CimMethod -InputObject ($repositories[0]) -MethodName SetSecurity -Arguments $args

Execution of this code will result in error:
Invoke-CimMethod : Unable to cast object of type 'Microsoft.Management.Infrastructure.CimInstance' to type 'M
icrosoft.Management.Infrastructure.Native.InstanceHandle'.
Parameter name: value
At C:\somepath\script1.ps1:11 char:1
+ Invoke-CimMethod -InputObject ($repositories[0]) -MethodName SetSecurity -Argume ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Invoke-CimMethod], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException,Microsoft.Management.Infrastructure.CimCmdlets.Invoke
   CimMethodCommand

If you change code
Permissions = @($group[0]); #Trouble here

To code
Permissions = $group; #Trouble here

Then error message will also change:
Invoke-CimMethod : Unable to cast object of type 'Microsoft.Management.Infrastructure.Native.InstanceHandle'
to type 'System.Collections.IList'.
Parameter name: value
At C:\somepath\script1.ps1:11 char:1
+ Invoke-CimMethod -InputObject ($repositories[0]) -MethodName SetSecurity -Argume ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Invoke-CimMethod], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException,Microsoft.Management.Infrastructure.CimCmdlets.Invoke
   CimMethodCommand

Any ideas how to pass $group to method properly?

A: I had exactly same problem with VisualSVN_Repository::SetSecurity method.
When working with CIM method arguments, you must cast ANY array arguments to [CimInstance[]].
For example, this worked for me:
$Everyone = Get-CimInstance -Namespace root/VisualSVN -ClassName VisualSVN_Everyone
# Grant Everyone a Read/Write access:
$AccessRule = New-CimInstance -Namespace root/VisualSVN -ClassName VisualSVN_PermissionEntry -ClientOnly -Property @{ Account = $Everyone; AccessLevel = [UInt32]2 }
$SvnRepo = Get-CimInstance -Namespace root/VisualSVN -ClassName VisualSVN_Repository -Filter "Name='MY_REPOSITORY_NAME'"

Invoke-CimMethod -InputObject $SvnRepo -MethodName SetSecurity -Arguments @{
    Path = '/';
    Permissions = [CimInstance[]]$AccessRule;
    ResetChildren = $true
} | Out-Null

You must cast array argument to [CimInstance[]] even when it is just a single item.
P.S.: Be careful with Ref array arguments too: you must first cast it to [CimInstance[]] and then to [ref[]]. For example, when calling VisualSVN_Group::Create method:
[CimInstance[]] $SvnUsers = [CimInstance[]]($ArrayOf_VisualSVN_User_Objects)

Invoke-CimMethod -ClassName VisualSVN_Group -Namespace root/VisualSVN -MethodName Create -Arguments @{
    Members = [ref[]]$SvnUsers;
    Name = 'MY_NEW_GROUP_NAME'
} | Out-Null

See also: Tip#5: Passing ref and embedded instances on PowerShell Blog.

A: If you had a repro that did not rely on software I do not have installed, I could answer definitively, so I will make my best attempt based on what I can infer from your question.
To make what you are assigning to Permissions an array, and you are only assigning one value, use a comma in front.
Permissions = ,$group
Here is some sample script and the output to demonstrate.
Script
$var1 = "any value"
$var2 = ,$var1

$var1.GetType()
$var2.GetType()
$var2.Count
$var2[0]

Output
IsPublic IsSerial Name      BaseType
-------- -------- ----      --------
True     True     String    System.Object
True     True     Object[]  System.Array
1
any value

A: A possible solution (it worked for me with a similar issue that led me here) based on the 'hint' that CIM are inert objects.  In my case it was installing SCCM updates in a scripted manner while allowing for reboots if the updates required them, and stopping if the entire process took more than a certain amount of time (to not go past the available maintenance window).
I was passing a CIMUpdate object through to a powershell function to perform the update to allow for rebooting if necessary between updates (Perform a single update at a time, verify if reboot is needed, then try the next update).
The CIM object was giving a Type Mismatch error when forcing it to cast as [CIMInstance[]], and if not casting at all I would get the same Unable to cast object of type 'Microsoft.Management.Infrastructure.CimInstance' to type 'Microsoft.Management.Infrastructure.Native.InstanceHandle' error message.
Solution was to use that CIMUpdate and re-query to get a live version of the object within the function and then use that new object as the argument to the CIMMethod.

A: as of now, it works for me , the case I am working on is passing New-ScheduledTaskTrigger instance to a function.
I am passing a CimInstance to a function and receiving it as PSCustomObject type.

*

*Send CimInstance receive as [PSCustomObject] -> at target it remains CimInstance object type

*Send CimInstance  receive as [CimInstance] -> at target it remains CimInstance object type

*Send CimInstance  receive as [CimInstance[]] -> at target it turn to CimInstance array type


text:
Q: Ajax data not shown in console log but give error as given "http://localhost/IFICSV3/public/sla/sla/getbranch/180 not found " I try to make dropdown option dependent using ajax . i want to see the data in console whether the data is success or else. I expect the data was shown in console log but error given

http://localhost/fic/public/sla/sla/getbranch/180 404 not found

Here is my code for view ajax
if(country_id) {

    //console.log(country_id);

    $.ajax ({
        url: 'sla/getbranch/'+country_id,
        //url: "{{ route('sla.getbranch') }}"+country_id,
        type: 'GET',
        datatype: 'json',
        success: function(data){
            console.log(data);
        }
    })

My controller
public function index()
{
    $custList = $this->hdcustomermaster->getAllCustomerActiveSts();
    return view('sla.slm.SLAList', compact('custList'));
}

public function getbranch($id)
{
    $data=HDCustomerBranch::where('cb_customer_ID',$id)->pluck('cu_customer_ID','cu_customer_Name');
    return json_encode($data);
}

my web.php
Route::group(['prefix' => 'sla'], function () {

   Route::get('/','SlaController@index');
   Route::resource('sla', 'SlaController');
   Route::get('sla/getbranch','SlaController@getbranch')->name('sla.getbranch');
});

A: Replace your route like this
Route::group(['prefix' => 'sla'], function () {

   Route::get('/','SlaController@index');
   Route::resource('sla', 'SlaController');
   Route::get('sla/getbranch/{id}','SlaController@getbranch')->name('sla.getbranch');
});

Here the problem is you are passing 180 as an param in that route. But you dont declare that param in your route.
Also you can add a '?' if it is an optional param, like this
Route::get('sla/getbranch/{?id}','SlaController@getbranch')->name('sla.getbranch');


text:
Q: Use an async function from one component to another I'm working on coding a Dapp with the react boxe from truffle. For that application I need to use a function (just two getters) from my smart contract in another component than App.js. This function is the getUser, which needs to be in form from Login.js.
App.js:
class App extends Component {
  state = {
    web3: null,
    contract: undefined,
    account: null,
    user: {
      id: null,
      name: '',
      password: ''
    }
  };

  componentDidMount = async () => {
    try {
      const web3 = await getWeb3();
      const accounts = await web3.eth.getAccounts();
      const networkId = await web3.eth.net.getId();
      const deployedNetwork = Login.networks[networkId];
      const instance = new web3.eth.Contract(
        Login.abi,
        deployedNetwork && deployedNetwork.address,
      );
      this.setState({ web3, accounts, contract: instance });
    } catch (error) {
      alert(
        `Failed to load web3, accounts, or contract.
         Check console for details.`,
      );
      console.error(error);
    }
  };

  getUser = async (event) => {
    const userID = this.state.id;
    const userName = await this.state.contract.methods
                     .getUsername(userID).call();
    const userPassword = await this.state.contract.methods
                        .getPassword(userID).call();
    console.log(userName + ' - ' +userPassword);
  };

  render() {
    if (!this.state.web3) {
      return
Loading Web3, accounts, and contract...
;
    }
    return (

    );
  }
}

export default App;

Login.js:
class App extends Component{

  handleInputChange = (event) => {
    let input = event.target;
    let name = event.target.name;
    let value = input.value;
    this.setState({
      [name]: value
    })
  }
render() {
    return (

        <form>

            Barcode:
            <input name="id" type="number" required
                   onChange={this.handleInputChange} />

          <button type="submit" value="submit">Get user data</button>
        </form>

    );
  }
}

export default Login;

I first tried to export the getUser function:
App.js:
export const getUser = async (event) => {
        const userID = this.state.id;
        const userName = await this.state.contract.methods
                         .getUsername(userID).call();
        const userPassword = await this.state.contract.methods
                            .getPassword(userID).call();
        console.log(userName + ' - ' +userPassword);
      };

Login.js:
import {getUser} from ...

But I got the following error:
Unhandled Rejection (TypeError): Cannot read property 'state' of undefined

I then tried to add inside the Login, the same componentDidMount
and state found inside App.js (with the imports), however I got
the following error:
TypeError: Cannot read property 'methods' of null

I no longer have any idea of how to do it. So I would like to ask some help please.
I thank in advance anyone who will take the time to help me.

A: You just need to pass the value between components. Let's say onClick you will move from login to app component and you will pass id & name.
onClick=(id,name)=>{
  history.push({
           pathname: '/secondpage', //app component url
           state: { id: id, name: name }
       })
}

history could be imported from react-router
Then in app component you can access this value in, this.props.location.state
If you want to send value through component, in login component declare app component like this,
<App
  id={id}
  name={name}
/>

Then in app component you can get the value in this.props

A: Global State Management
You are looking for a way to manage state at a global level. There are lots of solutions for this problem that exists and are widely used.
Solution 1: Props or "prop drilling"
The idea is to pass the state to every component that needs it. You should only consider doing this if you are passing down props that are not global level or is needed by only a few component trees.

An example of passing down props is in the official docs (https://reactjs.org/docs/context.html)

Solution 2: React Context API
There is already a built in feature inside React that is widely used called Context API that solves this. Example of usage is also in the docs. https://reactjs.org/docs/context.html

Context provides a way to pass data through the component tree without having to
pass props down manually at every level.

TLDR; If you need to your state to be at a global level where lots of component trees need access to it, this is probably the solution.


text:
Q: how to convert .dat file to .mat in Matlab I have a .dat file which contains MRI images. i want to open this file in Matlab and convert it to .mat file which will contain "MrPort" and "Reco". Could anyone help me with this?
Thanks!

A: You need to read the dat file into matlab, set MrPort and Reco variables and then save to mat file:
>> save('myMatFile.mat', 'MrPort', 'Reco' );


text:
Q: Regex with PowerShell won't work with /n (newline) For some reason, newline characters will not work with my regex.
Here's the first part of the PowerShell script. This piece of code is used to get a set of markdown files. For testing purposes, I'm only using the first file.
The code then gets the content inside the file.
$path = 'C:\Users\Will\Desktop\ProjectTemp'

$filelist = ls $path -filter *.md -recurse

[string[]]$currentfile_path = $filelist[0].FullName

$currentfile_data = Get-Content $currentfile_path

This is the problematic code. It works fine anywhere else, but PowerShell will not find the matched so that they can be replaced. Specifically, I have found that the newline characters will not work. Nothing I have tried will work.
$currentfile_data -Replace '([ \t]*)\| (.*) \| (.*) \| (.*) \|\r\n[ \t]*\| .* \| .* \| .* \|\r\n[ \t]*\| (.*) \| (.*) \| (.*) \|','$1
\n$1\t
\n$1\t\t$2	\n$1\t\t$3	\n$1\t\t$4	\n$1\t
\n$1\t
\n$1\t\t$5	\n$1\t\t$6	\n$1\t\t$7	\n$1\t
\n$1
'

This is meant to find the regex:
'([ \t]*)\| (.*) \| (.*) \| (.*) \|\r\n[ \t]*\| .* \| .* \| .* \|\r\n[ \t]*\| (.*) \| (.*) \| (.*) \|'
and replace it with:
$1
\n$1\t
\n$1\t\t$2	\n$1\t\t$3	\n$1\t\t$4	\n$1\t
\n$1\t
\n$1\t\t$5	\n$1\t\t$6	\n$1\t\t$7	\n$1\t
\n$1
'

What the input and output should look like:
| th1 | th2 | th3 |
| :-: | :-: | :-: |
| td1 | td2 | td3 |

        th1
        th2
        th3

        td1
        td2
        td3

Is there any way this can be fixed? Am I doing something wrong?

A: tl;dr
$currentfile_data = Get-Content -Raw $currentfile_path

-Raw ensures that Get-Content reads the iput file as a whole, as a single, typically multi-line string, which ensures that the subsequent -replace operation can perform matching across lines.

As for what you tried:

$currentfile_data = Get-Content $currentfile_path

This saves an array of the lines from the input file in variable $currentfile_data, because Get-Content by default streams the target file's lines one by one.

$currentfile_data -Replace '...'

This makes the -replace operator act on each element of the array stored in $currentfile_data, i.e. on each line of the original file rather than across lines.

A PowerShell (Core) 7+ alternative:
As Santiago Squarzon points out, PowerShell (Core) 7+ ships with the ConvertFrom-Markdown cmdlet, which can directly transform your input file to HTML (albeit not in the exact same format):
(@'
| th1 | th2 | th3 |
| :-: | :-: | :-: |
| td1 | td2 | td3 |
'@ | ConvertFrom-Markdown).Html

Output:

th1
th2
th3

td1
td2
td3


text:
Q: the packages pydub.AudioSegment in python doesn't work on window7? I am using python on the window7, python3 ver, jupyter(or pycharm both).
I installed the pydub package for some reasons,
that converting *.mp3 to *.wav file at the same time
and split to mp3 file to per 40sec files,
and I checked it installed successfully.
"Requirement already satisfied: pydub in c:\programdata\anaconda3\lib\site-packages (0.22.1)"
but when I typed like bellows,
from pydub import AudioSegment
song = AudioSegment.from_mp3('D:\a'+'.mp3' )
it caused the error like:
C:\ProgramData\Anaconda3\lib\site-packages\pydub\utils.py:165: RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work
pydub ffmpeg
so I try to installed ffmpeg but it's impossible with this message:
Could not find a version that satisfies the requirement subprocess (from ffmpeg) (from versions: )
No matching distribution found for subprocess (from ffmpeg)
so I found another way to solve it in here:
import pydub
pydub.AudioSegment.converter = "C:\path\to\ffmpeg.exe"
but another error shows up like this:
C:\ProgramData\Anaconda3\lib\site-packages\pydub\utils.py:193: RuntimeWarning: Couldn't find ffprobe or avprobe - defaulting to ffprobe, but may not work
  warn("Couldn't find ffprobe or avprobe - defaulting to ffprobe, but may not work", RuntimeWarning)
as like many guys stuck in the same error.
I read many solutions about these, but nothing to make it better.
Anybody help me with this problem with a code in detail.

A: I have w8.
If i use this, i have а error.
AudioSegment.converter = ffmpeg_catalog+'ffmpeg.exe'
AudioSegment.ffmpeg = ffmpeg_catalog+'ffmpeg.exe'
AudioSegment.ffprobe = ffmpeg_catalog+'ffprobe.exe'

But when i add "C:\ffmpeg\bin" to PATH and restart os, it works.
And you must to remove lines above.


text:
Q: Mutual SSL between WAS Liberty Profile and IBM HTTP Server I'd like to turn on client authentication on WAS liberty profile so that the communication b/w the web server and the app server is in mutual SSL.
On IHS, I have a plugin file to FW the traffic to the app server in HTTPS with a keyring and stashfile. It is working and FW the traffic to the WLP.
On WLP's server.xml I turn on the client authentication to enforce the WLP to authenticate the certificate by giving clientAuthentication="true" in the <ssl> element.
<ssl id="defaultSSLConfig" keyStoreRef="defaultKeyStore" trustStoreRef="defaultTrustStore" clientAuthentication="true" />

I try to validate this by directly hitting the app server using browser with https address (without any client certificate) and expected to get a access denied. And to access the app server via the app server should grant access if mutual SSL is up and running. However, both hitting the app server directly or via web server, I can access the resource.
This set up clearly isn't correct or not complete. Any thoughts?

A: I have it resolved. What I missed was the <sslOptionRef id="defaultSSLConfig" /> inside <httpEndpoint>. I was under impression that it would automatically pick up the olny one <ssl> element I defined in server.xml. But without the sslOptionRef, client authentication somehow doesn't work and does not authenticate the client.
Now with <sslOptionRef> defined in server.xml, the client authentication is working fine that I can only access the WLP app server via my web server in my browser in https.


text:
Q: Update table: Converting CRLF to LF on linux I use oracle database.
I was trying to use replace CRLF characters on my emp table column.
However, the following does not give me the right result.
UPDATE emp t
   SET ename = REPLACE(t.ename, '[CR-LF]', chr(10))
commit;

What seems to be the problem?

A: The wrong thing is the text you are trying to replace. Use the code of the characters instead:
UPDATE emp t
SET ename = REPLACE(t.ename, chr(13) || chr(10), chr(10))

A: try this :
UPDATE emp t
   SET ename = TRIM( TRAILING CHR(13) FROM t.ename)


text:
Q: Converting VC++ 6 project to VC++2010 with MFC So, I have this code that hasn't been touched since '99, and was made with VS6. I need to be able to compile and change some stuff in the code, SO, after trying the VS2010 conversion wizard, I get a few errors saying certain header files couldnt be found.: afxwin.h , and one other header file that's related to the program. I know it's using MFC, and since I have NOT the express edition of VS, but the full version, I should have all the dependencies required, right?
So I guess my question is: what would be the best way to convert a VS file thats several versions old? Will I have to create a new 2010 C++ proj, and just manually port over all the files?
Thanks!

A: You could try Create New Project from Existing Code if the conversion is problematic.
VC++ 10 is a lot better on conformance to the standard, so you may find the VC++ 6 source code no longer compiles even when you have a working project file (a good thing).  Fixing such problems up is not generally too hard.


text:
Q: Using an intent to send data of an item from Firestore UI RecyclerView to next activity I have implemented a RecyclerView using the Firestore UI. It displays currently a username and a profile picture. When the user clicks on any item of the RecyclerView he gets to a user profile activity. There, the name and the profile picture of the user should be displayed which is currently not the case because I don't know how to send the data of one item to the next activity and set the TextView to its value. Is an intent the best approach or should I just sent the UID of the user that got clicked and then retrieve the data of the user from Firestore within the "User Profile Activity"? How can I achieve this? There are tutorials on how to achieve this with the Real Time Database but I don't want to switch the database.
Here is my activity where the RecyclerView is implemented:
...
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player_search);
...
        userAdapter.setOnItemClickListener(new UserAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(DocumentSnapshot documentSnapshot, int position) {

                String user_id = documentSnapshot.getId();
            }
        });
...

Here is the Adapter class of the RecyclerView with an intent that opens the next activity:
public class UserAdapter extends FirestoreRecyclerAdapter<Users, UserAdapter.UserHolder> {
    private OnItemClickListener listener;

    public UserAdapter(@NonNull FirestoreRecyclerOptions<Users> options) {
        super(options);
    }

    @Override
    protected void onBindViewHolder(@NonNull UserHolder holder, int position, @NonNull Users model) {

        holder.textViewUsername.setText(model.getUsername());

        Picasso.get()
                .load(model.getAvatar_id())
                .into(holder.circleImageView);
    }

    @NonNull
    @Override
    public UserHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listitem_search_result,parent, false);
        return new UserHolder(view);
    }

    class UserHolder extends RecyclerView.ViewHolder {

        TextView textViewUsername;
        CircleImageView circleImageView;

        public UserHolder(@NonNull View itemView) {
            super(itemView);

            textViewUsername = itemView.findViewById(R.id.player_name_search);
            circleImageView = itemView.findViewById(R.id.image_view_avatar_player_search);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = getAdapterPosition();
                    if (position != RecyclerView.NO_POSITION && listener != null){
                        listener.onItemClick(getSnapshots().getSnapshot(position),(position));
                        Intent i = new Intent (itemView.getContext(), FriendRequest.class);
                        itemView.getContext().startActivity(i);
                    }

                }
            });
        }
    }

    public interface OnItemClickListener{
        void onItemClick (DocumentSnapshot documentSnapshot, int position);

    }

    public void setOnItemClickListener(OnItemClickListener listener){
        this.listener = listener;
    }
}

The structure of my Collection is this:
User
    uid
        username: "Player1"
        avatar_id: "uri of a picture stored in Storage"

Any help is much appreciated!

A: In order to send the information from one activity to other use the Intent
Intent i = new Intent (itemView.getContext(), FriendRequest.class);
i.putExtra("username", textViewUsername.getText().toString());
i.putExtra("profile",model.getAvatar_id());
itemView.getContext().startActivity(i);

and in yours FriendRequest activity, use getIntent to receive that data.
Intent intent = getIntent();
String username = intent.getStringExtra("username");
String link = intent.getExtra("profile");

now you can use these values.


text:
Q: To feel myself + a participle Can you explain how "I feel myself" can be used? I come across different sentences, some are correct others not. I can't understand what makes them wrong.

Wrong:
I feel myself thinking.
I feel myself dreaming.
Correct:
I feel myself flying.
I feel myself getting anxious.
I feel myself changing.
Don't know if they are correct:
I feel myself to have a duty.
I feel myself the equal of Moses.

Any guidelines?

A: So, first of all, there are actually two different ways that the words "I feel myself" can be used in a sentence, and thus really two different meanings they can have:

*

*"I feel myself (verb)ing" essentially means "I feel the physical sensation of myself doing (verb)".  In this case, "feel" is being used with a meaning of actual tactile sensation (i.e. the sensation of touch, or motion, etc).

*"I feel myself to be (thing)" or "I feel myself to have (thing)", however, means "I believe that I am/have (thing)".  In this case, "feel" is just being used as another word for "believe" or "think".

(Also, note that sometimes the "to be" part is left out and just implied, so it can sometimes be said as just "I feel myself (thing)", but it means the same thing as "I feel myself to be (thing)")
So in your examples:

*

*I feel myself flying --> I feel the physical sensation of myself flying

*I feel myself to have a duty --> I believe that I have a duty

*I feel myself the equal of Moses --> I believe that I am the equal of Moses

The reason your first examples are not really correct is because they are using the "I feel myself (verb)ing" form, which means they're talking about tactile sensation, but the verbs your using are not things that actually have a tactile sensation associated with them:

*

*I feel myself thinking --> I feel the physical sensation of myself thinking

What does "thinking" feel like?  Can you describe the sensation?  For most people, they don't actually feel a different sensation when they're thinking than when they're not, so this doesn't actually make a lot of sense.

*

*I feel myself dreaming --> I feel the physical sensation of myself dreaming

Again, does "dreaming" have a particular feeling that you get when you're doing it?  Many dreams may involve feeling things, but what you feel probably changes from dream to dream, there's generally no specific sensation one experiences for "dreaming" itself, which someone could identify as "what dreaming feels like".
Basically, using this construction automatically brings up the implied question:  What does doing that thing actually feel like?  If you can't actually answer that question, then it's probably not a verb you can use that way.


text:
Q: Spring Boot as a resource server (JWK validation) & Angular/Cordova as front end - OAuth2 for social Login (Facebook & Google) support I am stuck with the implementation of spring boot as a resource server for multiple authorization servers for validating the access/id tokens provided by authorization servers (such as google, facebook via front end libraries). Here is the architecture I am looking for the below desired flow as a working model.
Desired Architecture Image - Click here
what I implemented so far: I used a library angularx-social-login on angular 8 to get the required tokens google. I was able to pass the token back to the backend resource server to validate the token with google and authorize. Below is the code snippets.
Property File:
google:
  client-id: xyz
  iss: accounts.google.com

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: https://accounts.google.com
          jwk-set-uri: https://accounts.google.com/.well-known/openid-configuration

Security Config Snippet
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}")
private String issuer;

@Value("${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}")
private String jwkSetUri;

@Value("${google.client-id}")
private String clientId;

@Value("${google.iss}")
private String iss;

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
        .authorizeRequests()
        .anyRequest().authenticated().and()
        .oauth2ResourceServer()
        .jwt().decoder(jwtDecoder());
}

@Bean
JwtDecoder jwtDecoder() {
    NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder)
            JwtDecoders.fromOidcIssuerLocation(issuer);

    OAuth2TokenValidator<Jwt> audienceValidator = new AudienceValidator(clientId);
    OAuth2TokenValidator<Jwt> withIssuer = JwtValidators.createDefaultWithIssuer(iss);
    OAuth2TokenValidator<Jwt> withAudience = new DelegatingOAuth2TokenValidator<>
    (withIssuer, audienceValidator);

    jwtDecoder.setJwtValidator(withAudience);

    return jwtDecoder;
}

}

The above snippet works for one authorization server (google in this case) but
below are my issues

*

*How do Intercept the code to validate if the user exists in our DB first?

*How do I add support for another authorization server like facebook?


text:
Q: Why do larger images not appear in a share extension, or action extension? When I try to create a share extension (or action extension)
 to write email containing shared images, why do the larger images not appear, only small ones?

A: Because there may be a delay before image data is provided to your extension, you must wait for it to arrive before presenting an email compose window including them. (Otherwise they do not appear)
I keep a counter in bitsToLoad, that I increment for each piece of data I request, and decrement for each piece I receive
if ([itemProvider hasItemConformingToTypeIdentifier:(NSString *)kUTTypeImage]) {
                        bitsToLoad ++;
                        __weak MFMailComposeViewController *pick = picker;
                        [itemProvider loadItemForTypeIdentifier:(NSString *)kUTTypeImage options:nil completionHandler:^(UIImage *image, NSError *error) {
                            if (image) {
                                [pick addAttachmentData:UIImageJPEGRepresentation(image,0.8) mimeType:@"image/jpeg" fileName:@"image.jpg"];
                            }
                            [self dataFetched];
                        }];

And check that they have all arrived, before I present the Email form.
-(void) dataFetched {
    bitsToLoad--;
    if (bitsToLoad==0) {
        [self presentViewController:picker animated:YES completion:^(){ }];
    }
}

But this isn't quite enough.
To make sure the email interface does not appear until all attachments have been considered, AND that it will be presented at the end even if there were no images, I set bitsToLoad to 1 at the beginning of the scanning routine...
NSInteger bitsToLoad=1

and decrement and check it at the end.
[self dataFetched];

Now the view controller will only be presented after all attachments have been checked, and all data has been fetched.
Note that you may find that small images (such as screen grabs) appear even without this sort of check, as they are passed to the extension quickly enough, but it would definitely break without this for larger images, such as typical iPhone photos.


text:
Q: mongoDB array pagination I have a comment collection with Comment Text in array with its Metadata.  I like to the pagination in the Comment Text Array. The pagination should allow me to get the "previous 5" or "next 5". What is the best way to do this in mongoDB with good performance.
   { "_id" : ObjectId( "502c706ac2e6777781a593f6" ),
      "commentType":"loc",
      "commentList" : [
{ "commentText" : "HelloComment",
  "commentTS" : Date( 1345165636344 ),
  "commentLoc" : { "commentlat" : 0,
    "commentlong" : 0 },
  "userInfo" : { "$ref" : "userProfile",
    "$id" : ObjectId( "4fd182d92b2a87f780c6bbe8" ) } },
{ "commentText" : "2222222",
  "commentTS" : Date( 1345165636344 ),
  "commentLoc" : { "commentlat" : 0,
    "commentlong" : 0 },
  "userInfo" : { "$ref" : "userProfile",
    "$id" : ObjectId( "4fd182d92b2a87f780c6bbe8" ) } },
{ "commentText" : "3333333",
  "commentTS" : Date( 1345165636344 ),
  "commentLoc" : { "commentlat" : 0,
    "commentlong" : 0 },
  "userInfo" : { "$ref" : "userProfile",
    "$id" : ObjectId( "4fd182d92b2a87f780c6bbe8" ) } },
{ "commentText" : "44444444",
  "commentTS" : Date( 1345165636344 ),
  "commentLoc" : { "commentlat" : 0,
    "commentlong" : 0 },
  "userInfo" : { "$ref" : "userProfile",
    "$id" : ObjectId( "4fd182d92b2a87f780c6bbe8" ) } },
{ "commentText" : "5555555",
  "commentTS" : Date( 1345165636344 ),
  "commentLoc" : { "commentlat" : 0,
    "commentlong" : 0 },
  "userInfo" : { "$ref" : "userProfile",
    "$id" : ObjectId( "4fd182d92b2a87f780c6bbe8" ) } },
{ "commentText" : "6666666",
  "commentTS" : Date( 1345165636344 ),
  "commentLoc" : { "commentlat" : 0,
    "commentlong" : 0 },
  "userInfo" : { "$ref" : "userProfile",
    "$id" : ObjectId( "4fd182d92b2a87f780c6bbe8" ) } },
    { "commentText" : "777777",
  "commentTS" : Date( 1345165636344 ),
  "commentLoc" : { "commentlat" : 0,
    "commentlong" : 0 },
  "userInfo" : { "$ref" : "userProfile",
    "$id" : ObjectId( "4fd182d92b2a87f780c6bbe8" ) } },
    { "commentText" : "888888",
  "commentTS" : Date( 1345165636344 ),
  "commentLoc" : { "commentlat" : 0,
    "commentlong" : 0 },
  "userInfo" : { "$ref" : "userProfile",
    "$id" : ObjectId( "4fd182d92b2a87f780c6bbe8" ) } },
    { "commentText" : "6666666",
  "commentTS" : Date( 1345165636344 ),
  "commentLoc" : { "commentlat" : 0,
    "commentlong" : 0 },
  "userInfo" : { "$ref" : "userProfile",
    "$id" : ObjectId( "4fd182d92b2a87f780c6bbe8" ) } },
{ "commentText" : "999999",
  "commentTS" : Date( 1345165668809 ),
  "commentLoc" : { "commentlat" : 0,
    "commentlong" : 0 },
  "userInfo" : { "$ref" : "userProfile",
    "$id" : ObjectId( "4fdeb271de26fd298262bb84" ) } },
{ "commentText" : "HelloComment",
  "commentTS" : Date( 1345749858601 ),
  "commentLoc" : { "commentlat" : 0,
    "commentlong" : 0 },
  "userInfo" : { "$ref" : "userProfile",
    "$id" : ObjectId( "4fdeb271de26fd298262bb84" ) } },
{ "commentText" : "NewTestforcomments",
  "commentTS" : Date( 1345750020526 ),
  "commentLoc" : { "commentlat" : 0,
    "commentlong" : 0 },
  "userInfo" : { "$ref" : "userProfile",
    "$id" : ObjectId( "4fdeb271de26fd298262bb84" ) } } ],
   } }

Thanks for your help.

A: You can do this with $slice:
http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements
There's also a JS test example of slice here.
So, findOne, combined with $slice, is probably the way to go.
Without more info about the language you're using, I think that's the deepest I can go.


text:
Q: Using for loop to find specific characters in string I am attempting the bean counting example in the functions chapter of the book Eloquent Javascript. My function is returning a blank.
Without giving me the full answer (I'm working through this example to learn), can someone tell me why my code is not printing any text?"
var string = "donkey puke on me boot thar be thar be!";

for (var i = 0; i <= string.length; i++);

function getB(){
  if (string.charAt(i) == "b")
    return i;
  else return "";
}

console.log(getB());

A: There is something wrong about how you're trying to implement this feature.
First of all I think it's better if you have a function that accepts the string and the char as parameters in order to call it whenever you want.
Example of calling :
getChar('this is my custom string', 'c')  -> it should search character `c` in `this is my custom string`

getChar('this is another custom string', 'b')  -> it should search character `b` in `this is another custom string`

Example of implementation :
var getChar = function(string, char){
  for(var i=0;i<string.length;i++)
  {
    if(string.charAt(i)==char) console.log(i);
  }
}

Now, try to make it not case-sensitive  and instead of console.log the output try to return a sorted array with character positions

A: Use This,
var string = "donkey puke on me boot thar be thar be!";

for (var i = 0; i <= string.length; i++) {
  if (string.charAt(i) == "b") {
    console.log(i);
  }
}

A: another example: collect all b positions:
var string = "donkey puke on me boot thar be thar be!";

function getB(string){
    var placesOfB = [];
    for (var i = 0; i < string.length; i++) {
        if (string.charAt(i) == "b") {
            placesOfB.push(i);
        }
    }
    return placesOfB;
}

console.log(getB(string));

A: if you want to print every position your value is at, you can program something like this:
var string = "donkey puke on me boot thar be thar be!";

for (var i = 0; i <= string.length; i++)
{
   getChar(i, "b");
}

function getChar(i, input)
{
    if (string.charAt(i) == input)
        console.log(i);
}

A: tip: your for has no body (putting ; after it just loops without doing anything)...
and it does not make sense to define a function inside that for.

A: Without giving you the full answer, I'll just give you pointers:
1. Your for loop is not complete - it doesn't do anything.
2. Your getB() function needs to accept string parameter in order to perform some action on it.
3. The if..else statement doesn't have opening and closing brackets {}


text:
Q: it is possible to validate json schema on mule 4 munit assert? In Postman tests I can validate if response has a given schema:
var jsonObject = pm.response.json();

var schemaResponse = {
   "type": "object",
  "properties": {
    "ok": {
      "type": "boolean"
    },
    "operation_id": {
      "type": "string"
    },
    "push_ids": {
      "type": "array",
      "items": [
        {
          "type": "string"
        }
      ]
    },
    "message_ids": {
      "type": "array",
      "items": [
        {
          "type": "string"
        },
        {
          "type": "string"
        }
      ]
    },
    "content_urls": {
      "type": "array",
      "items": [
        {
          "type": "string"
        },
        {
          "type": "string"
        }
      ]
    },
    "localized_ids": {
      "type": "array",
      "items": [
        {
          "type": "string"
        },
        {
          "type": "string"
        }
      ]
    }
  }
}

pm.test("Response Schema Validation", function() {
    var result = tv4.validateResult(jsonObject, schemaResponse);
    pm.expect(result.valid).to.be.true;
});

Can I do the same in Mule 4 Munit tests?

A: There is no out of the box option to do it. If you need a simple workaround you can use json-schema-validator as one of your validation steps. The problem with this is it will not throw an AssertionException, but a JSON:SCHEMA_NOT_HONOURED error, due to which your test will be treated as Errored out instead of the expected Failed. Therefore I will not recommend this approach.
The correct way to do this is to create your own custom assertion and use Run Custom Event Processor. The official MuleSoft document (link) describes the process with a simple and good explanation on how to implement a custom assertion class.
Basically, you will need to create a Java class that will implement MunitAssertion interface and use a Java Library to do the schema validation. You can pick from a variety of Java library available like everit-org/json-schema


text:
Q: Sound implementation in Symbian^3 I am looking around to implement sound in my Symbian^3 game application. Are the examples of Symbian S60 work well for Symbian^3 devices? I am in doubt because syntax is different for S60 and Symbian^3.
If anybody can provide me any link where I could find any method to implement sound in Symbian^3 application. Looking for early reply.
Thanks in advance.
Atul Prakash Singh

A: Have you looked at CMdaAudioPlayerUtility
link . Although the link is to a 3rd ed doc , the Class remains mostly the same.


text:
Q: Why is the sentence "Wall-to-wall carpets in every room is their dream" acceptable? I saw this sentence in the CoGEL(Quirk et al).

15.16 Verbless clause:
Wall-to-wall carpets in every room is their dream.

Question: Why is this awkward sentence acceptable? It's obvious that it violates the subject-verb agreement.
The book explains that this sentence may be paraphrased by nominal nonfinite existential
clauses as below:
Having wall-to-wall carpets in every room is their dream. (This sentence is perfect, but why does the above example exist with no problem?)

A: "Wall-to-wall carpets in every room" is a singular noun phrase in the sentence Wall-to-wall carpets in every room is their dream. The phrase represents a single dream (meaning a desire, a hope for the future) so that's why the verb is "is".
A simpler sentence with the same grammatical structure is:

A trip to Europe is my dream.

What if the sentence was:

Wall-to-wall carpets in every room is expensive.

Now, one might see a blur between a verbless clause (where having is implied) and a noun phrase as the subject-verb disagreement is more clear. However, carpets can mean or be replaced with carpeting so the phrase still strongly suggests a usual noun phrase.
Here is a more complex situation:

Are fast cars in cities really reasonable?

It sounds right, right? The question form tends to have a subject-verb agreement.

Is fast cars in cities really reasonable? [might sound off without using "having"]

and the answer can be:

[Having] fast cars in cities is really reasonable.

Because of this situation, there is an additional category of verbless clauses called nominal verbless clause, which appears to be coined by Quirk (a British linguist) but mentioned as debatable. It can also be described as a noun phrase having the elements of a verbless clause. The version of "A Comprehensive Grammar of the English Language" by Quirk et al. (1985) I've found on Google Books has this excerpt:

The nominal verbless clause is a more debatable category than the other nominal clauses. The category seems to be required to account for construtions which, although superficially noun phrases, have some of the semantic and structural characteristics of clauses:
     A friend in need is a friend indeed. [proverb]
     Wall-to-wall carpets in every room is their dream.


text:
Q: How to build renamed POM xml I am relatively new to Maven. I actually wanted to know how to build the renamed pom.xml i.e.
there is a XML file with the name parent-pom.xml. Shall I directly name it to pom.xml and try building it or is there some other way to do it?

A: Maven looks for the pom.xml file, so you should rename it that for it to work.
You could use another file name using the -f option.
mvn -f parent-pom.xml.


text:
Q: Print (full) value of returned string in main Hi I am very new to the language 'C' I am struggling to print my returned value from the function get_type_of_card() I would like to print it in main on the same line. If I entered in the string "VISA" then the output = VISA.
As of right now the output is just 'V' out of "VISA".
I have one warning I was wondering how to get rid of it.
WARNING: assignment makes pointer from integer without a cast [-Wint conversion] card[i] = c;
I have tried a for loop with putchar().
#include <stdio.h>
#include <ctype.h>

//Function prototypes
const char* get_type_of_card();

int main(void)
{
    const char* type_of_crd = get_type_of_card();
    printf("\nYou entered: %c", type_of_crd);

    return 0;
}

const char* get_type_of_card()
{
    const char* card[50];
    char c;
    int i;

    do
    {
        printf("\nPlease select a credit card: ");
        for (i = 0; (c = getchar()) != '\n'; ++i)
        {
            card[i] = c;
            return card[i]; // Holds value of "VISA"
        }
        card[i] = '\0';
    } while ((c != '\n') && (c != EOF));

}

A: I have achieved my result not sure if it is programmatically correct.
#include <stdio.h>
#include <ctype.h>

//Function prototypes
const char* get_type_of_card();

int main(void)
{
    const char* type_of_crd = get_type_of_card();
    printf("\nYou entered: %s", type_of_crd);

    return 0;
}

const char* get_type_of_card()
{
    static char card[50];
    char c;
    int i;

    do
    {
        printf("\nPlease select a credit card: ");
        for (i = 0; (c = getchar()) != '\n'; ++i)
        {
            card[i] = c;
        }
        card[i] = '\0';
    } while ((c != '\n') && (c != EOF));

    return card;
}


text:
Q: how to pass value from php to python and the python will return the value and echo it using php again How to pass a value from php to python
<?php $print_this = "hello world";
//pass it to python. then echo it in here. "hello world";
?>

how will i pass the value of a variable from php to python and the python will return it and the php will echo it.
import sys
import urllib
from BeautifulSoup import BeautifulSoup as BS

url = '''http://www.kumby.com/avatar-the-last-airbender-book-3-chapter-5/'''
#open and read page
page = urllib.urlopen(url)
html = page.read()
#create BeautifulSoup parse-able "soup"
soup = BS(html)
#get the src attribute from the video tag

        video = soup.find("iframe").get("src")
        print video

the variable url should come from the php. where in php ,
$url = website
and in that  my python code should be
url = $url
or  i dont know how. i just heard that the php can call the python. so i was thinking is it possible to pass the variable of php to python .
now the value of variable video should be echoed in php.

A: You could pipe it:
php myscript.php | python myscript.py

A: you can use $_GET to send the variable to the python script and your python can return the value as api... or may be u can use curl() in php

A: You do not need Python as PHP has multiple ways to parse HTML/XML.
Here is an example using the DOM extension:
<?php

  $url = "http://www.kumby.com/avatar-the-last-airbender-book-3-chapter-5/";
  $page = new DOMDocument;
  $page->loadHTML(file_get_contents($url));
  foreach ($page->getElementsByTagName('iframe') as $node) {
    echo $node->getAttribute('src');
  }

?>


text:
Q: Webpack: HMR Update check failed Error: Manifest Request to ..... timed out at XMLHttpRequest So I have this dev environment through work, and sometimes i can go 20 minutes or so without restarting the server, but most of the time its every little change. this is the error message that pops up

This is my webpack config

var webpack = require("webpack");
var path = require("path");
var SaveHashes = require("assets-webpack-plugin");
var config = require("config");

//used to read in command line args
const args = require('yargs').argv;

var useConfig;

if (args.env && args.env.useConfig){
    useConfig = args.env.useConfig; //must match a key of a configuration
} else {
    useConfig = config.get("useConfig"); //must match a key of a configuration
}

//define config object
var configuration = config.get(useConfig); //the configuration object that has the key of useConfig

var router = ["regenerator-runtime/runtime", "./react/router.jsx"];

if (configuration.router) {
    router = configuration.router;
}

//define global webpack variables that go into definePlugin
var release = (args.env && args.env.BUILD_RELEASE === "true");

var definePlugin = new webpack.DefinePlugin({
    __DEV__: !release,
    __RELEASE__: release,
    __HMR__: true
});

module.exports = {
    entry: {
        router: router
    },
    output: {
        path: path.join(__dirname, "public", "javascripts"),
        filename: "router-bundle.js",
        publicPath: "http://<IP>:8080/javascripts/" // Relative to public folder
    },
    module: {
        loaders: [
            { test: /\.(wav|ttf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/, loader: "file-loader" },
            { test: /\.pug$/, loader: "pug-loader" },
            { test: /\.css$/, loader: "style-loader!css-loader" },
            { test: /\.scss$/, loader: "style-loader!css-loader!sass-loader" },
            { test: /\.(png|jpg)$/, loader: "url-loader?limit=32768" },
            {
                test: /.jsx?$/,
                loader: "babel-loader",
                exclude: /node_modules/,
                query: { presets: ["env", "react", "stage-2"] }
            },
            {
                test: /.js?$/,
                loader: "babel-loader",
                exclude: /node_modules/,
                query: { presets: ["env", "react", "stage-2"] }
            },
            { test: /\.json$/, loader: "json-loader" }
        ]
    },
    node: { fs: "empty" },
    externals: {
        react: "React",
        "react-dom": "ReactDOM",
        uiplugin: "UIFactory",
        "./cptable": "var cptable",
        "./jszip": "jszip"
    },
    resolve: {
        extensions: ["*", ".js", ".jsx"]
    },
    plugins: [definePlugin]
};

I've tried different variations of publicPath value also other different configs with no avail!
webpack version comes up 3.9.1
A faster development process where I don't have to restart the HMR every time I save a file would be nice!


text:
Q: Will nginx+paste hold up in a production environment? I've developed a website in Pylons (Python web framework) and have it running, on my production server, under Apache + mod_wsgi.
I've been hearing a lot of good things about nginx recently and wanted to give it a try. Currently, it's running as  a forwarding proxy to create a front end to Paste. It seems to be running pretty damn fast... Though, I could probably contribute that to me being the only one accessing it.
What I want to know is, how will Paste hold up under a heavy load? Am I better off going with nginx + mod_wsgi ?

A: Your app will be the bottleneck in performance not Apache or Paste.
Nginx is used in lots of production servers so that bit will be fine. I don't know about mod_wsgi but uWSGI is used in production environments and plays well with both nginx and Paste applications.
I currently run a server using Apache + Paste using Apache to serve static content and Paste to handle Pylons. When I stress tested the setup (using default settings on Apache) I got a lot of variation in the time it took to handle requests (varying from 0.5 to 10 secs).
As a test I setup Nginx + uWSGI. Nginx is known to be very good for handling static content and I saw a 10x improvement in the number of files it could serve. The average response time for the Pylons app didn't change (it's DB bound) but the variability dropped to almost zero.
Neither setup dropped a connection or failed to respond so based on this I'll be moving to Nginx + uWSGI for our next app, especially as it has a lot more static content.


text:
Q: SAS parallel processing: Start k parallel jobs subsequently until N jobs are done There might be a simple solution, but currently I cannot get my head around it. Maybe someone could help me out.
So I have the following problem:
I have in total N SAS jobs that I want to finish. As my resources on my machine are too limited to start all N jobs simultaneously, I only want to start say k = 5 at the same time. Every time one job finishes, I want to start the next one. The order in which the jobs are completed is not important.
Currently, I let all k=5 jobs finish before I start the next 5.
So here is the pseudo code, for what I am currently doing:
/*The following macro starts k threads*/
%macro parallel_processing(k);

options fullstimer autosignon=yes sascmd="sas -nonews -threads";

%global thread jj idlist;

/*These are the N ID numbers for the jobs*/
%let idlist = 1 2 3 4 5 ... N;
%let jj = 0;
%do %until(&jj.=N);
    %do thread = 1 %to &k.;
        %let jj = %eval(&thread.+&jj.);
         %syslput thread = &thread;
         %syslput jj = &jj.;
         %syslput idlist = &idlist.;

        rsubmit process=task&thread. wait=no sysrputsync=yes;

          %let id =%scan(%trim(&idlist.),&jj.);
          /*Do the job*/
          %job(id);

        endrsubmit;
    %end;

    /* HERE IS MY PROBLEM:
       I want to wait for each job separately, and start a new one
       with an increased id. So that constantly k threads are busy.
    */

    /* Wait for all threads to finish */
    waitfor _all_ %do thread = 1 %to &k.;
        task&thread
    %end;

    /* GET RESULTS FROM THREADS */
    %do thread = 1 %to (&k.);
        rget task&thread;
    %end;

    /* SIGNOFF THREADS*/
    %do thread = 1 %to (&k.);
        signoff task&thread;
    %end;
%end;
%mend parallel_processing;

%parallel_processing(k);

Maybe somebody has a nice idea, I would be grateful! Thank you in advance.

A: Use waitfor _any_ ... instead of waitfor _all_ ...:

*

*Start the first 5 tasks, keeping a note of which 5 tasks are active.

*Wait for any one of them to finish and remove it from the list of active tasks.

*Start the next task from the queue and add it to the list of active tasks.

*Repeat steps 2 and 3 until there are no tasks left in the queue.

You can use any method you like to keep track of which 5 tasks are currently active.


text:
Q: Python Class member variables initilialization? Came across one Python Class and I am finding it hard to understand how and why its working . A simplified example of the class is :
class Test:
  def __init__(self):
    self.var = 1

  otherVar = 2

  def myPrinter(self):
    print self.__dict__  # Prints {'var': 1}
    print self.var
    print self.otherVar  # Doubt !!
    print self.__dict__  # Prints {'var': 1}

ob = Test()
ob.myPrinter()

My doubt is with the self.otherVar call not throwing an error while self.__dict__ does not show reference to otherVar

A: otherVar is a class member, not instance member, that's why it doesn't show in __dict__.
It appears in self.__class__.__dict__. (this way doesn't work in Python 2.x)
By the way, otherVar member value is shared across all instances and also accessible from type object: Test.otherVar
Example here: https://trinket.io/python3/d245351e58
For a more in depth explanation check here

A: It's because otherVar is an attribute of the class, while the var you setup in the __init__ is an attribute of the instance.
The otherVar is visible to the instance, because python first tries to get the instance attribute values, if the instance doesn't have it, then it checks its class attributes. If you define a var in both with different values, things may get confusing at first.
Well, do you know that comparison that a class is like a blueprint and the instance is the object built following it, right? So, var is an extra you added while creating the instance.
If you want to see otherVar, do Test.__dict__. It won't show you var, but all the class attributes.
Play a little with it and with time you are going to get used to it. Class attributes may be tricky, but extremely useful.


text:
Q: Add text in every word of a multi value variable I have the following variable
var="text1 value1.text value2"

I want to add specific characters at the start and the end of every word in variable
Τhe desired result I want it to be the following
[text1] [value1.text] [value2]

As far I can only add text only in all variable content
echo [$var]

output
[text1 value1.text value2]

Can you help me how to do it
preferably with awk

A: You may use this awk:
awk '{for (i=1; i<=NF; ++i) $i = "[" $i "]"} 1' <<< "$var"

[text1] [value1.text] [value2]

Or a gnu-awk solution without looping:
awk -v RS='[[:space:]]' '{$0 = "[" $0 "]"; ORS=RT} 1' <<< "$var"

[text1] [value1.text] [value2]

A: It's not clear if you want to change the value of var or just output the contents of var with the square brackets added so take your pick:
$ var='text1 value1.text value2'

$ echo "[${var// /] [}]"
[text1] [value1.text] [value2]

$ var="[${var// /] [}]"
$ echo "$var"
[text1] [value1.text] [value2]

A: set -f
var="text1 value1.text value2"
printf -v var "[%s] " $var
echo "${var% }"

Output:
[text1] [value1.text] [value2]