text:
Q: Compute the spectrum of an explicit integral operator Let $H = L^2[0,1]$. Define an operator $K \in B(H)$ by $Kf(x) := x^2 \cdot \int_{0}^{1} y f(y) \; \text{d} y$. Show that $K$ is compact and compute its spectrum.
I already showed that $ ||K || \leq \sqrt{\frac{1}{15}}$ and as K is an bounded integraloperator  with continuous kernel $k(x,y) = x^2y$ it is also compact since it can be approximated by finite rank operators. To compute the spectrum we now want to know  for which $\lambda \in \mathbb{C}$ the operator $ ( \lambda Id - K ) $ is not invertible.
So I tried to solve the equation $ \lambda f(x) - x^2 \int_0^1 y f(y) \; \text{d} y  = g(x) $ for $f(x)$ but I didn't get anything useful on the paper and I dont know if thats the right way to do it.
How can I continue from here? Thank you very much !

A: As observed by Ruy in the comment, $Kf \in \mbox{Span}(x^2)$ for all $f \in L^2([0,1])$ and thus the unique nonzero eigenvalue $\lambda=\frac 1 4$.
In fact $K x^2=x^2 \int_0^1y^3dy=x^2 \frac 1 4$. This also prove that $K$ is compact.


text:
Q: In Twitter Bootstrap, how do I unbind an event from the closing of a modal dialog? I have a function that is bound to the action of hiding a modal dialog.
I'm using code similar to the accepted answer to this question.
$('#myModal').on('hidden', function () {
    // do something…
})

However, this dialog may get reopened for editing, and, when that happens, I don't necessarily want to run this code. Is there a way to "unbind" the function so that it is no longer run when the dialog closes? I haven't found anything in the documentation.

A: You can do something like to unbind all events tied to the modal element:
Unbind all events in the modal:
/* First option */
$('#myModal').on('hidden', function (e) {
    $(e.currentTarget).unbind(); // or $(this)
});

/* Second option is to call it directly when needed */
$('#myModal').unbind();

The Bootrap modal also have specific events tied to it, so you can also specify which event(s) you want to unbind.
/* Events are 'hidden', 'hide', 'show', 'shown' */
$('#myModal').unbind(/* specific event here */);

If you wish to remove events tied to the content of the modal, you can simply just empty the elements within $('#myModal').empty() and unbind those elements appropriately.

A: Use:
$('#myModal').off('hidden');

Why not unbind?

As of jQuery 3.0, .unbind() has been deprecated. It was superseded by the .off() method since jQuery 1.7, so its use was already discouraged.

Source: jQuery API.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Use two Bootstrap carousels on the same page - One single and one with multiple items on one slide I am using two different Bootstrap Carousels on the same page on my wordpress website
One of them is a normal carousel with one item on each slider. The second carousel has three items on each slide and only slides one item each time, like so:
[1, 2, 3] .. [2, 3, 4] .. [3, 4, 1]
The first carousel is working fine, but the second carousel is not.
The second carousel isn't showing the first item after the last one. It is showing two empty items first and then does a weird "jump" (you can see if you visit my website in the URL below).
This is what happens basically:
[1, 2, 3] .. [2, 3, 4] .. [3, 4, blank] .. [4, blank, blank] ..and then jumps back to start.. [1, 2, 3]
However, it is working without any issues if I put the carousel on a page where theres is no other bootstrap carousel! So the problem is in the conflict with the first carousel.
I've been googling and looking at stackoverflow for an answer on my particular situation for many hours without luck.
All the old questions has been for people using two normal carousels and not with a "multislider" involved.
I use unique identifiers for the carousels.
Links to my carousels:
You can see my two carousels in action here (and inspect the code): https://devolt.se/.
Here you can see my second carousel on a test page (it works fine here): https://devolt.se/test/

A: While you do have different identifiers, you don't use them to initiate the each carousel separately. Also, you use slide.bs.carousel event on #carousel-reviews, but then within the scoped function, you apply code to both carousels' items, and that is what is causing that weird behavior.
See your code:
<script>
// Stop portfolio slider from auto looping
$('.carousel').carousel({ //HERE YOU INITIATE BOTH CAROUSELS AT SAME TIME
  interval: false
})
</script>

<script>
jQuery(document).ready(function() {

    /*
        Carousel
    */
    $('#carousel-reviews').on('slide.bs.carousel', function (e) {

        var $e = $(e.relatedTarget);
        var idx = $e.index();
        var itemsPerSlide = 3;
        var totalItems = $('.carousel-item').length;

        if (idx >= totalItems-(itemsPerSlide-1)) {
            var it = itemsPerSlide - (totalItems - idx);
            for (var i=0; i<it; i++) {
                // append slides to end
                if (e.direction=="left") {
                    $('.carousel-item').eq(i).appendTo('.carousel-inner');
                }
                else {
                    $('.carousel-item').eq(0).appendTo('.carousel-inner');
                }
            }
        }
    });

});
</script>

Try initiating them separately, and then manipulate .carousel-item specifically for each carousel:
<script>
    // Stop portfolio slider from auto looping
   $('#carousel-portfolio').carousel({
      interval: false
    })
    $('#carousel-reviews').carousel({
      interval: false
    })
    </script>

    <script>
    jQuery(document).ready(function() {

        /*
            Carousel
        */
        $('#carousel-reviews').on('slide.bs.carousel', function (e) {

            var $e = $(e.relatedTarget);
            var idx = $e.index();
            var itemsPerSlide = 3;
            //also, here, specify selection only to #carousel-reviews:
            var carouselItems = $('#carousel-reviews .carousel-item');
            var totalItems = carouselItems.length;

            if (idx >= totalItems-(itemsPerSlide-1)) {
                var it = itemsPerSlide - (totalItems - idx);
                for (var i=0; i<it; i++) {
                    // append slides to end
                    if (e.direction=="left") {
                        carouselItems.eq(i).appendTo('#carousel-reviews .carousel-inner');
                    }
                    else {
                        carouselItems.eq(0).appendTo('#carousel-reviews .carousel-inner');
                    }
                }
            }
        });
        //and if you need to do this to #carousel-portfolio too:

       $('#carousel-portfolio').on('slide.bs.carousel', function (e) {

            var $e = $(e.relatedTarget);
            var idx = $e.index();
            var itemsPerSlide = 3;
            //also, here, specify selection only to #carousel-reviews:
            var carouselItems = $('#carousel-portfolio .carousel-item');
            var totalItems = carouselItems.length;

            if (idx >= totalItems-(itemsPerSlide-1)) {
                var it = itemsPerSlide - (totalItems - idx);
                for (var i=0; i<it; i++) {
                    // append slides to end
                    if (e.direction=="left") {
                        carouselItems.eq(i).appendTo('#carousel-portfolio .carousel-inner');
                    }
                    else {
                        carouselItems.eq(0).appendTo('#carousel-portfolio .carousel-inner');
                    }
                }
            }
        });

    });
    </script>


text:
Q: Having problem using IIS 8 Self Signed Certificate for SharePoint 2013 High Trust Provider Hosted App During development we were using the Self Signed Certificate from IIS 8 for developing/testing Provider Hosted App we are working on.
Now we need to make changes to the app for Packaging and Publishing. I am following the MSDN documentation Package and publish high-trust apps for SharePoint 2013
I have made the changes in the project, as explained in the MSDN documentation but having issue in the TokenHelper.cs code
    private static X509SigningCredentials GetSigningCredentials(X509Certificate2 cert)
    {
        return (cert == null) ? null
                              : new X509SigningCredentials(cert,
                                                           SecurityAlgorithms.RsaSha256Signature,
                                                           SecurityAlgorithms.Sha256Digest);
    }

    private static X509Certificate2 GetCertificateFromStore()
    {
        if (string.IsNullOrEmpty(ClientSigningCertificateSerialNumber))
        {
            return null;
        }

        // Get the machine's personal store
        X509Certificate2 storedCert;
        X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

        try
        {
            // Open for read-only access
            store.Open(OpenFlags.ReadOnly);

            // Find the cert
            storedCert = store.Certificates.Find(X509FindType.FindBySerialNumber,
                                                 ClientSigningCertificateSerialNumber,
                                                 true)
                           .OfType<X509Certificate2>().SingleOrDefault();
        }
        finally
        {
            store.Close();
        }

        return storedCert;
    }

I have the certificate show up in
  store.Certificates

but the Find method returns an empty collection. Because of which I am getting SigningCredentials was not initialized exception.
Things I verfied -

*

*Went through the steps twice, as mentioned in the MSDN documentation

*Checked the serial number in the web config is correct and all CAPs.

*Self Signed Certificate (.pfx) installed under Personal -> Certificates in Microsoft Certificate Store.

Note - I am doing these steps with Self Signed Certificate and once these steps are successful will be getting the commercial certificate from a CA and proceed to package the app.

A: I had that same issue. Certificate turned up when I used this:
foreach (var certificate in store.Certificates)
{
     if (certificate.SerialNumber.ToLower().Equals(ClientSigningCertificateSerialNumber))
     {
     storedCert = certificate;
     break;
     }
}

Update (original method, slightly changed):
//removes unwanted characters
string newString = new string(ClientSigningCertificateSerialNumber.Where(c => char.IsLetter(c) || char.IsDigit(c)).ToArray());
//use new string in find method
var storedCert = store.Certificates.Find(X509FindType.FindBySerialNumber, newString, true).OfType<X509Certificate2>().FirstOrDefault();

Checking ClientSigningCertificateSerialNumber's length gave me 33 instead of 32. The above code removes unwanted characters and gives the correct length of 32. Using this returns the correct certificate.

A: You can also do that by powershell, this is an example.
https://msdn.microsoft.com/en-us/library/office/fp179901.aspx

A: So I found a way to solve my problem with this change to the tokenhelper code
    private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
    private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
    private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
    private static readonly string ClientSigningCertificateSerialNumber = WebConfigurationManager.AppSettings.Get("ClientSigningCertificateSerialNumber");
    private static readonly X509SigningCredentials SigningCredentials = GetSigningCredentials(GetCertificateFromStore());

    private static X509SigningCredentials GetSigningCredentials(X509Certificate2 cert)
    {
        return (cert == null) ? null
                              : new X509SigningCredentials(cert, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
    }

    private static X509Certificate2 GetCertificateFromStore()
    {
        if (string.IsNullOrEmpty(Convert.ToString(ClientSigningCertificateSerialNumber)) && ClientCertificate != null)
        {
            return ClientCertificate;
        }

        // Get the machine's personal store
        X509Certificate2 storedCert = null;
        X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

        try
        {
            // Open for read-only access
            store.Open(OpenFlags.ReadOnly);

            foreach (var cert in store.Certificates)
            {
                var serialNumber = cert.SerialNumber;
                if (ClientSigningCertificateSerialNumber.Equals(serialNumber, StringComparison.InvariantCultureIgnoreCase))
                {
                    storedCert = cert;
                    break;
                }
            }
        }
        finally
        {
            store.Close();
        }

        return storedCert;
    }

In this code I have handled the Find method issue and also built in logic for continuing to use ClientSigningCertificatePath and ClientSigningCertificatePassword for developers in the team.


text:
Q: Print function customize How i can make every new calculation in new line like this but in print

Now print look like
Can I remove site url (this is url in live-server)in left bottom?
And date too (top left)?
Code HTML:<button type="button" id="Print" onclick="printContent('result')" > Print</button> (result is textarea id).
Code in JS:

function printContent(e) {
    var restorepage = document.body.innerHTML;
    var printcontent = document.getElementById(e).innerHTML;
    document.body.innerHTML = printcontent  ;
    window.print();
    document.body.innerHTML = restorepage;
}

A: //try some like this,

var printcontent = "";

var printcontent2 = "";

for (var x = 0; x <= 10; x++) {

 printcontent = "hi" + x;

console.log(printcontent);

printcontent2 = printcontent2 + printcontent + "<br>";

}
document.body.innerHTML = printcontent2;
window.print();


text:
Q: Scikit-learn multi-label classification I am trying to learn about multi-label classification of texts using Scikit-learn, I am attempting to adapt one of the initial example tutorials which comes with scikit for the classification of languages using wikipedia articles as training data. I am trying to implement this below but the code still returns a single label for each where I would expect the last prediction to return fr, en
Could anyone advice on the correct way to enable multi-label classification.
import sys

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.datasets import make_multilabel_classification
from sklearn.preprocessing import LabelBinarizer

from sklearn.svm import LinearSVC
from sklearn.pipeline import Pipeline
from sklearn.datasets import load_files
from sklearn.cross_validation import train_test_split
from sklearn import metrics
from sklearn.multiclass import OneVsRestClassifier
#change model_selection to cross_validation

# The training data folder must be passed as first argument - This uses the example wiki language data files
languages_data_folder = sys.argv[1]
dataset = load_files(languages_data_folder)

# Split the dataset in training and test set:
docs_train, docs_test, y_train, y_test = train_test_split(
dataset.data, dataset.target, test_size=0.5)

#pipeline
clf = Pipeline([
('vectorizer', CountVectorizer(ngram_range=(1,2))),
('tfidf', TfidfTransformer()),
('clf', OneVsRestClassifier(LinearSVC())),
])
    target_names=dataset.target_names

# TASK: Fit the pipeline on the training set
clf.fit(docs_train, y_train)

# TASK: Predict the outcome on the testing set in a variable named y_predicted
y_predicted = clf.predict(docs_test)

print target_names

# Predict the result on some short new sentences:
sentences = [
    u'This is a language detection test.',
    u'Ceci est un test de d\xe9tection de la langue.',
    u'Dies ist ein Test, um die Sprache zu erkennen.',
    u'Bonjour Mon ami. This is a language detection test.',

]
predicted = clf.predict(sentences)

for s, p in zip(sentences, predicted):
    print(u'The language of "%s" is "%s"' % (s, target_names[p]))

Returns -
The language of "This is a language detection test." is "en"
The language of "Ceci est un test de détection de la langue." is "fr"
The language of "Dies ist ein Test, um die Sprache zu erkennen." is "de"
The language of "Bonjour Mon ami. This is a language detection test." is "en"

A: You can use scikit-multilearn for multi-label classification, it is a library built on top of scikit-learn. With languages, the correlations between labels are not that important so a Binary Classifier should be well suited. You can find examples of how to do the classification in documentation but in your case what you need is to replace:
('clf', OneVsRestClassifier(LinearSVC())),

with
('clf', BinaryRelevance(LinearSVC())),

and at the top add the import:
from skmultilearn.problem_transform import BinaryRelevance

Just remember to install scikit-multilearn first!


text:
Q: Failing to build a node.js plugin that references the libjpeg library I have copied the libjpeg library into the 'c' directory where I am keeping the C and C++ source code for my node.js application.
I have used the binding.gyp file to point to the C++ file, and it has built successfully. However, when I add the line
#include "libjpeg-master/jpeglib.h"

I get the error message
fatal error C1083: Cannot open include file: 'jconfig.h': No such file or directory [...]

I am attempting to build the libjpeg library alongside the node.js code, rather than first building libjpeg using the build configuration there.
How should I go about solving this. If the answer is to use the build configuration from libjpeg, how can I get that to work when building a node.js plugin?
I am currently developing this on Windows but I want to get this working properly for all platforms.


text:
Q: State changes after second click of onPress in react native I have a made a custom checkbox for my application.
constructor(props) {
    super(props);
    this.state = {
      checkValue1: false,
      color1: 'white',
    };
  }

checkBox1 = () => {
        if (this.state.checkValue1 == false) {
          this.setState({
            color1: 'white',
            checkValue1: true,
          });
        } else if (this.state.checkValue1 == true) {
          this.setState({
            color1: '#70AD47',
            checkValue1: false,
          });
        }
      };

  <TouchableOpacity style={styles.checkBorder} onPress={this.checkBox1}>
    <Icon name="checkmark" type="ionicon" size={20} color={this.state.color1} />
  </TouchableOpacity>

checkBorder: {
    backgroundColor: "blue",
    width: 20,
    height: 20,
    borderColor: '#7F7F7F',
    borderWidth: 1.5,
    borderRadius: 3,
  },

It's working all fine. But only problem is that, icon color changes after second click. After that it changes with every click. Issue is only that it should change color after first click itself. I don't know what I am missing out in my code

A: Try this way
checkBox1 = () => {
  if (this.state.checkValue1 == false) {
    this.setState({
      color1: "#70AD47", // change here
      checkValue1: true,
    });
  } else if (this.state.checkValue1 == true) {
    this.setState({
      color1: "white",  // change here
      checkValue1: false,
    });
  }
};


text:
Q: How to add multiple css files to CKEditor editorarea I have created a small mvc application using Ckeditor that should use some css files that are stored on a local server
<head>
<link href="http://fonts.googleapis.com/css?family=Droid+Sans" rel="stylesheet" type="text/css" />
<link href="http://fonts.googleapis.com/css?family=Bree+Serif" rel="stylesheet" type="text/css" />
<link href="http://fonts.googleapis.com/css?family=Droid+Sans+Mono" rel="stylesheet" type="text/css" />
<link href="http://192.168.0.50/css/new/all.css?v=1" media="all" rel="stylesheet" type="text/css" />
<link href="http://192.168.0.50/css/new/templates.css?v=1" media="all" rel="stylesheet" type="text/css" />
<link href="http://192.168.0.50/css/pre_review/colors.css?v=1" rel="stylesheet" type="text/css" />
<link href="http://192.168.0.50/css/pre_review/paged_test.css?v=2" media="paged" rel="stylesheet" type="text/css" />
<link href="http://192.168.0.50/css/pre_review/bootstrap.min.css?v=1" media="all" rel="stylesheet" type="text/css" />
<link href="http://192.168.0.50/css/pre_review/main.css?v=1" rel="stylesheet" type="text/css" />
<style type="text/css">html { -ro-editable: true; }
</style>
</head>

At the initialization of the editor i call setData and pass in a string with that html block to apply the remote css files to the content of the editor. However they are not being applied correctly
if i set config.fullPage = true then the html block gets put in between the body tags and thus can be deleted if the user presses the backspace key enough.
I have also tried setting config.fullPage =false, this inserts the content fine however it strips the head tags from the block so it can also be deleted by the user if they press backspace.
Is there anyway of getting this html block to go specifically in the head section so that it cannot be edited?

A: I recommend to use the config.contentsCss property in your ckeditor config, to set a specific css file or a list of css files.
See API Docs: http://docs.ckeditor.com/#!/api/CKEDITOR.config-cfg-contentsCss
Since version 4.4 it is also possible to add more than one stylesheet during runtime to the editor instance with editor.addContentsCss(), see http://docs.ckeditor.com/#!/api/CKEDITOR.editor-method-addContentsCss for more info.
May the source be with you. Have Fun.


text:
Q: Swagger-Codegen: How to stuff JSON blob in a String I'm using a swagger yaml file to define my API and generate Java code out of it. With this structure:
SomeStructure:
  type: object
  properties:
    field1:
      type: string
      required: true
    field2:
      type: string
      required: true
    field3:
      type: string
      additionalProperties: {}

Now, once API code generation is done, I would like the 3rd field to flatten any specified JSON structure into a Java String.
For instance, for an input like this:
{
    "field1":"value1",
    "field2":"value2",
    "field3":{
        "subvalue1":"subvalue1",
        "subvalue2":"subvalue2"
  }
}

I want it to get mapped to a String containing:
{"subvalue1":"subvalue1","subvalue2":"subvalue2"}

I tried to use the freeform indicator '{}', but obviously, it's not working. Is it possible, and how do I do this?


text:
Q: AWS Elastic Beanstalk error I cannot deploy I am new to AWS Beanstalk and there was an existing project that I'm working with that is deployed but I had to change the Private Key associated with it and after updating the security and pairing it with another private key, the instance was remade and now I get this...
Could someone please help me figure out what to do? really appreciate it!....
Command failed on instance. Return code: 1 Output: (TRUNCATED)...our Certbot configuration directory at /etc/letsencrypt. You should make a secure backup of this folder now. This configuration directory will also contain certificates and private keys obtained by Certbot so making regular backups of this folder is ideal. container_command 20_getcert in .ebextensions/00_apache_ssl.config failed. For more detail, check /var/log/eb-activity.log using console or EB CLI.
Obtaining a new certificate
  Performing the following challenges:
  http-01 challenge for domain.com
  Cleaning up challenges
  Exiting abnormally:
  Traceback (most recent call last):
  File "/opt/eff.org/certbot/venv/bin/letsencrypt", line 11, in
  sys.exit(main())
  File "/opt/eff.org/certbot/venv/local/lib/python2.7/site-packages/certbot/main.py", line 14, in main
  return internal_main.main(cli_args)
  File "/opt/eff.org/certbot/venv/local/lib/python2.7/site-packages/certbot/_internal/main.py", line 1350, in main
  return config.func(config, plugins)
  File "/opt/eff.org/certbot/venv/local/lib/python2.7/site-packages/certbot/_internal/main.py", line 1237, in certonly
  lineage = _get_and_save_cert(le_client, config, domains, certname, lineage)
  File "/opt/eff.org/certbot/venv/local/lib/python2.7/site-packages/certbot/_internal/main.py", line 121, in _get_and_save_cert
  lineage = le_client.obtain_and_enroll_certificate(domains, certname)
  File "/opt/eff.org/certbot/venv/local/lib/python2.7/site-packages/certbot/_internal/client.py", line 416, in obtain_and_enroll_certificate
  cert, chain, key, _ = self.obtain_certificate(domains)
  File "/opt/eff.org/certbot/venv/local/lib/python2.7/site-packages/certbot/_internal/client.py", line 347, in obtain_certificate
  orderr = self._get_order_and_authorizations(csr.data, self.config.allow_subset_of_names)
  File "/opt/eff.org/certbot/venv/local/lib/python2.7/site-packages/certbot/_internal/client.py", line 395, in _get_order_and_authorizations
  authzr = self.auth_handler.handle_authorizations(orderr, best_effort)
  File "/opt/eff.org/certbot/venv/local/lib/python2.7/site-packages/certbot/_internal/auth_handler.py", line 70, in handle_authorizations
  resps = self.auth.perform(achalls)
  File "/opt/eff.org/certbot/venv/local/lib/python2.7/site-packages/certbot_apache/_internal/configurator.py", line 2301, in perform
  http_response = http_doer.perform()
  File "/opt/eff.org/certbot/venv/local/lib/python2.7/site-packages/certbot_apache/_internal/http_01.py", line 76, in perform
  self._mod_config()
  File "/opt/eff.org/certbot/venv/local/lib/python2.7/site-packages/certbot_apache/_internal/http_01.py", line 111, in _mod_config
  for vh in self._relevant_vhosts():
  File "/opt/eff.org/certbot/venv/local/lib/python2.7/site-packages/certbot_apache/_internal/http_01.py", line 166, in _relevant_vhosts
  " {0}.".format(http01_port))
  PluginError: Unable to find a virtual host listening on port 80 which is currently needed for Certbot to prove to the CA that you control your domain. Please add a virtual host for port 80.
  Please see the logfiles in /var/log/letsencrypt for more details.
  IMPORTANT NOTES:
  - Your account credentials have been saved in your Certbot
  configuration directory at /etc/letsencrypt. You should make a
  secure backup of this folder now. This configuration directory will
  also contain certificates and private keys obtained by Certbot so
  making regular backups of this folder is ideal.
   (ElasticBeanstalk::ExternalInvocationError)

A: You have web server configuration issue, that's why certbot cannot validate your domain, check the configuration below for the recommended setup
https://gist.github.com/cichondev/08056094a27cfcc7424afc3afcbf781c


text:
Q: Have issues to make paytm payment integration live in flutter For Test MID I am able to pay successfully but when i try to make it live with my production key and production MID of paytm i am getting error of 'Invalid: This MID is not available on our staging environment' and i am using 'https://securegw.paytm.in/theia/paytmCallback?ORDER_ID=' callback url for production as instuction given for paytm but still i am not able to make payment in production environment. Below is my flutter code :
class _MyAppState extends State<MyApp> {
  String payment_response = '';
  final String M_ID = "";      //Production MID
  final String CHANNEL_ID = "WAP";// type here your channel id given by paytm
  final String INDUSTRY_TYPE_ID = "Retail";  // type here your industry type id given by paytm
  final String WEBSITE = "DEFAULT";    //for production

  TextEditingController amountController = new TextEditingController();

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Paytm example app'),
        ),
        body: Padding(
          padding: EdgeInsets.all(10.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              TextFormField(
                controller: amountController,
                decoration: InputDecoration(
                  hintText: 'Enter Amount',
                  prefix: Text('Rs. '),
                ),
                keyboardType: TextInputType.number,
              ),
              SizedBox(height: 5.0,),
              RaisedButton(
                onPressed: () {
                  //Firstly Generate CheckSum bcoz Paytm Require this
                  generateCheckSum();
                },
                color: Colors.blue,
                child: Text(
                  "Pay Now",
                  style: TextStyle(color: Colors.white),
                ),
              ),
              SizedBox(height: 20.0,),
              Text('Response: $payment_response\n'),

            ],
          ),
        ),
      ),
    );
  }

  void generateCheckSum() async {
    var url =
        'https://promiseacademy.co.in/flutterapp/paytm/generateChecksum.php';

    String orderId = DateTime
        .now()
        .millisecondsSinceEpoch
        .toString();

    String callBackUrl =
    'https://securegw.paytm.in/theia/paytmCallback?ORDER_ID=' +
        orderId;

    //Please use your parameters here
    //CHANNEL_ID etc provided to you by paytm

    final response = await http.post(url, headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    }, body: {
      "M_ID": M_ID,
      "CHANNEL_ID": CHANNEL_ID,
      'INDUSTRY_TYPE_ID': INDUSTRY_TYPE_ID,
      'WEBSITE': WEBSITE,
      'TXN_AMOUNT': amountController.text,
      'CALLBACK_URL': callBackUrl,
      'ORDER_ID': orderId,
      'CUST_ID': '1',
    });

    //for Testing(Stagging) use this

    //https://securegw-stage.paytm.in/theia/paytmCallback?ORDER_ID=

    //https://securegw.paytm.in/theia/paytmCallback?ORDER_ID=

    if (response.statusCode == 200) {
      var result = json.decode(response.body);

      print("Response :" + response.body + "\nchecksumhash:" + result['CHECKSUMHASH']);

      var paytmResponse = Paytm.startPaytmPayment(
          true,
          M_ID,
         orderId,
          "1",
          CHANNEL_ID,
          amountController.text,
          WEBSITE,
          callBackUrl,
          INDUSTRY_TYPE_ID,
          result['CHECKSUMHASH']);

      paytmResponse.then((value) {
        setState(() {
          payment_response = value.toString();
        });
      });
    }
    else{
      print(response.statusCode);
    }
  }
}

A:  var paytmResponse = Paytm.startPaytmPayment(
          true,
          M_ID,
         orderId,
          "1",
          CHANNEL_ID,
          amountController.text,
          WEBSITE,
          callBackUrl,
          INDUSTRY_TYPE_ID,
          result['CHECKSUMHASH']);

Please change first parameter to false from true in Paytm.startPaytmPayment(). That parameter indicates isTesting. If you keep true, it is taking staging details and giving you error for production details not found.


text:
Q: StreamReader doesn't take string? I'm trying to read a file with a StreamReader, but I get an error for using path

Argument 1: cannot convert from 'string' to System.IO.Stream

even though it's clear from the documentation, that you should be able to use a string.
What am I missing here?
public MyClass Load(String path)
{
    try
    {
        // exception in this line, `path` is underlined with red
        using (StreamReader reader = new StreamReader(path))
        {
            String line = reader.ReadLine();
// ... etc

A: I can't tell if you got your answer or not but the proper syntax for UWP is below:
using (var sr = new StreamReader(new FileStream(filenamestring, FileMode.Open)))


text:
Q: cannot read local xml file with jquery $.ajax I want to use an XML file for creating a sort of Dynamic website with jquery.
When testing on a local webserver i see via developer console on chrome that the xml file is not visible.
When opening the homepage in the local file (not using the webserver) I get the following error:
XMLHttpRequest cannot load file /// . Cross origin requests are only supported for protocol schemes: http, data, ...
I read XMLHttpRequest cannot load file. Cross origin requests are only supported for HTTP but since am using an IIS local server I already rules that out.
My code for reading the xml:
$.ajax({

    type: "GET",
    url: "data.xml",
    dataType: "xml",
    success: function(xml){
        var xmlDoc = $.parseXML(xml);
        var root = $(xmlDoc).find("root");
        alert(root);
    }

});

the project i have exists out of a few files:
index.html
code.js            ==> my own code
jquery.js          ==> jquery code
style.css
data.xml
Web.config         ==> I'm not entirely sure if i need this since i won't be using connections.
Website.sln        ==> I use a vs2013 express edition

This is my first project with jquery and though the adding and dropping of html content works perfectly, reading out an XML file keeps me at bay. I created a web.config file via visual studio express but i'm not entirely sure that i need this.
EDIT:
with the following changes I got it done:
firstly: replace the data.xml to a subdirectory (I don't know if it was this or not)
secondly: drop the parseXML function and go for a
$(this).find(name).each(function(){ //your code });

Eh voila, no back to programming...

A: with the following changes I got it done:
firstly: replace the data.xml to a subdirectory (I don't know if it was this or not)
secondly: drop the parseXML function and go for a
$(this).find(name).each(function(){ //your code });
url then became = url: "../data/data.xml",


text:
Q: Function sending null sets to null sets. Okay, so here's a question I was ask forever ago, but to this day, I haven't been able to find a solution the
Let $[a,b] \subset \mathbb{R}$ be compact. Then, if $f \colon F \to \mathbb{R}$ is continuous, show that the following are equivalent, where $E \subset [a,b]$:
$m(f(E)) = 0$ whenever $m(E) =0$ iff $f(E)$ is measurable whenever $E$ is measurable.
We begin by showing that $f$ sends $F_{\sigma}$ sets to $F_{\sigma}$ sets. To begin, let $K = \cup_{n=1}^{\infty} F_n$, where $K \subset [a,b]$ and $F_n$ is closed for each $n \geq 1$. Notice that
$$
f(K) = f\left( \bigcup_{n=1}^{\infty} F_n \right) = \bigcup_{n=1}^{\infty} f(F_n),
$$
and by noting that each $F_n \subset F$ is bounded for each $n \geq 1$, by the continuity of $f$, we see that $f(F_n)$ is compact for each $n$. But then, since each $f(F_n)$ is compact, it follows that each $f(F_n)$ is closed. Thus, we see that $f(K) = \bigcup_{n=1}^{\infty} f(F_n)$ is an $F_{\sigma}$ set.
Now, suppose that $m^*(f(E)) = 0$ whenever $m^*(E) = 0$ for $E \subset [a,b]$. In addition, suppose that $K \subset [a,b]$ is measurable. Then, $K = J \cup W$, where $J, W \subset [a,b]$ are such that $J$ is an $F_{\sigma}-$set and $W$ is a null set. But then, $f(K) =f \left(J \cup W \right) = f(J) \cup f(W)$. But, we show that $f$ sent $F_{\sigma}-$set to $F_{\sigma}-$sets and we assumed that $f$ preserves nullsets, and so $f(W)$ is a null set and $f(J)$ is an $F_{\sigma}-$set. Thus, again, by The Fun Theorem, we see that $f(K)$ is measurable.
I cannot get the other implication.  I want to argue by contradiction, however, I'm not sure if this is good.

A: So suppose there exists a set $E$ such that $m(E) = 0$, and $m(f(E)) \ne 0$.  For each $y \in f(E)$, choose one point $x_y \in E$ such that $f(x_y) = x$.  Then by replacing $E$ by $\{x_y : y \in f(E)\} \subset E$, we may suppose without loss of generality that $f$ is injective on $E$.
Now if $f(E)$ is not measurable, we are done.  Otherwise $m(f(E)) > 0$, so we can find a non-measurable subset $H \subset f(E)$.  Then $E' = E \cap f^{-1}(H)$ has measure zero and is hence measurable, but $f(E') = H$ is not measurable.
Let us show how to find $H$.  So there exists $n\in \mathbb N$ so that $m(f(E) \cap[-n,n)) > 0$.  Let $T_t(x) = ((x+t+n) \bmod 2n) -n$ be the usual circular translation on $[-n,n)$ by $t$.  Define an equivalence relation $x \sim y$ if and only if $x-y \in \mathbb Q$, and let $K \subset [-n,n)$ pick one element from each equivalence class of $\sim$.  Then $T_q(K) \cap E$ ($q \in \mathbb Q$) is a disjoint countable collection of subsets of $E$.  If all of the $T_q(K) \cap E$ are measurable, then ther exists $\tilde q \in \mathbb Q$ such that $T_{\tilde q}(K) \cap E$ has measure greater than $0$.  But then $T_q(T_{\tilde q}(K) \cap E)$ ($q \in \mathbb Q$) is a disjoint countable collection of subsets of $[-n,n)$, each having the same positive measure, which is a contradiction.  Hence there exists a $q \in \mathbb Q$ such that $T_q(K) \cap E$ is non-measurable.


text:
Q: How to post a task on a celery-rabbitmq queue in PHP? I have below versions of celery and rabbitmq installed -

celery 3.1.6
  rabbitmq 3.1.1

I can post a task to the default queue from PHP -
//client.php
<?php
require 'celery-php/celery.php';
$c = new Celery('localhost', 'guest', 'guest', '/');
$result = $c->PostTask('tasks.add', array(2,2));

My worker module is in python -
# tasks.py
from celery import Celery
celery = Celery('tasks', broker='amqp://guest:guest@localhost:5672//')
@celery.task(queue='demo', name='add')
def add(x, y):
    return x + y

I run the celery worker and client like this -
# terminal window 1
$ celery -A tasks worker --loglevel=info
# terminal window 2
$ php -f client.php

This works. I see below output in terminal window 1 :
Received task: tasks.add[php_52b1759141a8b3.43107845]
Task tasks.add[php_52b1759141a8b3.43107845] succeeded in 0.000701383920386s: 4

But I want to have different queues. For a demonstration, let's say I only want one queue called demo. So I run my celery worker like this -
$ celery -A tasks worker --loglevel=info -Q demo

But it's not working. The task is not getting executed. I guess it's probably because PHP code is posting the task on default queue : celery (apparently not on demo queue).
How do I post my task on a particular queue in PHP? Please help.

A: By default, your PHP client for Celery takes the queue name as "celery".
In order to change the queue to publish to, you must specify the queue name while instantiating a connection to Celery.
So, if you are starting your Celery worker with "-Q demo" option, then your connection to Celery in PHP should be -
$exchange = 'demo';
$binding = 'demo';
$c = new Celery('localhost', 'guest', 'guest', '/', $exchange, $binding);

Note: With -Q option, the exchange and routing_key value is same as queue_name.
Please try this and share the results.
About exchange and binding :
With analogy to Telephone Services, Exchange is like "Telephone Operator", whose only job is to "Direct the call to YOU" with the help of routing_key.
Binding is then "Your Telephone Number", which acts as routing_key to your telephone.
Note : This process where exchange is redirecting the incoming message to the queue based on binding (routing_key), is a DIRECT exchange type.
AMQP has few other types of exchanges, which you can read in AMQP documentation.
You can also refer this Celery page


text:
Q: Issue with JQuery window resize function calls I have a resize method in my js file :
$(window).resize(function(){
    my_function();
});

In it i have loads of other functions which need to be called when the window is resized (for the responsive part of a website) ,i have not included all these functions as the problem i keep facing is the same in the one i am about to post.
It can't be simpler :
function my_function() {
    console.log('1');
    $('body').click(function(){
        console.log('2');
    });
   }
   my_function();
//when the function is called the console logs 1,when you click on the body ,it logs 2.

Now the problem, when I resize the window (for example : from full window to half in 2s),the resize() fires a couple of times (for example :  10 [every time it's different]).I know this because in the console the number 1 is called/logged 10 times as the window is being resized.Now,after i finished resizing the window, when i click on the body, the console logs the number 2 the same amount of times (10).
Why ? And how can i make it fire the click.function only once ?
Alex.
UPDATE 1 : in addition,every subsequent click on the body logs 2 another 10 times (so if i click 5 times,the console will log the number 2 50 times.


text:
Q: Why virtual function has to be implemented in superclass? I am trying to compile the following code:
#include <iostream>
class X{
public:
    virtual void func();
};
class Y : public X{
public:
    virtual void func(){
        std::cout << "y" << std::endl;
    }
};
int main(){
    Y* y = new Y();
    y->func();
    return 0;
}

But building fails (on Xcode - C++11) with the following messages:
Undefined symbols for architecture x86_64:
  "typeinfo for X", referenced from:
      typeinfo for Y in c.o
  "vtable for X", referenced from:
      X::() in c.o
  NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

However, as soon as I add an implementation for func in X, it builds successfully. I am pretty sure, that virtual method is optional to be implemented in the superclass but I don't understand why is this happening. Also, if comment the code in main(), it builds successfully. I am assuming that the problem is calling the func() in main, but Xcode doesn't list it as runtime error, it only says build-time error.

A: If you don't want to implement the virtual function in the base class at all, simply mark it as pure virtual:
virtual void func() = 0;

A: No, you are wrong. You need to have implementations for non-pure virtual functions. If you do not want to provide an implementation, you need to make function pure virtual, using = 0 syntax.


text:
Q: C# MVC site - saving canvas to an image file on the server - image is being cropped I'm creating an admin system where a user(admin) can create users. The system requires a user to have a photograph.
I've implemented a file upload but I am also trying to provide the option to use a webcam to take an image and use that.
I've pretty much got this working EXCEPT that the image I manage to save on the server is cropped at the bottom.
I assumed it was something to do with the size of the canvas/video elements that I have used. I tried to hard code larger sizes but it had no effect.
In the UI the image is captured from the video element and displayed on the canvas as I want it to be.
I've added a text box that's bound to my Model so I can pass the canvas as text to the server.
Here's the code:
<video id='v' class="employee-image-display"></video>
@Html.TextBoxFor(m => m.WebcamImageData, new { id = "tbWebcamImage" })

<canvas id="canvas"></canvas>

Javascript:
function TakePhoto() {

    var canvas = $('#canvas')[0];
    //set canvas width/height
    canvas.width = 600;//v.videoWidth;
    canvas.height = 600;//v.videoHeight;

    canvas.getContext('2d').drawImage(v, 0, 0, 600, 600, 0, 0, 600, 600);

    //get image data from canvas
    var imgData = canvas.toDataURL("img/png");
    imgData = imgData.replace(/^data:image\/(png|jpg);base64,/, "");

    $('#tbWebcamImage').val(imgData);

}

function StartWebCam() {
    navigator.getUserMedia = (navigator.getUserMedia ||
                  navigator.webkitGetUserMedia ||
                  navigator.mozGetUserMedia ||
                  navigator.msGetUserMedia);
    if (navigator.getUserMedia) {
        navigator.getUserMedia(
           {
               video: true,
               audio: false
           },
 function (stream) {
     var url = window.URL || window.webkitURL;
     v.src = url ? url.createObjectURL(stream) : stream;
     v.play();
 },
 function (error) {
     alert('Something went wrong. (error code ' + error.code + ')');
     return;
 }
        );
    }
    else {
        alert('Sorry, the browser you are using doesn\'t support getUserMedia');
        return;
    }
}

$(document).ready(function () {

    $('#btnTakePhoto').on('click', function () {
        TakePhoto();
    });
    StartWebCam();
});

Controller Action:
if (!string.IsNullOrWhiteSpace(model.WebcamImageData))
{
    using (var stream = new MemoryStream())
    {
        using (var writer = new BinaryWriter(stream))
        {
            writer.Write(bytes);
            stream.Seek(0, SeekOrigin.Begin);

            string filepath = "~/Content/Images/Employees/test.png";

            System.IO.File.WriteAllBytes(Server.MapPath(filepath), bytes);
        }
    }
}

As you can see - the image is cropped (you should be able to see my chest as in the image below). Here is what the UI looks like when I click the "Take Photo" button:

As you can see - Not cropped.
Can anyone tell me why my image is being cropped? - is the error client or server side?

A: Which browser are you using?
Try the following to set the video and canvas dimensions correctly.
var v = document.getElementById('v');
var c = document.getElementById('c');
var canvasWidth = 600;
var canvasHeight = 600;

// Wait until the video stream can play
v.addEventListener('canplay', function (e) {
    if (!isStreaming) {
        // videoWidth isn't always set correctly in all browsers
        if (v.videoWidth > 0) {
            canvasHeight = v.videoHeight / (v.videoWidth / canvasWidth)
        }
        v.setAttribute('width', canvasWidth);
        v.setAttribute('height', canvasHeight);
        c.setAttribute('width', canvasWidth);
        c.setAttribute('height', canvasHeight);
        isStreaming = true;
    }
}, false);

Also make your code more cross browser friendly...
// Cross browser
navigator.getUserMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);

if (navigator.getUserMedia) {
    // Request access to video only
    navigator.getUserMedia(
                {
                    video: true,
                    audio: false
                },
                function (stream) {
                    // Cross browser checks
                    var url = window.URL || window.webkitURL;
                    v.src = url ? url.createObjectURL(stream) : stream;
                    // Set the video to play
                    v.play();
                },
                function (error) {
                    alert('Something went wrong. (error code ' + error.code + ')');
                }
    );
}
else {
        alert('Sorry, the browser that you are using isn\'t supported.');
        return;
     }

EDIT: For the context try the following:
var con = c.getContext('2d');
con.drawImage(v, 0, 0, canvasWidth, canvasHeight);


text:
Q: Is there a faster way to apply a function to all the strings within a multidimensional array than using foreach? (PHP) Here's my iteration:
foreach ($this->itens as $i => $i_val) {
    foreach ($i_val as $j => $j_val) {
        if (is_string($this->itens[$i]->$j)) {
            $this->itens[$i]->$j = iconv(mb_detect_encoding($this->itens[$i]->$j, mb_detect_order(), true), "UTF-8", $this->itens[$i]->$j);
        }
    }
}

This running each time something is loaded from the Database is just too performance-killer, and it's quite necessary since the previous programmers screwed the database with multiple random encodings. Anyway, is there a faster way to perform this operation in PHP? A traditional while loop is faster than a foreach? Is there a function that can apply a function to all the inner contents, like map on Python or similar?

A: I think http://php.net/manual/en/function.array-walk-recursive.php will do what you are after?
array_walk_recursive() is similar to array_walk(), applying your function, but does it in a multi-dimensional/recursive sense - basically it does what the name says!
As you've got a bit of logic in there, you'd have to write your own function that comprises the comparison and the resultant return value, and then pass that function to the array_walk_recursive() function (or depending on your PHP version, you could write it as an anonymous function):
$this->itens = array_walk_recursive($this->itens,function($param,$key){
    if (is_string($param)) {
        return iconv(mb_detect_encoding($param, mb_detect_order(), true), "UTF-8", $param);
    }else{
        return $param;
    }
});


text:
Q: Display and play audio files I am new to python, and I'm trying to build a simple recording program. With the some help from my previous question, I was able to add a timestamp for each recorded file
EDIT:
I did some research and decided on displaying the files with filechooser... this still does not work
def openfiles(self, *args):

    satter2 = BoxLayout(pos= (629, 950), size_hint= (.1,.1))
    self.fclv = FileChooserListView(path= '/sdcard/', filters= ['*.3gp'])
    self.fclv.bind(on_selection= self.pressed(fclv.selection)
    scatter.add_widget(self.fclv)

    self.add_widget(satter2)

def pressed(self, filename):
     #with open(os.path.join(path, filename[0]))

    if self.soundf is None:
        self.soundf = SoundLoader.load(self.path)
    if self.soundf.status != 'stop':
        self.soundf.stop()
    self.soundf.loop = False
    self.soundf.play()

A: Here is a simple example of how to show all 3gp files in your current directory.
from kivy.app import App
from kivy.uix.filechooser import FileChooserListView
from kivy.uix.boxlayout import BoxLayout

class MyLayout(BoxLayout):

    def __init__(self,**kwargs):
        super(MyLayout,self).__init__(**kwargs)
        self.fclv = FileChooserListView(path= '.', filters= ['*.3gp'])
        self.add_widget(self.fclv)

class MyApp(App):

    def build(self):
        return MyLayout()

MyApp().run()

Result is:


text:
Q: What is the difference between the ViewContext.Writer and System.Web.Mvc.IView Render(...) Writer? The MVC 5 IView.Render method has the following signature:
void Render(
    ViewContext viewContext,
    TextWriter writer
)

Meanwhile, ViewContext also has the Writer property:
public virtual TextWriter Writer { get; set; }

In the Render method, what is the difference between these two TextWriter instances? When should I use one vs the other when rendering the content of the IView?


text:
Q: how to export svg to png on the command line without antialiasing I need to do some batch processing of svg files.  SVG elements are all either black or white and I need bitmap images that are monochrome (black/white, no grayscale).
From within the inkscape gui I can just select this as an option.

However, I don't see any inkscape cli options related to antialiasing
Same for librsvg, (rsvg-convert) no command line options in the manual related to anti-aliasing.
Second thought was to just export to a png image and then use ImageMagick to threshhold the image.  However, on my system
Mac OSX catalina (latest)
brew install imagemagick -> 7.0.10-23

when I run the following, i get an error:
>>> convert test.im.png -channel RGB -threshhold 50% test.im.t.png
convert: unrecognized option `-threshhold' @ error/convert.c/ConvertImageCommand/3112.

looking for a little help on how to get from a black and white svg to a black and white png on the command line for batch processing given these problems.

A: On IM 7, use magick, not convert. So try
magick +antialias image.svg -channel RGB result.png

or
magick image.svg -channel RGB -threshold 50% result.png

If one of these works, then you can process a whole folder of files using magick mogrify. See https://imagemagick.org/Usage/basics/#mogrify


text:
Q: Simple Cocoa App with ViewController I am trying to create a custom NSViewController and just log something out in viewDidLoad.  In iOS, this is very trivial and works fine.  However, when I setup a contentViewController on NSWindow (which i assume is similar to RootViewController in iOS?) it attempt to load it from a nib.
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {

   self.ABViewController = [[ABViewController alloc] init];

   self.window.contentViewController = self.ABViewController;

}

2016-06-28 09:15:42.186 TestApp[32103:33742217] -[NSNib _initWithNibNamed:bundle:options:] could not load the nibName: ABViewController in bundle (null).

What assumptions am I missing about how Cocoa is different from iOS that prevent me from simply setting up a viewController?

A: It looks like your program wan't find the file where the view's are defined. You need to do something like this for storyboards:
UIStoryboard *sboard = [UIStoryboard storyboardWithName:@"StoryboardFileName"
                                             bundle:NSBundle.mainBundle()];
SecondViewController *vc1 = [sboard instantiateInitialViewController];

A: NSViewController doesn't have the same behavior as UIViewController, in that it won't automatically know to look for a nib file with the same name as itself. In other words, it won't automatically know to look for the ABViewController.nib file.
The simplest way to fix this is just override the nibName method in ABViewController:
@implementation ABViewController

- (NSString *)nibName {
    return NSStringFromClass([self class]);
}

@end

Note that using NSStringFromClass() is usually better than trying to hard code the string, as this way will survive refactoring.
You can then call [[ABViewController alloc] init]; like before and NSViewController's default init method will get the nib name from your overridden nibName method.


text:
Q: where do i download gene expression data? i wanted to download gene expression data derived from generated by microarray experiments. i do not know too much about this subject, but as i understand, rows often correspond to genes and columns corresponds to samples. ideally, i expect a matrix of gene expression data.
i've been searching on the internet, and although it may seem like there are many places to download such data, when i actually do download the data, i do not get the matrix of gene expression. could someone please let me know if there is a place or how to download gene expression data in the format that i expect above?
any help is appreciated.

A: If you look at e.g. this entry in the Gene Expression Omnibus, one of the file formats is "TXT" and contains a matrix like you are asking for, after some metadata.

A: In principle microarray data can be expressed (please pardon the pun) as a matrix with samples as columns and rows as genes. In practice it is a good bit more complicated to derive such a representation for the raw data of an experiment. If you just get a pre-processed dataset you have little guarantee that the raw data was processed in a way that makes it comparable to other experiments or that the underlying raw data was of sufficiently high quality.
You are also going to need high quality metadata to derive any meaning from the data matrix. What were the biological conditions and sources from which the samples were derived? What genes do the probes on the particular array used correspond to? (Note that 9890_at is "probeset id", a unique identifier of a molecular probe of a particular sequence design which then needs to be mapped to a gene, different probes for the same gene won't give exactly the same response.)
The public microrarray databases therefore provide a lot of additional information in addition to a processed data matrix. In addition to GEO that has already been mentioned I would recommend ArrayExpress which in my opinion has the better search interface.
The tool of choice to work with microarray data for many is the bioconductor suite of software for the statistical programming language R.
Bioconductor provides APIs to download raw data with accompanying metadata from both repositories, see the GEO bioc package  and ArrayExpress bioc package.
Both packages, in common with most bioconductor software come with excellent "vignettes" that introduce the software:
GEO bioc vignette and
Arrayexpress bioc vignette
Those vignettes should also give you examples of taking the raw data and deriving "Esets" (expression sets) from the raw data. At that point you can access the gene expression matrix in the bioconductor Eset object, and you have an object and APIs to interrogate the necessary metadata.
Note that there are different types of microarray. I would recommend starting with data from Affymetrix arrays as they have probably the most straightforward analysis APIs.


text:
Q: Spring Boot Actuator DataSourceHealthIndicator not working for auto-configured DataSource I'm using an auto-configured DataSource in Spring Boot 1.3.6 and I'm using Actuator's health endpoint.  However, the health endpoint does not include any database component in the output.
My application.properties is as follows:
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:local
spring.datasource.username=vagrant
spring.datasource.password=vagrant
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver

endpoints.enabled=false
endpoints.health.enabled=true

The output from the /health endpoint is:
{"status":"UP","diskSpace":{"status":"UP","total":499863515136,"free":121851781120,"threshold":10485760}}

I enabled trace logging and it looks like Spring Boot is autoconfiguring the health indicators before the datasource.  Here is an excerpt from the trace log (note the timestamps):
2016-07-22 10:07:20.976 TRACE 7628 --- [restartedMain] o.s.b.a.condition.OnClassCondition       : Condition OnClassCondition on org.springframework.boot.actuate.autoconfigure.HealthIndicatorAutoConfiguration$DataSourcesHealthIndicatorConfiguration matched due to @ConditionalOnClass classes found: org.springframework.jdbc.core.JdbcTemplate
2016-07-22 10:07:20.977 TRACE 7628 --- [restartedMain] .b.a.a.OnEnabledHealthIndicatorCondition : Condition OnEnabledHealthIndicatorCondition on org.springframework.boot.actuate.autoconfigure.HealthIndicatorAutoConfiguration$DataSourcesHealthIndicatorConfiguration matched due to All default health indicators are enabled by default
2016-07-22 10:07:23.304 TRACE 7628 --- [restartedMain] o.s.b.a.condition.OnClassCondition       : Condition OnClassCondition on org.springframework.boot.actuate.autoconfigure.HealthIndicatorAutoConfiguration$DataSourcesHealthIndicatorConfiguration matched due to @ConditionalOnClass classes found: org.springframework.jdbc.core.JdbcTemplate
2016-07-22 10:07:23.305 TRACE 7628 --- [restartedMain] o.s.b.a.condition.OnBeanCondition        : Condition OnBeanCondition on org.springframework.boot.actuate.autoconfigure.HealthIndicatorAutoConfiguration$DataSourcesHealthIndicatorConfiguration did not match due to @ConditionalOnBean (types: javax.sql.DataSource; SearchStrategy: all) found no beans

2016-07-22 10:07:23.577 TRACE 7628 --- [restartedMain] o.s.b.a.condition.OnBeanCondition        : Condition OnBeanCondition on org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration matched due to @ConditionalOnMissingBean (types: javax.sql.DataSource,javax.sql.XADataSource; SearchStrategy: all) found no beans
2016-07-22 10:07:23.578 DEBUG 7628 --- [restartedMain] a.ConfigurationClassBeanDefinitionReader : Registered bean definition for imported class 'org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration'
2016-07-22 10:07:23.578 DEBUG 7628 --- [restartedMain] a.ConfigurationClassBeanDefinitionReader : Registering bean definition for @Bean method org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration.dataSource()

Am I doing something wrong, or is this a bug in Spring Boot?  Is there a way to change the order so that the datasource is initialised first?

A: My problem was caused by running the app from Eclipse.  I also had a TestApplication class in src/test/java which had an exclusion for DataSourceAutoConfiguration.  I excluded the TestApplication class from the component scanning (via excludeFilter on @ComponentScan) and the health endpoint worked as expected (i.e. it included database information).


text:
Q: Continuous Markov Chain Let $\left(\xi_n\right)_{n\geqslant1}$ be a sequence of independent identically distributed random variables with distribution $\mathcal{N}(0,1)$. Let $X_0$ be a random variable in $\mathbb{R}$ with distribution $\mu$, independent from the sequence $\left(\xi_n\right)_{n\geqslant1}$. Let us define the sequence $\left(X_n\right)_{n\geqslant1}$ by $$X_n=\alpha X_{n-1}+\xi_n$$
where $\alpha\in(0,1)$.
Show that $\left(X_n\right)_{n\geqslant0}$ is a Markov chain and compute its transition kernel. Find $\sigma^2>0$ such that $\mathcal{N}\left(0,\sigma^2\right)$ is a stationnary distribution for this chain.
My work
I have computed $X_n=\alpha^nX_0+\sum_{j=1}^n \alpha^{n-j}\xi_j$, however when writing
$$\mathbb{P}\left(X_0\in C_0,\dots,X_n\in C_n\right)$$
for $C_0,\dots,C_n$ borel sets of $\mathbb{R}$, I do not know how to use independence to make it look like
$$\int_{\substack{x_0\in C_0\\\dots\\x_n\in C_n}}\mu(dx_0)P(x_0,dx_1)\dots P(x_{n-1},dx_n)$$

A: Observe that $X_0,X_1,..,X_{n-1}$ depend only on $\xi_1,\xi_2,...,\xi_{n-1}$.  Hence, $P(X_n\leq x|X_0,X_1,..,X_{n-1})=P(\xi_n\leq x-\alpha X_{n-1}|X_{n-1})$. By independence of $\xi_n$ and $X_{n-1}$ you can compute this as  $\Phi (x-\alpha X_{n-1})$.


text:
Q: How to input Date and Time info from a PHP form into a MySQL table in datetime format I am a bit of a greenback here and looking for some help with some help with a formatting issue that I am having with one of my websites.
I am trying to input Date and Time information inputted by a user into a MYSQL database in the datetime format. However when the user selects their date and time it will be done in the following format: 10:00 PM January 11, 2014
Currently I am trying to input information from a set of drop down menus that are populated from my database into that same MYSQL database;

        Time:

            <select name="hour">
                <?php query_hour() ?>
            </select>
          :
            <select name="minute">
                <?php query_minute() ?>
            </select>
            <select name="ampm">
                <?php query_ampm() ?>
            </select>

        Date:

            <select name="month">
                <?php query_month() ?>
            </select>
            <select name="day">
                <?php query_day() ?>
            </select>
        ,
            <select name="year">
                <?php query_year() ?>
            </select>

The PHP that I use to input this information into the database is:
// scrub inputs
$day = mysql_real_escape_string($_POST['day'], $conn);
$month = mysql_real_escape_string($_POST['month'], $conn);
$year = mysql_real_escape_string($_POST['year'], $conn);
$minute = mysql_real_escape_string($_POST['minute'], $conn);
$hour = mysql_real_escape_string($_POST['hour'], $conn);
$ampm = mysql_real_escape_string($_POST['ampm'], $conn);

// scrub date
$date = date('Y-m-d G:i:s',strtotime($year.' '.$month.' '.$day.' '.$hour.' '.$minute.' '.$ampm));

// prepare query
$sql = "INSERT INTO my_db.events (eventtime)
 VALUES
 ('$date')";

 // execute query
mysql_query($sql);
echo $sql;

When I submit the form it succeeds but submits generic time information instead of the user submitted information. Is there anyone that can provide a solution to this problem? I feel as though this is likely a duplicate question, but I have spent several hours perusing this forum as well as others with similar questions and have not found resolve.
Thanks in advance, you have all been a huge help so far and I appreciate the support!

A: Try with 'Y-m-d H:i:s' instead of G

*

*G is  24-hour format of an hour without leading zeros -->     0 through 23

*H is  24-hour format of an hour with leading zeros -->    00 through 23

For more info: PHP date manual
And to know more about php-mysql datetime: convert php date to mysql format

A: I solved my own issue, but figured I would post the result anyways in case anyone else is having a similar issue and needs some help.
The problem was with the way I was formatting the date when I was scrubbing it. It wasn't in the January 11, 2014 5:00 PM format.
It was:
$date = date('Y-m-d G:i:s',strtotime($year.' '.$month.' '.$day.' '.$hour.' '.$minute.' '.$ampm));

When it should have been:
$date = date('Y-m-d H:i:s',strtotime($month.' '.$day.','.$year.' '.$hour.':'.$minute.' '.$ampm));

Once I separated '.$day.' and '.$year.' with a comma and '.$hour.'and  '.$minute.'with a colon it started feeding the proper date.
Thanks for the help guys, it got me on the right track!


text:
Q: Why can pandas DataFrames change each other? I'm trying to keep of a copy of a pandas DataFrame, so that I can modify it while saving the original. But when I modify the copy, the original dataframe changes too. Ex:
df1=pd.DataFrame({'col1':['a','b','c','d'],'col2':[1,2,3,4]})
df1

    col1    col2
    a       1
    b       2
    c       3
    d       4

df2=df1
df2['col2']=df2['col2']+1
df1

    col1    col2
    a       2
    b       3
    c       4
    d       5

I set df2 equal to df1, then when I modified df2, df1 also changed. Why is this and is there any way to save a "backup" of a pandas DataFrame without it being modified?

A: You need to make a copy:
df2 = df1.copy()

df2['col2'] = df2['col2'] + 1
print(df1)

Output:
  col1  col2
0    a     1
1    b     2
2    c     3
3    d     4

You just create a second name for df1 with df2 = df1.

A: This is much deeper than dataframes: you are thinking about Python variables the wrong way. Python variables are pointers, not buckets. That is to say, when you write
>>> y = [1, 2, 3]

You are not putting [1, 2, 3] into a bucket called y; rather you are creating a pointer named y which points to [1, 2, 3].
When you then write
>>> x = y

you are not putting the contents of y into a bucket called x; you are creating a pointer named x which points to the same thing that y points to. Thus:
>>> x[1] = 100
>>> print(y)
[1, 100, 3]

because x and y point to the same object, modifying it via one pointer modifies it for the other pointer as well. If you'd like to point to a copy instead, you need to explicitly create a copy. With lists you can do it like this:
>>> y = [1, 2, 3]
>>> x = y[:]
>>> x[1] = 100
>>> print(y)
[1, 2, 3]

With DataFrames, you can create a copy with the copy() method:
>>> df2 = df1.copy()

A: When you set a data frame equal to another it keeps the same location for its data in the computer's memory. This means if you change one value in the new data frame it will change that value in the old one. To fix this you should make a copy of it instead of just making it equal to the original. Example : df2 = df1.copy()


text:
Q: Programmatically pass constant 'NOT LIKE' parameter Is it possible to pass parameter to the search method programmatically in Yii?
I have tables Team and Workers and I create add workers to the team functionality. I want to show CGridView searching which will show all workers except those assigned to the actually editing team. How to achieve it?

A: Usually the gridview is calling the search() method of your model, you could easily edit this method to add an optional parameter like:
public function  search($notLike = false){
    if($notLike) {
        //add the new sql condition not like
    }
}

A: Just use
$criteria->addSearchCondition($column, $keyword, $escape, 'AND', $like)

For example
$criteria->addSearchCondition('CustomerName', 'Jo', false, 'AND', 'NOT LIKE')
// Column 'CustomerName'
// Value to look for 'Jo'
// escape value? false
// append to query using 'AND'
// Compare using Not Like
//     This should generate: "... AND CustomerName LIKE 'Jo'"

Check out CDbCriteria->addSearchCondition()


text:
Q: Clearing form fields after invalidation JSF Ok i have the following problem: In my web app i have the CRUD all one page via dialogs controls of Primefaces. In the new dialog i have some validators. For example: when a user does not fill the necessary fields for form submission obviously the form doesn't submit. But when i close de New dialog and open it up again, the validation messages are still there! How can i get rid of this? I want a fresh new page (without accumulated validation errors) every time a dialogs open up! How that can be done?
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns:ui="http://java.sun.com/jsf/facelets"
            xmlns:h="http://java.sun.com/jsf/html"
            xmlns:f="http://java.sun.com/jsf/core"
            xmlns:p="http://primefaces.org/ui"
            template="./../../resources/templates/baseTemplate.xhtml">

<ui:define name="content">
    <f:view id="vRoot">
        <p:fieldset legend="Gerenciar público">
            <h:form id="frmPublicos">
                <!-- Exibição de mensagens gerais -->
                <p:growl id="gMessages" sticky="false" globalOnly="true" />

                <!-- Exibição da lista de públicos -->
                <p:dataTable id="dtPublicos"
                             value="#{publicoBean.lstDataTablePublico}"
                             paginator="true" rows="5"
                             rowsPerPageTemplate="5,10"
                             paginatorPosition="bottom"
                             paginatorTemplate="{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
                             var="atual">
                    <!-- Every time dialog opens validation messages should be cleaned -->
                    <f:facet name="header">
                        <p:commandButton id="cbViewNovo"
                                         value="Novo" type="button"
                                         styleClass="cbViewNovo"
                                         onclick="dlgNovo.show();"
                                         update=":dlgNovoPublico"
                                         process="@this">
                            <p:resetInput target=":dlgNovoPublico"/>
                        </p:commandButton>
                    </f:facet>
                    <!-- Colunas de edição e exclusão -->
                    <p:column>
                        <f:facet name="header">
                            <h:outputLabel value="Editar"/>
                        </f:facet>
                        <p:commandButton id="cbViewEditar"
                                         image="ui-icon-pencil"
                                         title="Editar"
                                         update=":frmEditar:pEditarPublico"
                                         oncomplete="dlgEditar.show();">
                            <f:setPropertyActionListener value="#{atual}" target="#{publicoBean.publicoSelecionado}" />
                        </p:commandButton>
                    </p:column>
                    <p:column>
                        <f:facet name="header">
                            <h:outputLabel value="Excluir"/>
                        </f:facet>
                        <p:commandButton id="cbViewExcluir" onclick="dlgExcluir.show();"
                                         icon="ui-icon-close" title="Excluir">
                            <f:setPropertyActionListener value="#{atual}" target="#{publicoBean.publicoSelecionado}" />
                        </p:commandButton>
                    </p:column>
                    <p:column>
                        <f:facet name="header">
                            Nome
                        </f:facet>
                        <h:outputLabel id="olViewNomePublico" value="#{atual.nmePublico}"/>
                    </p:column>
                    <p:column>
                        <f:facet name="header">
                            Tipo de público
                        </f:facet>
                        <h:outputLabel id="olViewTipoPublico" value="#{atual.tdTipoPublico}"/>
                    </p:column>
                </p:dataTable>
            </h:form>

            <!-- Caixa de diálogo de inclusão -->
            <p:dialog id="dlgNovoPublico"
                      widgetVar="dlgNovo"
                      modal="true"
                      header="Novo público"
                      resizable="false">
                <h:form id="frmNovo">
                    <p:panel id="pNovoPublico">
                        <p:messages id="mNovoMessages" redisplay="false" />
                        <p:panelGrid columns="2">
                            <p:outputLabel id="olNovoNomePublico" value="Nome:" for="itNovoNomePublico"/>
                            <p:inputText id="itNovoNomePublico" value="#{publicoBean.nome}" required="true"
                                         requiredMessage="Digite o nome do público."/>

                            <p:outputLabel id="olNovoTipoPublico" for="somNovoTipoPublico" value="Tipo de público:"/>
                            <p:selectOneMenu id="somNovoTipoPublico"
                                             value="#{publicoBean.tipoPublicoSelecionado}"
                                             effect="fade"
                                             converter="#{publicoBean.conversor}"
                                             required="true"
                                             requiredMessage="Selecione um tipo de público."
                                             >
                                <f:selectItem itemLabel="Selecione um item..." itemValue=""/>
                                <f:selectItems value="#{publicoBean.lstMenuTipoPublico}" var="atual" itemLabel="#{atual.label}" itemValue="#{atual}"></f:selectItems>
                            </p:selectOneMenu>
                            <p:commandButton value="Cancelar" immediate="true" onclick="dlgNovo.hide()"/>
                            <p:commandButton id="cbNovoSalvar" value="Salvar"
                                             actionListener="#{publicoBean.cadastrarPublico}"
                                             oncomplete="handleSalvo(xhr, status, args);"
                                             update=":frmPublicos:dtPublicos :frmNovo :frmPublicos:gMessages"
                                             ajax="true"/>
                        </p:panelGrid>
                    </p:panel>
                </h:form>
            </p:dialog>

            <!-- Caixa de diálogo de exclusão -->
            <p:confirmDialog id="dialogoExcluir" message="Deseja realmente excluir?"
                             header="Excluir público" severity="alert"
                             widgetVar="dlgExcluir">
                <h:form id="frmExcluir">
                    <p:commandButton id="cbExcluirCancelar" value="Cancelar" onclick="dlgExcluir.hide()" type="button" />
                    <p:commandButton id="cbExcluirContinuar" value="Continuar"
                                     update=":frmPublicos:dtPublicos :frmPublicos:gMessages"
                                     oncomplete="dlgExcluir.hide()"
                                     actionListener="#{publicoBean.excluirPublico}"/>
                </h:form>
            </p:confirmDialog>
            <!-- Caixa de diálogo de edição -->
            <p:dialog id="dialogoEditar" widgetVar="dlgEditar" header="Editar público"
                      resizable="false" modal="true">
                <h:form id="frmEditar">
                    <p:panel id="pEditarPublico">
                        <p:messages id="mEditarMessages" redisplay="false" />
                        <p:panelGrid columns="2">
                            <p:outputLabel id="olEditarNomePublico" value="Nome:" for="itEditarNomePublico"/>
                            <p:inputText id="itEditarNomePublico" value="#{publicoBean.publicoSelecionado.nmePublico}" required="true"
                                         requiredMessage="Digite o nome do público."/>

                            <p:outputLabel id="olEditarTipoPublico" for="somEditarTipoPublico" value="Tipo de público:"/>
                            <p:selectOneMenu id="somEditarTipoPublico"
                                             value="#{publicoBean.publicoSelecionado.tdTipoPublico}"
                                             effect="fade"
                                             converter="#{publicoBean.conversor}"
                                             required="true"
                                             requiredMessage="Selecione um tipo de público."
                                             >
                                <f:selectItem itemLabel="Selecione um item..." itemValue=""/>
                                <f:selectItems value="#{publicoBean.lstMenuTipoPublico}"
                                               var="atual"
                                               itemLabel="#{atual.label}"
                                               itemValue="#{atual}"></f:selectItems>
                            </p:selectOneMenu>
                            <p:commandButton value="Cancelar" immediate="true" onclick="dlgEditar.hide()"/>
                            <p:commandButton id="cbEditarSalvar" value="Salvar"
                                             actionListener="#{publicoBean.alterarPublico}"
                                             oncomplete="dlgEditar.hide();"
                                             update=":frmPublicos:dtPublicos :frmEditar :frmPublicos:gMessages"/>
                        </p:panelGrid>
                    </p:panel>
                </h:form>
            </p:dialog>
        </p:fieldset>
    </f:view>
    <!-- Javascript responsável por fechar a caixa de diálogo ao cadastrar-->
    <script type="text/javascript">
        function handleSalvo(xhr, status, args){
            if(args.salvo){
                dlgNovo.hide();
            }
        }
        function handleEditar(xhr, status, args){
            if(args.salvo){
                dlgEditar.hide();
            }
        }
    </script>
</ui:define>

A: Try p:resetInput. http://www.primefaces.org/showcase-labs/ui/resetInput.jsf

A: Try with pe:resetInput from Primefaces Extensions: http://fractalsoft.net/primeext-showcase-mojarra/sections/resetInput/formElements.jsf
<p:commandButton id="cbViewNovo"
                                         value="Novo" type="button"
                                         styleClass="cbViewNovo"
                                         onclick="dlgNovo.show();"
                                         update=":dlgNovoPublico"
                                         process="@this">
                            <pe:resetInput target=":dlgNovoPublico"/>
                        </p:commandButton>


text:
Q: Leaflet popup options with GeoJSON data In the following how would I customize the popup options?  I want to add in the option for the keepInView  to be true.
var myLayer = L.geoJson(polygon, {
  onEachFeature: yourOnEachFeatureFunction
}).addTo(map);

function yourOnEachFeatureFunction(feature, layer){
  if (feature.properties.name) {
      layer.bindPopup(feature.properties.name);
  }
}

A: Check out the Leaflet Documentation.
Here's the bit you want:
L.popup( <Popup options> options?, <ILayer> source? )

You can implement like this:
//set up a standalone popup (use a popup as a layer)
var popup = L.popup({keepInView:true})
     .setLatLng([51.5, -0.09])
     .setContent("I am a standalone popup.")
     .openOn(map);

Or in your example:
function yourOnEachFeatureFunction(feature, layer){ if (feature.properties.name) { layer.bindPopup(feature.properties.name,{keepInView:true}); } }

(This is passing in an object, which is composed of 'attribute:value' pairs.


text:
Q: Vim: How do I override a command with a new command that uses the old command? My Ruby folding expression is causing auto-completion (<C-n>/<C-p>) to slow down dramatically, which is a massive pain. When I switch to manual folding, auto-completion becomes instant.
To work around that I'd like the folding to be "on demand", i.e. it only calculates folds when i do zx or zX. The plan:

*

*Set Ruby code default folding method to manual

*When opening a Ruby file, locally map zx to switch folding method to expr and run zx, then switch folding method back to manual

*Repeat #2 for zX
The issue is, when I've overridden zx, how do I call the "old" zx?

Perfect answer by Kent, here's my final working solution (ftplugin/ruby.vim):
if &filetype == 'ruby'
    setlocal foldmethod=manual
    nn <buffer> <silent> zx :set foldmethod=expr<CR>:norm! zx<CR>:set foldmethod=manual<CR>
    nn <buffer> <silent> zX :set foldmethod=expr<CR>:norm! zX<CR>:set foldmethod=manual<CR>
end

A: Using the :noremap series of commands, rather than plain :map, you prevent any mappings from firing recursively. So you can safely call the "old" zx inside your mapping just by using zx directly. Example for your case:
nnoremap <buffer> <silent> zx :set foldmethod=expr<CR>zx:set foldmethod=manual<CR>

A: with :normal command, you can execute NORMAL mode command. And if you added a !, you will bypass mappings. For the example from yours,
:norm! zx

may help.


text:
Q: Splice not removing all matching elements in array I want to remove every 1 in an array. The final answer should be:
[4, 0, 5, 2, 6, 7, 3, 5, 11, 9, 9]

But I get:
[4, 0, 5, 2, 6, 1, 7, 3, 5, 11, 9, 9]

My code:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    let myNumber =[1,4,0,5,1,2,6,1,1,7,3,5,11,9,1,9];
    for(i=0;i<myNumber.length;i++){
        if(myNumber[i]===1){
        myNumber.splice(i,1);
        }
    }
    console.log(myNumber);

  </script>

</body>
</html>

Why doesn't this work, and how can I fix it?


text:
Q: click on mobile/tablet, hover on other devices (future-proofing) need an idea, I am stuck in quite the conundrum. I am building a responsive future proof webdesign.
On desktop and similar devices: I have a menu which on hover does a css animation to desplay a description of what hides behind the link and on click navigates to a new page.
On mobile devices: I wish to have a touch-event that triggers the hover (thus desplaying the description) and on touch number 2 it should then navigate to the new page.
the above is doable, but how to do it without checking user-agents, this is my situation. How does one go about future proofing the above.
Any great ideas are more then welcome. :)

A: Use Javascript to add a class on the touchstart/touchend events. Browsers won't issue these events:
Javascript:
document.querySelector("#myMenu").addEventListener("touchstart", function() {
    this.classList.add("mobileHovered ");
});
document.querySelector("#myMenu").addEventListener("touchend", function() {
    this.classList.remove("mobileHovered");
});

CSS:
#myMenu:hover,
#myMenu.mobileHovered {
    /* CSS styles */
}


text:
Q: Error in grouping variable trying to create a function to get frequency counts using dplyr in R I have a dataset which looks like this
df1 <- data.frame (
age = rep(c("40-44", "45-49", "50-54", "55-59", "60-64"),4),
dep = rep(c("Dep1", "Dep2", "Dep3", "Dep4", "Dep5"),4),
ethnic_1 = c(rep("M",4),rep("NM",7),rep("P", 3), rep("A", 6)),
ethnic_2 = c(rep("M",8),rep("NM",6),rep("P",2),rep("A", 4)),
gender = c(rep("M",10), rep("F",10))
)

What I want to do, is get a comparison of the two ethnicity classifications in these dataframes, by creating and running the following function
Comp_fun <- function(data, var1, ...) {

group_var <- quos(...)

var_quo <- enquo(var1)

df <- data %>%
 group_by(!!! group_var) %>%
 summarise (n = n()) %>%
 spread(key = !!! var_quo, value = count)

return(df)
}

eth_comp <- Comp_fun(df1, ethnic_1, ethnic_1, ethnic_2)

When I run this code, I get the following error message Error: Invalid column specification
What I want as output from this is a 4 x 4 table, showing the count of ethnic 1 along the horizontal, and the count of ethnic 2 along the vertical, and showing the numbers where they match, and where they don't.
I think I'm using the quo enquo incorrectly. Can anyone tell me where I'm going wrong?

A: There is no 'count' variable.  It should be 'n'.  Also, 'var_quo' is a quosure and not quosures.  So, it can be evaluated with !!
Comp_fun <- function(data, var1, ...) {

  group_var <- quos(...)

  var_quo <- enquo(var1)

  data %>%
    group_by(!!! group_var) %>%
    summarise (n = n()) %>%
    spread(key = !! var_quo, value = n)

}

eth_comp <- Comp_fun(df1, ethnic_1, ethnic_1, ethnic_2)
eth_comp
# A tibble: 4 x 5
#  ethnic_2     A     M    NM     P
#  <fct>    <int> <int> <int> <int>
#1 A            4    NA    NA    NA
#2 M           NA     4     4    NA
#3 NM          NA    NA     3     3
#4 P            2    NA    NA    NA


text:
Q: Retrofit request throwing UnknownHostException behind VPN So I'm having an issue that looks that it came straight out from the Twilight Zone.
Problem
I have to hit a REST API endpoint from a backend, the thing is that in order to hit that endpoint I need to go through a VPN. Otherwise the host is not reachable. On desktop everything works fine, I open Postman, hit the GET endpoint and get the response. However when I try to hit the same endpoint through my Android device Retrofit throws an UnknownHostException.
Context
The endpoint url is something like https://api.something.something.net/. I'm using dependency injection with Dagger, so I've a NetworkModule that looks like:
...
NetworkModule("https://api.something.something.net/")
...
@Module
class NetworkModule(
    private val baseHost: String
) {
...
    @Provides
    @Named("authInterceptor")
    fun providesAuthInterceptor(
        @Named("authToken") authToken: String
    ): Interceptor {
        return Interceptor { chain ->
            var request = chain.request()

            request = request.newBuilder()
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer $authToken")
                .build()
            val response = chain.proceed(request)
        }
    }
...
    @Provides
    @Singleton
    fun provideOkHttpClient(
        curlInterceptor: CurlInterceptor,
        @Named("authInterceptor") authInterceptor: Interceptor
    ): OkHttpClient {
        val builder = OkHttpClient.Builder()
        builder.addInterceptor(authInterceptor)
        builder.addInterceptor(curlInterceptor)
        return builder.build()
    }
...
    @Provides
    @Singleton
    fun provideRetrofit(okHttpClient: OkHttpClient, gson: Gson): Retrofit {
        return Retrofit.Builder()
                .baseUrl(baseHost)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(okHttpClient)
                .build()
    }
}

Then I've a bunch of Repositories which are the ones doing the request through Retrofit:
class MyApiRepositoryImpl(
    val myRetrofitApi: MyRetrofitApi,
    val uiScheduler: Scheduler,
    val backgroundScheduler: Scheduler
) : MyApiRepository {

    override fun getSomethingFromTheApi(): Observable<DataResource<List<ApiSomethingResponse>>> {
        return myRetrofitApi.getResponseFromEndpoint()
            .map {
                if (it.isSuccessful) {
                    DataResource(it.body()?.list!!, ResourceType.NETWORK_SUCCESS)
                } else {
                    throw RuntimeException("Network request failed code ${it.code()}")
                }
            }
            .subscribeOn(backgroundScheduler)
            .observeOn(uiScheduler)
            .toObservable()
    }
}

And this is the Retrofit's API interface:
interface MyRetrofitApi {

    @GET("/v1/something/")
    fun getResponseFromEndpoint(): Single<Response<ApiSomethingResponse>>
}

So, when I call this Repository method from my Interactor/UseCases it jumps straight through the onError and shows the UnknownHostException.
What I tried so far

*

*I switched Retrofit by Volley and later by Ion, just to be sure that wasn't something related to the rest client. I got the same exception in all cases:

java.net.UnknownHostException: Unable to resolve host "api.something.something.net": No address associated with hostname
com.android.volley.NoConnectionError: java.net.UnknownHostException: Unable to resolve host "api.something.something.net": No address associated with hostname
I tried every configuration possible with Retrofit and the OkHttpClient:

*

*On OkHttpClient I tried setting the followSslRedirects to true and false. followRedirects to true and false. Set hostnameVerifier to allow any hostname to pass through. Set a SSLSocketFactory to allow any unsigned certificates to pass through.

*On my Manifest I set my android:networkSecurityConfig to:
https://github.com/commonsguy/cwac-netsecurity/issues/5

*

*I tested the App on my Android Device (Android Nougat), on Emulators with Nougat, Marshmellow and Oreo, and a Genymotion emulator with Nougat.

*I tried hitting a random public endpoint (https://jsonplaceholder.typicode.com/todos/1) and It worked perfectly. So this isn't an issue with the internet connection.

*I've these three permissions set on my Manifest:
android.permission.INTERNET
android.permission.ACCESS_NETWORK_STATE
android.permission.ACCESS_WIFI_STATE

It's super weird because I've an Interceptor set to convert all the requests into cURL requests, I copied and pasted the same request that is failing into Postman and works perfectly.

*

*On my laptop I'm using Cisco AnyConnect, on my Android device I'm using the Cisco AnyConnect App and AFAIK on the emulators and Genymotion it should use the same network than the hosting machine.

There's a couple of websites that are only visible through the VPN and I can see them on the devices and on the emulators. But the endpoint URL is still unreachable from the App.
Couple of weird things
Yes, this gets weirder. If I hit the endpoint through the Chrome browser in my device or in the emulator I got redirected into a login page, that's because I'm not sending the authorization token. Now If I check the network responses through chrome://inspect I can get the IP of the host. Now if I change the base url of the NetworkModule by the IP and I add this line to the authorization Interceptor:
@Provides
@Named("authInterceptor")
fun providesAuthInterceptor(
    @Named("authToken") authToken: String
): Interceptor {
    return Interceptor { chain ->
        var request = chain.request()

        request = request.newBuilder()
            .addHeader("Content-Type", "application/json")
            .addHeader("Authorization", "Bearer $authToken")
            .build()
        val response = chain.proceed(request)
        response.newBuilder().code(HttpURLConnection.HTTP_SEE_OTHER).build() // <--- This one
    }
}

Then I start getting:
11-13 13:56:01.084 4867-4867/com.something.myapp D/GetSomethingUseCase: javax.net.ssl.SSLPeerUnverifiedException: Hostname <BASE IP> not verified:
        certificate: sha256/someShaString
        DN: CN=something.server.net,OU=Title,O=Company Something\, LLC,L=Some City,ST=SomeState,C=SomeCountryCode
        subjectAltNames: [someServer1.com, someServer2.com, someServer3.com, someServer4.com, andSoOn.com]

I'm not sure if this is unrelated or if it's actually one step forward to fix it.
Any tip or advice is appreciated.
Thanks,

A: A coworker found the issue. Basically the VPN is blocking any App except com.android.chrome.
https://www.cisco.com/c/en/us/td/docs/security/vpn_client/anyconnect/anyconnect40/administration/guide/Cisco_AnyConnect_Mobile_Administrator_Guide_4-0/mobile-anyconnect-mobile-devices.html#task_F445916BDC9649D49A98F98224D2EA7D

A: I think this issue may be related to ssl certificate validity. for dealing with that issue you should to set setSSLSocketFactory in HttpClient.
  private SSLConnectionSocketFactory getSSLSocketFactory() {
  KeyStore trustStore;
  try {
    trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null, null);
    TrustStrategy trustStrategy = new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] chain, String authType)
    throws CertificateException {
            return true;
        }

    };

    SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
    sslContextBuilder.loadTrustMaterial(trustStore, trustStrategy);
    sslContextBuilder.useTLS();
    SSLContext sslContext = sslContextBuilder.build();
    SSLConnectionSocketFactory sslSocketFactory = new
    SSLConnectionSocketFactory(sslContext);
    return sslSocketFactory;
       } catch (GeneralSecurityException | IOException e) {
    System.err.println("SSL Error : " + e.getMessage());
      }
   return null;
  }

 HttpClientBuilder.create().setSSLSocketFactory(getSSLSocketFactory())
 .build();


text:
Q: Gulp rev-del not removing files do I understand this wrong or is something not right here?
I have this piece of code
gulp.task("minifyScripts", function () {
  return gulp.src("assets/scripts/*.js")
    .pipe(uglify())
    .pipe(rev())
    .pipe(gulp.dest('assets/scripts/min'))
    .pipe(rev.manifest())
    .pipe(revDel())
    .pipe(gulp.dest('assets/scripts'))
    .pipe(livereload())
    .pipe(browserSync.stream());
});

My understanding was that this should remove old .js file when one with new hash is created, but its not...
Do you have any idea? Thanks so much!

A: You need to specify either dest in the options, or base in the manifest options—unless you're writing everything to the root directory.
Try:
pipe(revDel({dest: "assets/scripts/min"})

A: Seems that rev-del has a number of users, including myself, who are unable to get the plug-in to delete the old static files after gulp-rev hashes them.
Switching over to gulp-rev-delete-original simply worked OOB.
In the OP's use case, the updated solution would be:
const revDel = require("gulp-rev-delete-original")

gulp.task("minifyScripts", function () {
  return gulp.src("assets/scripts/*.js")
    .pipe(uglify())
    .pipe(rev())
    .pipe(revDel()) // call just after rev()
    .pipe(gulp.dest('assets/scripts/min'))
    .pipe(rev.manifest())
    //.pipe(revDel()) ==> move to just after rev()
    .pipe(gulp.dest('assets/scripts'))
    .pipe(livereload())
    .pipe(browserSync.stream());
});