text:
Q: TypeError: Cannot read property 'byteLength' of undefined - AWS S3 Upload I'm working on an aws s3 photo upload from a react client and I'm experiencing the following error:
TypeError: Cannot read property 'byteLength' of undefined
I'm assuming there's a flaw in the upload object, but I believe there might be something wrong with the s3/cognito configuration because I receive the same error when I invoked s3.listObjects. I'm following these docs - https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-photo-album-full.html
Any thoughts?
uploadPhoto() {
        const files = document.getElementById("photoUpload").files;
        if (!files.length) {
          return alert("Please choose a file to upload first.");
        }
        const file = files[0];
        const fileName = file.name;
        const albumPhotosKey = encodeURIComponent('screenshots') + "/";

        const photoKey = albumPhotosKey + fileName;

        // Use S3 ManagedUpload class as it supports multipart uploads

        const upload = new AWS.S3.ManagedUpload({
            params: {
              Bucket: <Bucket Name>,
              Key: fileName,
              Body: file
            }
          });

        const promise = upload.promise();

        promise.then(
          function(data) {
            alert("Successfully uploaded photo.");
            console.log('UPLOAD: ', data)
          },
          function(err) {
              console.log('ERROR: ', err)
            // return alert("There was an error uploading your photo: ", err.message);
          }
        );
      }

A: I got this error in a React Native app. I was able to fix it by turning off my Dev Tools network inspector.

A: I've run the example as described in the docs and it works, so can't reproduce your err. Here's a couple of things to check:

*

*Try passing your accesskey and secret into your config object (although I don't recommend this for security reasons, it might indicate where the issue is):

AWSService.config.update({
    region: region,
    accessKeyId: accessKeyId,
    secretKey: secretAccessKey,
    credentials: new AWSService.CognitoIdentityCredentials({
    IdentityPoolId: identityPoolId
    })
});

*

*Confirm your your Cognito Identity Pool ID has an IAM policy attached with the following:

    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:DeleteObject",
                "s3:GetObject",
                "s3:ListBucket",
                "s3:PutObject"
            ],
            "Resource": [
                "arn:aws:s3:::BUCKET_NAME",
                "arn:aws:s3:::BUCKET_NAME/*"
            ]
        }
    ]
}

A: Just in case! Check that your credentials are configured and passed right. And that you have the privileges for the resource in IAM.
I had the error above because i forget to pass the access credentials. It went away once i put them in.


text:
Q: bootstrap tooltip and angularJs I'm using the bootstrap-tooltip  and angularJs for display tooltip.
I am using the following code for display tooltip :

   <input valid-number ng-model="gotoPageInput" ng-class="{notValidPageNumber: gotoPageInput > totalPage || gotoPageInput<1}" ng-keyup="gotoPage($event,(gotoPageInput>=1 && gotoPageInput<=totalPage))" type="text" class="form-control goToPage " style="width: 70px">
   <button rel="tooltip" title="{{gotoPageInput}}" class="btn btn-default goToPage" ng-class="{disabled: gotoPageInput > totalPage || gotoPageInput<1}" ng-click="gotoPage($event,true)" type="button">go</button>

The first time it works properly Like the picture below :

See what happens when I change the value from 4 to 5 :

why ? Two tooltip Displays.Browser tooltip is correct but bootstrap tooltip is Wrong.

A: You can use angular-ui bootstrap's tooltip instead of using the jquery tootltip that twitter bootstrap is using.
See this plunker
HTML

Go

<input type="text" ng-model="text">

redpajama_set_name: RedPajamaStackExchange


text:
Q: Two MAMP/Wordpress sites, one with "missing MySQL" error I'm trying to do some major dev on a two sites I built a couple years ago. They're both just plain old Wordpress installs with some customized themes. I pulled them both down off production today in an attempt to get them running locally to do this dev. First one goes fine. Second one keeps throwing the

Your PHP installation appears to be missing the MySQL extension which
  is required by WordPress.

error. They're both running on the same MAMP install on my system, just different directories. So I'm pretty confused as to why there's a difference. Typical "check phpinfo" on server responses to this issue don't really help as they're on the same server and have the same settings. Nothing SEEMS out of place within wp-config or phpMyAdmin. Feeling lost... plz help.

A: Welp, I'm dumb. My MAMP was defaulting to php 7. Turned it back to 5.6 and now I'm in business.


text:
Q: Differentiating between running and being sourced in a bash shell script? Either what I'm asking here is extremely unorthodox/unconventional/risky, or my Google-fu skills just aren't up to snuff...
In a bash shell script, is there any easy of way of telling if it is getting sourced by another shell script, or is it being run by itself? In other words, is it possible to differentiate between the following two behaviors?
# from another shell script
source myScript.sh

# from command prompt, or another shell script
./myScript.sh

What I'm thinking of doing is to create an utilities-like shell script containing bash functions that can be made available when sourced. When this script is being run by itself though, I'll like it to perform certain operations, based on the defined functions too. Is there some kind of an environment variable that this shell script can pick up on, e.g.
some_function() {
    # ...
}
if [ -z "$IS_SOURCED" ]; then
    some_function;
fi

Preferably, I'm looking for a solution that doesn't require the caller script to set any flag variables.
edit: I know the difference between sourcing and and running the script, what I'm trying to find out here if it's possible to tell the difference in the script that is being used (in both ways).

A: Combining @DarkHeart's answer with the environment variable BASH_SOURCE seems to do the trick:
$ head example*.sh
==> example2.sh <==
#!/bin/bash
. ./example.sh

==> example.sh <==
#!/bin/bash
if [ "$(basename $0)" = "$(basename $BASH_SOURCE)" ]; then
    echo "running directly"
else
    echo "sourced from $0"
fi
$ ./example2.sh
sourced from ./example2.sh
$ ./example.sh
running directly

edit Seems to be a simpler solution still if I were to just count the number of elements in BASH_SOURCE's array:
if [ ${#BASH_SOURCE[@]} -eq 1 ]; then echo "running directly"; else echo "sourced from $0"; fi

A: I just created the same kind of library script that works alot like BusyBox. In it, I use the following function to test if it is being sourced...
function isSourced () {
  [[ "${FUNCNAME[1]}" == "source" ]]  && return 0
  return 1
}

The Bash-maintained FUNCNAME array is essentially a function call stack. $FUNCNAME (or ${FUNCNAME[0]}) is the name of the currently executing function. ${FUNCNAME[1]} is the name of the function that called it, and so on.
The topmost item is a special value for the script itself. It will contain...

*

*the word "source" if the script is being sourced

*the word "main" if the script is being executed AND the test is being done from within a function

*""(null) if the script is being executed AND the test is being done outside of any function, that is... at the level of the script itself.

The function above actually only works when called at the script level (which is all I needed). It would fail if called from inside another function because the array item number would be wrong. To make it work anywhere requires finding the top of the stack and testing that value, which is more complicated.
If you need that, you can get the array item number of the "top of the stack" with...
  local _top_of_stack=$(( ${#FUNCNAME[@]} - 1 ))

${#FUNCNAME[@]} is the number of items in the array. As a zero-based array, we subtract 1 to get the last item#.
These three functions are used together to produce a function stack trace similar to Python's and they may give you a better idea how all this works...
function inspFnStack () {
  local T+="  "
  local _at=
  local _text="\n"
  local _top=$(inspFnStackTop)
  local _fn=${FUNCNAME[1]}; [[ $_fn =~ source|main ]]  || _fn+="()"
  local i=_top; ((--i))
  #
  _text+="$i item function call stack for $_fn ...\n"
  _text+="| L   BASH_SOURCE{BASH_LINENO called from}.FUNCNAME  \n"
  _text+="| ---------------------------------------------------\n"
  while (( $i > 0 ))
  do
    _text+="| $i ${T}$(inspFnStackItem $i)\n"
    T+="  "
    ((--i))
  done
  #
  printf "$_text\n"
  #
  return 0
}

function inspFnStackItem ()  {
  local _i=$1
  local _fn=${FUNCNAME[$_i]}; [[ $_fn =~ source|main ]]  || _fn+="()"
  local _at="${BASH_LINENO[$_i-1]}"; [[ $_at == 1 ]]  && _at="trap"
  local _item="${BASH_SOURCE[$_i]}{${_at}}.$_fn"
  #
  printf "%s" "$_item"
  return 0
}

function inspFnStackTop () {
  # top stack item is 1 less than length of FUNCNAME array stack
  printf "%d\n" $(( ${#FUNCNAME[@]} - 1 ))
  #
  return 0
}

Note that FUNCNAME, BASH_SOURCE and BASH_LINENO are 3 arrays maintained by bash as if they were one three-dimensional array.

A: Yes - the $0 variable gives the name of the script as it was run:
$ cat example.sh
#!/bin/bash
script_name=$( basename ${0#-} ) #- needed if sourced no path
this_script=$( basename ${BASH_SOURCE} )
if [[ ${script_name} = ${this_script} ]] ; then
    echo "running me directly"
else
    echo "sourced from ${script_name}"
fi

$ cat example2.sh
#!/bin/bash
. ./example.sh

Which runs like:
$ ./example.sh
running me directly
$ ./example2.sh
example.sh sourced from example2.sh

That doesn't cater for being source from an interactive shell, but you get this idea (I hope).
Updated to include BASH_SOURCE - thanks h.j.k

A: One way which also works when sourcing from an interactive shell:
if [ $BASH_LINENO -ne 0 ]; then
    some_function;
fi

The BASH_LINENO variable is also an array with all the lines the calling function was executed at. It will be zero if you call the script directly, or an integer corresponding to a  line number.
The BASH_* variable docs

A: Just want to add that counting the array appears to be unreliable and one should probably not assume source was used since using a dot (.) is very common as well (and predates the source keyword).
For example, for a sourced.sh script containing only echo $0:

$ . sourced.sh
bash
$ source sourced.sh
bash
$ chmod +x sourced.sh
$ ./sourced.sh
./sourced.sh
$ cat ./sourced.sh
echo $0

The comparison solutions suggested work better.


text:
Q: ActionScript - Contact Form Not Working I'm trying to debug a contact form that was built in Flash, but I'm not sure how I can go about debugging this. From the ActionScript, I can tell that it's supposed to POST the results to /assets/files/functions.php. The problem is that when I fill out the fields and click onto 'Send' (which is supposed to trigger this), nothing happens and I can't tell if it's a PHP issue or a flash issue.
Is there any ideas as to how to debug this?
The website can be found here and the form can be seen by clicking onto 'Connect' and then click onto 'Send Inquiry'.
The code may be seen below:
lvOut = new LoadVars();               //create lv object
lvIn = new LoadVars();                //create lv object
lvIn.onLoad = function (success) {
if(success){
    gotoAndPlay("success");
}else{
    gotoAndPlay("failure");
}
}

function submit() {
if ( (inputName.text != "") && (inputAddress.text != "") && (inputCity.text != "") && (inputState.text != "")
      && (inputCountry.text != "") && (inputTelephone.text != "") && (inputEmail.text != "") ) {
        lvOut.input_name = inputName.text;
        lvOut.input_address = inputAddress.text;
        lvOut.input_city = inputCity.text;
        lvOut.input_state = inputState.text;
        lvOut.input_zip = inputZip.text;
        lvOut.input_country = inputCountry.text;
        lvOut.input_telephone = inputTelephone.text;
        lvOut.input_email = inputEmail.text;
        lvOut.input_bedrooms = inputBedrooms.text;
        lvOut.input_realtor = inputRealtor.text;
        lvOut.input_comments = inputComments.text;

        if (realtorYes) {
            lvOut.input_hasRealtor = "yes";
        } else if (realtorNo) {
            lvOut.input_hasRealtor = "no";
        } else {
            lvOut.input_hasRealtor = "no answer";
        }

        //send vars to functions page and load in result
        lvOut.sendAndLoad("assets/files/functions.php", lvIn, "POST");
}
}

btnSend.addEventListener("click", submit);

Please help me out as much as possible! :-)

A: You have a problem in your flash app: it sends nothing. I just entered webpage you said with Chrome and opened "Network" tab in "Developer's tools" menu. It captured 0 requests on "send" button click. I  don't know AS2 (saveAndLoad is AS2 method), so I can't say what is wrong, but  here
is a working example of POST request in AS3.

A: Try taking a different approach by using URLLoader class. I assume your functions.php file is somewhere online.
const SITE_DOMAIN:String = "PUT_YOUR_SITE_DOMAIN_HERE_UP_TO_ASSETS_FOLDER";
var loader = new URLLoader();
loader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
loader.addEventListener(Event.COMPLETE, loadCompleteHandler);

request = new URLRequest();
request.url = SITE_DOMAIN + "assets/files/functions.php";
request.method = URLRequestMethod.POST;
loader.load(request);

function loadCompleteHandler(event:Event):void
{
    // handle load complete
}

function securityErrorHandler(event:SecurityErrorEvent):void
{
    // handle security error
}

function ioErrorHandler(event:IOErrorEvent):void
{
    // handle io error
}

Hope this help.

A: You have an error in your PHP script : http://nordicacondos.com/assets/files/functions.php
Fix it, then try some trace in your AS code to see what is send to PHP.

*

*Check if your test on non empty values works by adding a trace inside (I think your problem is here because your swf sends nothing even if all fields are filled)

*Check the content of the lvOut object before send, in AS2 you can browse the content like this

for (var name in lvOut) {
  trace(name +'->' + lvOut[name]);
}

Add the full path to the PHP script so you can test from Flash IDE.

*

*Add a trace in the lvIn onLoad handler to check if its fired

You may also check on the PHP side by logging the raw request like this :
$handle = fopen('log.txt', 'ab+');
fwrite($handle, print_r($_REQUEST, true) );
fwrite($handle, PHP_EOL);
fclose($handle);

Make sure that you have write permissions on the functions.php directory.
Of course using AS3 would offer better control... :)


text:
Q: ckeditor disallow some tags I am using ckeditor and so far like it. Since I am loading it from the CDN I don't have immediate access to config.js.  I want to allow most of the html tags but want to block  tabs as my page formatting heavily depends on the div tags. However I am not able to block div tags from the CKEditor. I read the ckeditor documentation and followed CKEDITOR.replace and replaceall methods with textareas and the textareas classed as ckeditor. However my changes don't seem to take any effect.
I am loading the ckeditor.js from a CDN first.

Then I tried
var editor = CKEDITOR.replace( 'ckeditor', {
    allowedContent: 'a[!href]; ul; li{text-align}(someclass)'
} );

I placed the above function both in document.ready and also near the end of the body after the said textarea is loaded at different times, between script tags, to test.
Somehow my changes dont seem to have any effect. Does anyone have any suggestions or help? Obviously I am screwing it up somewhere. Any guidance on where to put the CKEDITOR.replace/replaceall calls? My textarea is classed as ckeditor.
Thanks a bunch

A:
My textarea is classed as ckeditor.

CKEditor automatically replaces all textarea of .ckeditor class in DOM. This is the first reason why your explicit CKEDITOR.replace call does nothing. Another reason is that such invocation expects id to be passed as a first argument.
If you want to leave it this way, move allowedContent definition to config.js so it's shared among instances and avoid CKEDITOR.replace. Otherwise, get rid of .ckeditor class from your element or disable/change config.replaceClass to make CKEDITOR.replace work as expected (id as a parameter).
P.S. Make sure you have the latest version of CKEditor.


text:
Q: Include html tag in jquery function I have this jQuery function:
$(function() {
  var str = $(location).attr('href');
  var myString = str.substr(str.indexOf("?id=")+4);
  $.getJSON(
    'http://sat3.altervista.org/index.php',
    { get_param: 'value' },
    function(data) {
      for (var i = 0; i < data.length; i++) {
        if (myString == (data[i]["Nr SAT"])) {
          $('body').append($('
').html(data[i]["Data"]));
          $('body').append($('
').html('Tipo Servizio: '+ data[i]["Tipo Servizio"]));
          $('body').append($('
').html('Stato: '+ data[i]["Stato"]));
          $('body').append($('
').html('Attributo: '+ data[i]["Attributo"]));
        }
      }
    }
  );
});

If after the control if (myString == (data[i]["Nr SAT"])) i would  write tag html like
, in which way i can include it in the function??

A: Try this:
$(function() {
  var str = $(location).attr('href');
  var myString = str.substr(str.indexOf("?id=")+4);
  $.getJSON(
    'http://sat3.altervista.org/index.php',
    { get_param: 'value' },
    function(data) {
      for (var i = 0; i < data.length; i++) {
        if (myString == (data[i]["Nr SAT"])) {
          $('body').append($('
').html(data[i]["Data"]+"
"));
          $('body').append($('
').html('Tipo Servizio: '+ data[i]["Tipo Servizio"]+"
"));
          $('body').append($('
').html('Stato: '+ data[i]["Stato"]+"
"));
          $('body').append($('
').html('Attributo: '+ data[i]["Attributo"]));
        }
      }
    }
  );
});


text:
Q: How to close this pure css popup with anywhere or outside click? Here is the HTML Code, check out this fiddle for full working code -
https://jsfiddle.net/fmqgeqby/
Get a Quote

REQUEST A PHONE CALL

×

Is there any possible solution for this to close popup, when user click outside of site?

A: Sorry the jsfiddle didn't work so I couldn't see it but can you change it to use bootstrap?  Bootstrap's modal works very well.
If not, you could mimic some of what they're doing with your own code.
https://www.w3schools.com/bootstrap/bootstrap_modal.asp

A: One way to go with is using html labels with hidden checkbox. You will need two labels to be able to toggle the checkbox - one outside of the popup and another inside. Not the cleanest solution, but works:
HTML:
Get a Quote
<input type="checkbox" id="toggle">

REQUEST A PHONE CALL

    ×

 Hello

CSS:
input[type=checkbox] {
  position: absolute;
  left: -999em;
}

input[type=checkbox]:checked ~ #popup1 {
  visibility: visible;
  opacity: 1;
}

#popup1 label {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 0;
}

Full example here


text:
Q: Accessing and viewing nested JSON (Tumblr API) using Sencha Touch 2 I am currently working on creating an image gallery using Sencha Touch 2 and Tumblr API to fetch the images from my Tumblr website. I am struggling a lot with accessing the JSON in the innermost nested folder -- that is what I need to display the URL of the image. I've looked at countless other tutorials and similar StackOverflow questions, but no solution so far has seemed to work. I was wondering if people can take a look at my code.
So the structure of the JSON file is this:
    {
    "meta": {
        "status": 200,
        "msg": "OK"
    },
   "response": {
        "blog": { ... },
        "posts": [
         {
             "blog_name": "derekg",
             "id": 7431599279,
             "post_url": "http:\/\/derekg.org\/post\/7431599279",
             "type": "photo",
             "date": "2011-07-09 22:09:47 GMT",
             "timestamp": 1310249387,
             "format": "html",
             "reblog_key": "749amggU",
             "tags": [],
             "note_count": 18,
             "caption": "
my arm is getting tired.<\/p>",
             "photos": [
             {
                   "caption": "",
                   "alt_sizes": [
                    {
                        "width": 1280,
                        "height": 722,
                        "url": "http:\/\/derekg.org\/photo\/1280\/7431599279\/1\/
                       tumblr_lo36wbWqqq1qanqww"
                    },
                    {
                       "width": 500,
                        "height": 282,
                       "url": "http:\/\/30.media.tumblr.com\/
                       tumblr_lo36wbWqqq1qanqwwo1_500.jpg"
                    },

So I am essentially trying to access response > posts > photos > alt_sizes > url . Yep, very nested. With what I'm been doing I've been able to get down to the alt_sizes nest, but I need to be able to reach down to just one level more to get the url so that I can put it in the tag  to display the images on the Sencha Touch 2 window...
I'm going to include the code for my Store, Model, and View.
Here is the Store (PhotoStore.js):
  Ext.define("tumblrPhotos.store.PhotoStore", {
extend: 'Ext.data.Store',
requires: [
        'Ext.data.proxy.JsonP',
        'tumblrPhotos.model.PostsModel',
    ],
config: {
    model: 'tumblrPhotos.model.PostsModel',
    autoLoad: true,
    proxy: {
        type: 'jsonp',
        url: 'http://api.tumblr.com/v2/blog/lisacanblog.tumblr.com/posts/photo?api_key=HssV7DgyS8RtT0uYE5qpSQJwSxs6nIWpx06mMt8kNprCGQqIo8&callback=Ext.util.JSONP.callback',
        reader: {
            callbackKey: 'callback',
            type: 'json',
            rootProperty: 'response.posts'
        }
    }
}
});

Here is the Model (PostsModel.js):
    Ext.define("tumblrPhotos.model.PostsModel", {
extend: 'Ext.data.Model',
config: {
    fields:[ //all the fields of posts BESIDES hasMany (photos)
        {name:'blog_name'},
        {name:'id'},
        {name:'post_url'},
        {name:'type'},
        {name:'date'},
        {name:'timestamp'},
        {name:'caption'}
    ],

    hasMany: {
        model: 'PhotoModel',
        name: 'photos',
        associationKey: 'photos'
    }

}
});

Ext.define("PhotoModel", {
extend: 'Ext.data.Model',
config: {

    fields:[ //all the fields of photos BESIDES hasMany(alt_sizes)
        {name:'caption'},
        {name:'alt_sizes'}
    ],

    hasMany: {
        model: 'AltSizesModel',
        name: 'alt_sizes',
        associationKey: 'alt_sizes'
    },

    belongsTo: [{
        model:'tumblrPhotos.model.PostsModel',
        name: 'photos'
    }]

}
});

Ext.define("AltSizesModel", {
extend: 'Ext.data.Model',
config: {
    fields:[
        {name:'width'},
        {name:'height'},
        {name:'url'}
    ],
    belongsTo: [{
        model: 'PhotoModel',
        name: 'alt_sizes'
    }]
}
});

And lastly, here is the View (GalleryView.js):
    Ext.define("tumblrPhotos.view.GalleryView", {
extend: 'Ext.dataview.DataView',
xtype:'galleryview',
requires: [
        'tumblrPhotos.store.PhotoStore',
    ],
config: {
    title: 'Gallery',
    id: 'gallerypanel',
    iconCls: 'star',
    iconMask: true,
    store: 'PhotoStore',
    styleHTMLContent: true,
    scrollable: 'vertical',
    itemTpl: new Ext.XTemplate (
        '
',
        '{blog_name}',
        '{photos}',
        '<tpl for="photos">',
        '{alt_sizes.url}',
        '
hi
',
        '</tpl>',
        '
',
        '
'
    )
}
});

In my View file, this doesn't work:
        '<tpl for="photos">',
          '{alt_sizes.url}',
          '
hi
',
        '</tpl>',

... But does does:
        '<tpl for="photos">',
          '{alt_sizes}',
          '
hi
',
        '</tpl>',

The latter option outputs [object OBJECT] for the alt_sizes, so I know it is passing through. Can somebody help me so that I can output the url under the alt_sizes nest? Thank you very much!

A: That's because alt_sizes is an array an not an object so you can't actually do
alt_sizes.url

but you should do
alt_sizes[0].url
or alt_sizes[1].url for another size.
Update
If you only need to get the URLs of the picture then you just need to do an Ext.data.JSONP.request :
I created an example here from your case
Hope this helped

A: This was also a proper way:
        '<tpl for="photos[0].alt_sizes[0]">',
            '',
        '</tpl>',


text:
Q: How to mark points by whether or not they are within a polygon I have the longitude and latitude of bird observations across New Zealand, stored in Count.df, under the variables count, longitude, and latitude. However some of these are appearing offshore/in the ocean (it's a Citizen Science data set).
I would like to subset these points based off whether they fall outside of the information given in maps::map("nz"), for two reasons:

*

*I would like to plot these offshore points on a map, perhaps using a different colour

*For further analysis I will probably remove them from the data set.

How can I create a new variable in Count.df based on whether they fall inside/outside of the groups (1:3) delineated by map("nz"), which is saved as "nzmap.dat"?
Thanks, and please try to keep the coding lingo simple.
Subset of Count.df, I have over 17000 observations, here are 10. Please note that the value of "count" is of no interest for this question.
df <- readr::read_table2(
  "count longitude latitude
3 174.7889 -41.24632
1 174.7764 -41.25923
4 176.8865 -39.67894
1 174.7656 -36.38182
2 175.5458 -37.13479
2 175.5458 -37.13479
1 176.8862 -39.67853
1 170.6101 -45.84626
5 174.9162 -41.25709
2 176.8506 -39.51831"
)

A: Unfortunately it's rather difficult to use maps data to spatially filter points, because the data is really for plotting and not so much for doing spatial operations with. Luckily, it's fairly easy to use the sf package to do this kind of spatial work.

*

*First I get a New Zealand boundary from the rnaturalearth package, which is a convenient source of country borders. I do a few transformations to keep only the largest three polygons in the shapefile, since otherwise we'd plot a lot of far flung islands that likely aren't relevant to this map.

*Then I generate some random points around New Zealand. You can see that the tibble is just a column of longitudes and a column of latitudes. We turn this into point geometries with st_as_sf and plot it, to show what it looks like.

*Last, we can use st_within to check for each point whether or not it is inside the nz boundary. st_within returns a list of indices of polygons that the point is within for each point, so we can use lengths to get the result we want. Here anything that is 0 is not within the boundary and anything that is 1 is within the boundary. Plotting with this new on_land attribute shows that offshore points are appropriately coloured.

library(tidyverse)
library(sf)
#> Linking to GEOS 3.6.1, GDAL 2.2.3, proj.4 4.9.3
library(rnaturalearth)

nz <- ne_countries(country = "New Zealand", returnclass = "sf", scale = "large") %>%
  st_cast("POLYGON") %>%
  mutate(area = st_area(geometry)) %>%
  top_n(3, area)
#> Warning in st_cast.sf(., "POLYGON"): repeating attributes for all sub-
#> geometries for which they may not be constant

points <- tibble(
  x = runif(1000, st_bbox(nz)[1], st_bbox(nz)[3]),
  y = runif(1000, st_bbox(nz)[2], st_bbox(nz)[4])
)
points
#> # A tibble: 1,000 x 2
#>        x     y
#>    <dbl> <dbl>
#>  1  167. -44.5
#>  2  175. -40.9
#>  3  177. -43.8
#>  4  167. -44.8
#>  5  173. -39.3
#>  6  173. -42.1
#>  7  176. -41.9
#>  8  171. -44.9
#>  9  173. -41.2
#> 10  174. -39.5
#> # ... with 990 more rows
points <- st_as_sf(points, coords = c("x", "y"), crs = 4326)
plot(nz$geometry, col = "red")
plot(points, pch = 19, cex = 1, add = TRUE)

points <- points %>% mutate(on_land = lengths(st_within(points, nz)))
#> although coordinates are longitude/latitude, st_within assumes that they are planar
plot(nz$geometry, col = "red")
plot(points, pch = 19, cex = 1, add = TRUE)

Created on 2018-05-02 by the reprex package (v0.2.0).

A: You can do this with maps::map.where and (if you want) a custom map containing only the 3 main islands:
nz3 = map("nz",c("North","South","Stewart"), fill=TRUE, plot=FALSE)
points$onland = is.na(map.where(nz3, points$x, points$y))
plot(points, col = ifelse(points$onland, 1, 2), pch=19)


text:
Q: IOS to PHP, How to store TimeStamp from IOS and store into MYSQL via PHP I have a table that needs to store the time stamp. The time stamp is created client side the sent to PHP script and i need to know how i store this time stamp into MYSQL table.
Also what data type do i need to set in MYSQL, the field data type that needs to store this time stamp?
IOS code:
CGRect screenRect = [[UIScreen mainScreen] bounds];
    UIActivityIndicatorView *activityIndicator;
    activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    activityIndicator.frame = CGRectMake(0.0, 0.0, screenRect.size.width, screenRect.size.height);
    activityIndicator.backgroundColor = [UIColor colorWithRed:0.0f/255 green:0.0f/255 blue:0.0f/255 alpha:0.9f];
    activityIndicator.center = self.view.center;
    [self.view addSubview: activityIndicator];

    [activityIndicator startAnimating];

    dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    // 3) Load picker in background
    dispatch_async(concurrentQueue, ^{

        NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];

        NSString *myRequestString = [NSString  stringWithFormat:@"ThreadName=%@&ThreadDesc=%@&CatId=%d&UID=%d&TimeStamp=%f", textFieldThreadName.text, textFieldThreadDesc.text, rowCategory, self.userID, timeStamp];
        NSString *response = [self setupPhpCall:myRequestString :@"insertThread.php"];

        dispatch_async(dispatch_get_main_queue(), ^{
        [self insertedThread:response];
        [activityIndicator stopAnimating];
        });

    });

PHP Code:
<?php

        include "connect.php";

        $threadName = $_POST["ThreadName"];
        $threadDesc = $_POST["ThreadDesc"];
        $catId = $_POST["CatId"];
        $uid = $_POST["UID"];
        $date = $_POST["TimeStamp"];

        $qry = "INSERT INTO Thread(T_U_ID,T_C_ID,T_Name,T_Description,T_Flagged,T_Rated) VALUES('$uid','$catId','$threadName','$threadDesc',$date,0,0)";
        $result = mysqli_query($conn, $qry);

        if($result){

            echo 'inserted';
            exit();
        }else{
            echo 'not inserted';
            exit();
        }

        mysqli_close($conn);

    ?>


text:
Q: Convert set to string and vice versa Set to string. Obvious:
>>> s = set([1,2,3])
>>> s
set([1, 2, 3])
>>> str(s)
'set([1, 2, 3])'

String to set? Maybe like this?
>>> set(map(int,str(s).split('set([')[-1].split('])')[0].split(',')))
set([1, 2, 3])

Extremely ugly. Is there better way to serialize/deserialize sets?

A: Try like this,
>>> s = set([1,2,3])
>>> s = list(s)
>>> s
[1, 2, 3]

>>> str = ', '.join(str(e) for e in s)
>>> str = 'set(%s)' % str
>>> str
'set(1, 2, 3)'

A: Use repr and eval:
>>> s = set([1,2,3])
>>> strs = repr(s)
>>> strs
'set([1, 2, 3])'
>>> eval(strs)
set([1, 2, 3])

Note that eval is not safe if the source of string is unknown, prefer ast.literal_eval for  safer conversion:
>>> from ast import literal_eval
>>> s = set([10, 20, 30])
>>> lis = str(list(s))
>>> set(literal_eval(lis))
set([10, 20, 30])

help on repr:
repr(object) -> string
Return the canonical string representation of the object.
For most object types, eval(repr(object)) == object.

A: 1) Set to String:
s = set({1,2,3,4}) # set with int values.
Convert each value of set as a string, and join them to return one string with , as a delimiter.
str_val = ', '.join(list(map(str, s)))
output of str_val: '1, 2, 3, 4'
2) String to Set:
Split the string with , as a delimiter. It creates a list. Then convert the list as a set.
s = set(str_val.split(","))
output of s: {' 2', ' 3', ' 4', '1'}

A: If you do not need the serialized text to be human readable, you can use pickle.
import pickle

s = set([1,2,3])

serialized_s = pickle.dumps(s)
print "serialized:"
print serialized_s

deserialized_s = pickle.loads(serialized_s)
print "deserialized:"
print deserialized_s

Result:
serialized:
c__builtin__
set
p0
((lp1
I1
aI2
aI3
atp2
Rp3
.
deserialized:
set([1, 2, 3])

A: The question is little unclear because the title of the question is asking about string and set conversion but then the question at the end asks how do I serialize ? !
let me refresh the concept of Serialization is the process of encoding an object, including the objects it refers to, as a stream of byte data.
If interested to serialize you can use:
json.dumps  -> serialize
json.loads  -> deserialize

If your question is more about how to convert set to string and string to set then use below code (it's tested in Python 3)
String to Set
set('abca')

Set to String
''.join(some_var_set)

example:
def test():
    some_var_set=set('abca')
    print("here is the set:",some_var_set,type(some_var_set))
    some_var_string=''.join(some_var_set)
    print("here is the string:",some_var_string,type(some_var_string))

test()

A: if the len of the set 1
>>> s
{'info@montenegroprospects.com'}
>>> list(s)[0]
'info@montenegroprospects.com'

if the set has more than one value
>>> def set2str(l, spe=' - '):
       s=''
       for i in l:
            s += f'{i}{spe}'
       return s[:len(s) - len(spe)]
>>> s.add('asfasf')
>>> set2str(s)
'asfasf - info@montenegroprospects.com'
>>> set2str(s,' ') # you can change the spe
'asfasf info@montenegroprospects.com'


text:
Q: Gulp watch task is not working when sass/js/html file is saved I am trying to reload the browser when scss, HTML and js file is changed but when I run the gulp watch command it's not reloading the browser or can't see any css/js/html changes.
var gulp = require('gulp');
// Requires the gulp-sass plugin
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();

gulp.task('sass', function() {
    return gulp.src('app/scss/**/*.scss') // Gets all files ending with .scss in app/scss
        .pipe(sass())
        .pipe(gulp.dest('app/css'))
        .pipe(browserSync.reload({
            stream: true
        }))
});

gulp.task('browserSync', function() {
    browserSync.init({
        server: {
            baseDir: 'app'
        },
    })
})

gulp.task('watch', gulp.series(['browserSync', 'sass']), function() {
    gulp.watch('app/scss/**/*.scss', gulp.series('sass'));
    gulp.watch('app/*.html', browserSync.reload);
    gulp.watch('app/js/**/*.js', browserSync.reload);
});

A: With respect to Mark's solution, just add .on('change', browserSync.relod) to the end of the desired watch if you want to see the live reload:
var gulp = require('gulp');
// Requires the gulp-sass plugin
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();

gulp.task('sass', function () {
  return gulp.src('app/scss/**/*.scss') // Gets all files ending with .scss in app/scss
    .pipe(sass())
    .pipe(gulp.dest('app/css'))
    .pipe(browserSync.reload({
      stream: true
    }))
});

gulp.task('browserSync', function (done) {
  browserSync.init({
    server: {
      baseDir: 'app'
    },
  });
  done();
})

gulp.task('watch', gulp.series('browserSync', 'sass', function () {
  gulp.watch('app/scss/**/*.scss', gulp.series('sass'));
  gulp.watch('app/*.html', browserSync.reload);
  gulp.watch('app/js/**/*.js', browserSync.reload);
  gulp.watch('app/scss/**/*.scss').on('change', browserSync.reload);
  gulp.watch('app/*.html').on('change', browserSync.reload);
  gulp.watch('app/js/**/*.js').on('change', browserSync.reload);
}));

A: You need to make a couple of changes shown here:
gulp.task('browserSync', function(done) {         // done added here
  browserSync.init({
    server: {
      baseDir: 'app'
    },
  });
  done();                                          // done() called here
})

// gulp.task('watch', gulp.series(['browserSync', 'sass']), function() {
gulp.task('watch', gulp.series('browserSync', 'sass', function () {       // see note below

    gulp.watch('app/scss/**/*.scss', gulp.series('sass'));

    // gulp.watch('app/*.html', browserSync.reload);

    gulp.watch("app/*.html", { events: 'all' }, function(cb) {
      browserSync.reload();
      cb();
    });

    gulp.watch('app/js/**/*.js', browserSync.reload);
}));                                                                       // added a )

gulp.watch() takes 2 arguments, not 3.  gulp.series() should include all the functions - including your anonymous function that contains the watch calls.  And lose the array brackets.


text:
Q: How could I get the mean and mode summary at the same time for a dataframe? I have a dataframe with 10 numeric columns and 3 character columns, as a sample I prepare this dataframe:
df <- data.frame(
  name = c("ANCON","ANCON","ANCON", "LUNA", "MAGOLLO", "MANCHAY", "MANCHAY","PATILLA","PATILLA"),
  destiny = c("sea","reuse","sea","sea", "reuse","sea","sea","sea","sea"),
  year = c("2022","2015","2022","2022", "2015","2016","2016","2018","2018"),
  QQ = c(10,11,3,4,13,11,12,23,7),
  Temp = c(14,16,16,15,16,20,19,14,18))

I need to group it by column "name", get the mean summary for columns "QQ" and "Temp", and the mode for columns "destiny" and "year". I could get the mean summary but I couldn´t include the mode
df_mean <- df %>%
  group_by(name) %>%
  summarise_all(mean, na.rm = TRUE)

  name    destiny  year    QQ  Temp
  <chr>     <dbl> <dbl> <dbl> <dbl>
1 ANCON        NA    NA   8    15.3
2 LUNA         NA    NA   4    15
3 MAGOLLO      NA    NA  13    16
4 MANCHAY      NA    NA  11.5  19.5
5 PATILLA      NA    NA  15    16

the desired output with the medians is something like this:
     name destiny year   QQ Temp
1   ANCON     sea 2022  8.0 15.3
2    LUNA     sea 2022  4.0 15.0
3 MAGOLLO   reuse 2015 13.0 16.0
4 MANCHAY     sea 2016 11.5 19.5
5 PATILLA     sea 2018 15.0 16.0

How could I do it? Please help

A: Use across and cur_column.  Median would only work with ordinal data, though, and for categorical data like the character columns you have, use mode:
mode <- function(x) {
   x_unique <- unique(x)
   x_unique[which.max(tabulate(match(x, x_unique)))]
}

Then
mode_columns <- c('destiny', 'year')
df %>%
    group_by(name) %>%
    summarise(
        across(
            everything(),
            ~ if (cur_column() %in% mode_columns) mode(.x) else mean(.x)
        )
    )

# A tibble: 5 × 5
  name    destiny year     QQ  Temp
  <chr>   <chr>   <chr> <dbl> <dbl>
1 ANCON   sea     2022    8    15.3
2 LUNA    sea     2022    4    15
3 MAGOLLO reuse   2015   13    16
4 MANCHAY sea     2016   11.5  19.5
5 PATILLA sea     2018   15    16

UPD: Or you could summarise a bit differently
     summarise(
        across({{mode_cols}}, mode),
        across(!{{mode_cols}}, mean)
    )


text:
Q: Cannot change ImageResolution after applying ImagePad I want to export high-resolution images of a plot I'm making.  The trouble is, the plot has a lot of extra white space around it which I get rid of via ImagePad (I could also use ImageCrop but I run into the same problem described here).
If I put in the following code,
tempimage = Plot[x^2, {x, -10, 10}];

Export["testexport100.png", tempimage, ImageResolution -> 100];
Export["testexport125.png", tempimage, ImageResolution -> 125];
Export["testexport150.png", tempimage, ImageResolution -> 150];

I get three files of different size and quality (10KB, 13KB, and 16KB).  But when I first adjust the margins of the image, I no longer have the ability to change the resulting image quality.  For example, if I do
tempimage2 = ImagePad[tempimage, {{0, -10}, {0, -10}}];

Export["testexport2_100.png", tempimage2, ImageResolution -> 100];
Export["testexport2_125.png", tempimage2, ImageResolution -> 125];
Export["testexport2_150.png", tempimage2, ImageResolution -> 150];

Then all three resulting files are identical and 7KB.

A: Answering your question in comments, there are ways to crop graphics directly, without converting it to raster. For example, using Inset here I cut off 10% of the ImageSize from the right and from the top keeping everything in vector form:
gr = Plot[x^2, {x, -10, 10}];
Graphics[Inset[gr, ImageScaled[{0, 0}], ImageScaled[{0, 0}],
  ImageScaled[10/9]], Options[gr, AspectRatio]]

And here I cut off 10 printer's points from the right and from the top:
gr = Plot[x^2, {x, -10, 10}, ImageSize -> {360, 234}];
gr2 = Graphics[
  Inset[gr, ImageScaled[{0, 0}], ImageScaled[{0, 0}], Automatic],
  ImageSize -> {{0, 360 - 10}, {0, 234 - 10}}, AspectRatio -> Full]

If you just need to display a part of the plot you could set explicit PlotRange to include only the part of the plot you wish to display (but it is not identical to vector cropping). If you need to remove white borders you could try Method -> {"ShrinkWrap" -> True}.

A: For whatever reason, the image that results from applying ImagePad or ImageCrop or ImageTrim cannot have its resolution changed.  Maybe it's already been rasterized?  But I'm able to work around this by rasterizing the image before applying ImagePad.  I use the following function to make sure that the amount trimmed off the side is the same that you would get by applying ImagePad to the original.
RasterPad[image_, resolution_, padding_] :=
  Module[{odims, ndims, nimage, npadding},
   odims = ImageDimensions[image];
   nimage = Rasterize[image, "Image", ImageResolution -> resolution];
   ndims = ImageDimensions[nimage];
   npadding = ndims/odims padding;
   ImagePad[nimage, npadding]];

So I can get the results desired above by
Export["testexport2_100.png",RasterPad[tempimage,100,{{0,-10},{0,-10}}]];
Export["testexport2_125.png",RasterPad[tempimage,125,{{0,-10},{0,-10}}]];
Export["testexport2_150.png",RasterPad[tempimage,150,{{0,-10},{0,-10}}]];


text:
Q: how to connect QActions to SLOTS using qt designer I have created a nice looking toolbar using qt Designer and populated it with some actions.
I tried to connect the actions to slots visually from qt designer by clicking edit> signals and slots. This DID NOT WORK because i could not find any QAction signals.
Question.
Is there a way to connect the QAction SIGNAL(triggered()) to my slots within QT designer?
Please help.
PS:
I am currently being forced to connect through code:
QObject::connect(myAction, SIGNAL(triggered()),this, SLOT(myActionWasTriggered()))

but ia am lazy and i wish to connect using qt designer.

A: There's "Signal/Slot Editor" docked panel (Toggled with View->Signal/Slot Editor).
You can connect your actions there.
You may also need to add your custom slots via the "Change signals/slots" form context menu.
To save yourself some work, use the auto-connection feature (see QMetaObject::connectSlotsByName). Basically, all slots named with a specific pattern of on_objectName_signalName will be auto-connected.

A: Look here in Docs Designer Connection Mode... How to autconnect in the designer

A: Use the "Action editor" panel. You can find it near "Signals & Slots editor".

A: If you have menu, Please name your actions object according to menus , Suppose you have:
File Edit View Tools Help

You have 5 menus bar,
So you'll have a set of action_x ,  x is a number.Please naming your x according to your menu.
more explaintion:
File = 1
Edit = 2
View = 3
Tools = 4
Help = 5

And suppose :
File---> Open ..Close
Edit---> find...replace
View---> ZoomIn ... ZoomOut
Tools--->calender... prefrences
help---> help... about

You have 5x2 = 10 , you have 10 action, please manage such as:
action_11 == File>Open
action_12 == File>close
action_21 == Edit>find
and so on..

Above type of managing make easy your coding .....


text:
Q: ignore_repeated_errors = on, still registering the same error to the log file This is an error logger:
function error_handler($errno, $errstr, $errfile, $errline){

    $DateFormat = "d-m-Y G:i:s";
    $time = date($DateFormat);

  switch ($errno) {

      case E_ERROR:
      case E_USER_ERROR:
      case E_RECOVERABLE_ERROR:
      error_log("$time: FATAL ERROR: $errstr in file $errfile on line: $errline \n", 1, ADMIN_EMAIL);
      error_log("$time: FATAL ERROR: $errstr in file $errfile on line: $errline \n", 3, LOG_FILE);
      break;

        case E_WARNING:
        case E_USER_WARNING:
        error_log("$time: WARNING: error $errstr in file $errfile on line:$errline \n", 3, LOG_FILE);
        break;

         case E_ERROR:
        case E_USER_ERROR:
        case E_RECOVERABLE_ERROR:
            error_log("$time: FATAL error $errstr at $errfile:$errline \n", 3, LOG_FILE);
            break;
    default:
      // Write the error to our log file
      error_log("$time Unknown error [#$errno]: $errstr in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
      break;
  }

  return TRUE;
}

and this code below to see how the above function work
set_error_handler("error_handler");
echo $hi;

The $hi is a variable left undefined intentionally to trigger an error. The function up top logs the error to the errors.log file somewhat like this
08-10-2017 12:51:27 Unknown error [#8]: Undefined variable: hi in C:\xampp\htdocs\abc\index.php on line 97

Well done.
Problem is I would like to log the error only once so that I do not have 100 or 1000 lines of same error repeating over and over again.
I thought I found solution and adding this
log_errors = On
ignore_repeated_errors = On
ignore_repeated_source = On

to php.ini file will stop the script from logging the same error from the same file over and over again.
But no it did not help. Can you point out?
P.S. I know there is a question PHP log will not ignore repeated errors with ignore_repeated_errors = On already on stackoverflow but this too does not help.


text:
Q: JavaScript: How to get value of sender input element from keyup event? I need to capture the keyup event to provide live validation when user is typing in an input (change event fires only when the input loses focus).
I am having trouble getting the edited value of the input that fired the evnt.
The code also runs on timer to prevent multiple calls when user is typing (fires only every 500 ms).
I have several inputs with class "priceinput" and attach to keyup event of each like the following:
<script language="javascript" type="text/javascript">
    var timer;
    $(document).ready(function()
    {
        $(".priceinput").each(function()
        {
            $(this).keyup(function(e)
            {
                clearTimeout(timer);
                timer = setTimeout(function()
                {
                //how to get the value of the input element that was changed?
                var value = ???;
                    $.getJSON('/Validator/IsValidInput', { input: value },
                    function(response)
                    {
                      //indicate if input is correct
                    });
                }, 500);
            });
        });
     });
</script>

To get the sender input value, I have tried $(this).val, this.val(), e.target.val() but none seem to work.
How do I get the value of the sender input?

A: The problem is that in your timeout function, you've lost the "this" reference to the input element. Try something like this:
$('.priceinput').keyup(function(e) {
  var $input = $(this);
  clearTimeout(timer);
  timer = setTimeout(function() {
    var value = $input.val();
    $.getJSON( ... );
  }, 500);
});

A: In Internet Explorer it should be event.srcElement, in Firefox event.target.
Or try event.toElement and event.relatedTarget.
(and of course combine them with .value or .val())


text:
Q: Call methods between repositories - Repository Pattern I'm using the Repository Pattern (like the examples in the https://dotnet.microsoft.com/apps/aspnet/mvc site) in a ASP.NET MVC application. I have two repositories, one called CategoryRepository an other called ProductRepository. I also use two services, the CategoryService and ProductService to validate and call the repositories methods. I need a list of categories in ProductService, a method that return one is already implemented in the CategoryRepository. My question is, which is the correct way to call the ListCategories method that exists in CategoryRepository from ProductService? I don't want to implement another ListCategories method in the ProductRepository (DRY philosophy). Thanks.

A: I would recommend rolling similar repositories into one service.  So if you're creating an e-Commerce application roll up ProductRepository, CategoryRepository etc into something like CatalogService and have it host all repositories that are related.

A: One option is to provide the ProductService class an instance of CategoryService.
public class ProductService {
    ICategoryService _categoryService = null;

    public ProductService(ICategoryService categoryService) {
        _categoryService = categoryService;
    }
}

You could then access the category listings from the ProductService without having to establish a direct coupling to any specific CategoryService implementation.


text:
Q: Java Mail Listening For Messages POP3 I am trying to listen for new messages using the POP3 protocol. I am aware that Pop3 doesn't allow new messages to appear in the Inbox while the folder is open. Below is the code that I have implemented:
import javax.mail.event.MessageCountAdapter;
import javax.mail.event.MessageCountEvent;

public class EmailListener extends MessageCountAdapter {

public EmailListener() {

}

public void messagesAdded(MessageCountEvent e) {
    System.out.println("I");
}

public void messagesRemoved(MessageCountEvent e) {
    System.out.println("J");
}
}

public class POPReceiver {

 public POPReceiver() {

 }

public void listen() throws Exception {
    Properties properties = new Properties();
    Session session = null;
    POP3Store pop3Store = null;
    String host = "NB-EX101.example.com";
    String user = "user2";
    properties.put(mail.pop3.host, host);
    session = Session.getDefaultInstance(properties);
    pop3Store = (POP3Store) session.getStore("pop3");
    pop3Store.connect(user, "password");
    Folder folder = pop3Store.getFolder("INBOX");
    folder.addMessageCountListener(new EmailListener());
    sendEmail();
}

public void sendEmail() {
    // not added code, but the email sends
}
}

public static void main(String[] args) throws Exception {
      POPReceiver i = new POPReceiver();
      i.listen();
 }

I am using Microsoft Exchange Server. Any ideas why it is not listening?
I have looked on http://www.coderanch.com/t/597347/java/java/Email-Listener but still does not listen.

A: From Javamail FAQ (http://www.oracle.com/technetwork/java/javamail/faq/index.html):

Q: I set up a MessageCountListener (as demonstrated in the monitor program) but I'm never notified of new mail in my POP3 INBOX.
A: The POP3 protocol does not allow the client to see new messages delivered to the INBOX while the INBOX is open. The application must close the INBOX and reopen it in order to see any new messages. You will never be notified of new mail using the MessageCountListener interface with POP3. See the com.sun.mail.pop3 package documentation for more information.

So, MessageCountListener will not work for POP3. You'll need to implement polling to get information about new messages for POP3.
However, you can try using IMAP instead.
But even in the case of IMAP you should be using this in another way. See idle() method in IMAPStore class (e.g. being called in a loop in a separate thread etc - see https://javamail.java.net/nonav/docs/api/com/sun/mail/imap/IMAPStore.html#idle() ).


text:
Q: Select id from one query and use it in another I have this code. In the first query I want it to select a pid. Then I want to somehow use the selected pid as WHERE in the second query. This do not work but I want it to work on this(the same) page. I have read about this on other forums but I still didn't fix it. Probably a small mistake somewhere.

<?php
ini_set('display_errors',1);
error_reporting(E_ALL);

if(mysqli_connect_errno())
{
  echo mysqli_connect_error();
}

$loggedInUserId = $_SESSION['user_id'];
$resu = mysql_query("SELECT pid FROM users WHERE id='$loggedInUserId';");
$ro = mysql_fetch_row($resu);

$sql= "SELECT pid, project_name, image, image_type FROM project WHERE pid ='". $row["pid"]. "';";

$result = $mysqli->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_array()) {

        //$type= "Content-type:".$row['image_type'];
    //header ($type);
    echo "<form action='respodents.php' method='post'><button name='submit' id='projectbutton'>

                "."
".$row['project_name']."
"."

            <input type='hidden' name='pid' value='".$row['pid']."'>
            <input type='hidden' name='project_name' value='".$row['project_name']."'>

       </button></form>";
    }}

mysqli_close($mysqli);

?>

A: With respect to the sql, perhaps this might work
SELECT `pid`, `project_name`, `image`, `image_type`
    FROM `project` WHERE `pid` = (
        SELECT `pid` FROM `users` WHERE `id`='$loggedInUserId'
    );

The original code had a mix of mysql and mysqli functions with a further mix of Object Orientated and Procedural method calls. Whilst this wouldn't cause an error necessarily it is bad practise to do so. Below is all in a procedural style - it's not tested but it incorporates the two queries into one which should work ( famous last words )
Sidenote: That said - with mysqli you can take advantage of prepared statements which help mitigate against the threat of sql injection - it's quite straightforward to lean and use - so rather than embedding a variable in the sql you would use a placeholder and then bind a variable to that.
<?php
    ini_set('display_errors',1);
    error_reporting(E_ALL);

    /* db connection? */

    if( mysqli_connect_errno() ) echo mysqli_connect_error();
    else {

        $loggedInUserId = $_SESSION['user_id'];

        $sql="select `pid`, `project_name`, `image`, `image_type`
            from `project`
            where `pid` = (
                select `pid` from `users` where `id`='$loggedinuserid'
            );";

        $resu=mysqli_query( $mysqli, $sql );
        if( $resu ){

            $ro = mysqli_fetch_row( $resu );

            while( $row=mysqli_fetch_object( $resu ) ){

                echo "<form action='respodents.php' method='post'>
                        <button name='submit' id='projectbutton'>

                                pid."' width='100px' height='100px'/>

".$row->project_name."

                                <input type='hidden' name='pid' value='".$row->pid."'/>
                                <input type='hidden' name='project_name' value='".$row->project_name."'/>

                        </button>
                   </form>";

            }
        }
        mysqli_close( $mysqli );
    }
?>

A: $ro = mysql_fetch_row($resu);

$sql= "SELECT pid, project_name, image, image_type FROM project WHERE pid ='".
$row["pid"]. "';";

$ro = mysql_fetch_row($resu); should be spelled $row not $ro. There's nothing in the variable you are calling in your SQL statement.
Also, your SQL Statement doesn't make much sense in terms of
$row["pid"],

you are accessing a numerical array with mysql_fetch_row(http://php.net/manual/en/function.mysql-fetch-row.php).
If anything, you want to do mysql_fetch_array or mysql_fetch_assoc, to fetch an associative array that you can access the "pid" data statement. The way you are doing it with fetch_row you want to access it numerical, i.e.,
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
$row = mysql_fetch_row($result);

echo $row[0]; // 42
echo $row[1]; // the email value

The above is copied directly from the php mysql_fetch_row docs.
Edit::
http://php.net/manual/en/mysqli-result.fetch-row.php
Mysqli Docs for fetch_row.

A: First of all, you should not be mixing mysql and mysqli. Let's use mysqli as mysql is deprecated.
I will assume that you don't need it to be in just one query since you never specified.
$result = mysqli_query("SELECT pid FROM users WHERE id='$loggedInUserId';");
while($row = mysqli_fetch_row($result))
{
    $pid = $row['pid'];
}

$sql= "SELECT pid, project_name, image, image_type FROM project WHERE pid ='". $pid. "';";

$result = $mysqli->query($sql);

Also, you really should learn to use prepared statements as they are a much safer.

A: I believe you have to change this code:
$resu = mysql_query("SELECT pid FROM users WHERE id='$loggedInUserId';");

to:
$resu = mysql_query("SELECT pid FROM users WHERE id='".$loggedInUserId."'");

And do not mix mysql and mysqli commands you can easly mess up you code that way.

A: This looks smelly
$ro = mysql_fetch_row($resu);

$sql= "SELECT pid, project_name, image, image_type FROM project WHERE pid ='". $row["pid"]. "';";

change $ro = mysql_fetch_row($resu); to $row = mysql_fetch_row($resu);


text:
Q: Python kivy asyncio Пишу клиент для сервера с помощью киви. При запуске выдает ошибку  AttributeError: 'MyApp' object has no attribute 'parent'. Скорее всего ошибка в последней части кода. Вот код
import asyncio
from asyncio import transports
from PySide2.QtWidgets import QMainWindow, QApplication
from asyncqt import QEventLoop
from interface import Ui_MainWindow

class ClientProtocol(asyncio.Protocol):
    transport: transports.Transport
    window: 'Chat'

    def __init__(self, chat):
        self.window = chat

    def data_received(self, data: bytes):
        print(data)
        decoded = data.decode()
        self.window.plainTextEdit.appendPlainText(decoded)

    def connection_made(self, transport: transports.Transport):
        self.window.plainTextEdit.appendPlainText("Успешно подключились, введите логин")
        self.transport = transport

    def connection_lost(self, exception):
        self.window.plainTextEdit.appendPlainText("Вы отключены от сервера")

class Chat(QMainWindow, Ui_MainWindow):
    protocol: ClientProtocol

    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.pushButton.clicked.connect(self.send_message)

    def send_message(self):
        message = self.lineEdit.text()
        self.lineEdit.clear()
        self.protocol.transport.write(message.encode())

    def create_protocol(self):
        self.protocol = ClientProtocol(self)
        return self.protocol

    async def start(self):
        self.show()

        loop = asyncio.get_running_loop()

        coroutine = loop.create_connection(
            self.create_protocol,
            "127.0.0.1",
            8888
        )

        await asyncio.wait_for(coroutine, 1000)

app = QApplication()
loop = QEventLoop(app)

asyncio.set_event_loop(loop)

window = Chat()

loop.create_task(window.start())
loop.run_forever()

A: Для стыковки PySide2 и asyncio я рекомендую asyncqt: pip3 install asyncqt
from asyncqt import QEventLoop, asyncSlot, asyncClose
import sys
import asyncio

from PySide2.QtWidgets import (
    QApplication, QWidget, QLabel, QLineEdit, QTextEdit, QPushButton,
    QVBoxLayout)

from PySide2.QtCore import Signal

class ClientProtocol(asyncio.Protocol):
    def __init__(self, chat):
        self.window = chat

    def data_received(self, data: bytes):
        decoded = data.decode()
        self.window.speak.emit(decoded)

    def connection_made(self, transport):
        self.transport = transport

    def connection_lost(self, exception):
        pass

class MainWindow(QWidget):

    speak = Signal(str)

    __transport = None
    __protocol = None

    def __init__(self):
        super().__init__()
        self.setLayout(QVBoxLayout())

        self.editResponse = QTextEdit('', self)
        self.layout().addWidget(self.editResponse)

        self.editSend = QLineEdit('', self)
        self.layout().addWidget(self.editSend)
        self.editSend.returnPressed.connect(self.on_editSend)

        self.speak.connect(self.editResponse.append)

    @asyncSlot()
    async def on_editSend(self):
        text = self.editSend.text()
        if self.__transport:
            self.__transport.write(text.encode())
            self.editSend.setText('')
            self.editResponse.append('>'+text)

    def set_transport(self, task):
        self.__transport, self.__protocol = task.result()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    mainWindow = MainWindow()

    coro = loop.create_connection(
               lambda : ClientProtocol(mainWindow),
               "127.0.0.1",
               8888
        )
    task = loop.create_task(coro)

    task.add_done_callback(mainWindow.set_transport)

    mainWindow.show()

    with loop:
        sys.exit(loop.run_forever())

Код работает - проверил на серевере netcat -l 8888
asyncSlot тут не сильно нужен, но пригодится как пример


text:
Q: Printing a panel in c# Im printing a panel which is basically a registration form, and contain 3 small panels, but it print only a blank page... i tried many times but got no solution.
PrintDialog myPrintDialog = new PrintDialog();
System.Drawing.Bitmap memoryImage = new System.Drawing.Bitmap(panel_stdadmcard.Width, panel_stdadmcard.Height);
panel_stdadmcard.DrawToBitmap(memoryImage, panel_stdadmcard.ClientRectangle);
PrintDocument printDocument1 = new PrintDocument();
if (myPrintDialog.ShowDialog() == DialogResult.OK)
{
    System.Drawing.Printing.PrinterSettings values;
    values = myPrintDialog.PrinterSettings;
    myPrintDialog.Document = printDocument1;
    printDocument1.PrintController = new StandardPrintController();
    printDocument1.Print();
}
printDocument1.Dispose();

A: You draw the panel to a bitmap, but you never use it, if this code is complete.
You should implement the PrintPage-Event of the printDocument.
And there you should use DrawImage to Draw the image.

A: Change panel_stdadmcard.ClientRectangle to new Rectangle(0, 0, panel_stdadmcard.Width, panel_stdadmcard.Height)


text:
Q: Proof that $\overline{B}_1(0)$ is not compact in $(C[0,1],||\cdot||_{\infty})$ I am asked to prove the following statement

The set $\overline{B}_1(0)$ is not compact in
  $(C[0,1],||\cdot||_{\infty})$ and $\overline{B}_1(0)=\{f\in
 C[0,1]:||f||_{\infty}\leq1\}$

My attempt was the following:
Find a function $h_k(f)$ where $f(x) = ?$ s.t.:
$$||h_k(f)-h_m(f)||_{\infty} = const.$$
I am trying to use the definition that a set is called compact if every sequence does have a convergent subsequence.

The idea behind the constant value came to me when solving the exact same question but for $(\mathbb{R},||\cdot||_{\infty})$, where I found the function
$$
    f_k(x)=
\begin{cases}
    1,& \text{if } x= \frac{1}{k}\\
    0,              & \text{otherwise}
\end{cases}
$$
when applying the cauchy-criteria one can define (for example) $\epsilon := \frac{1}{2}$ and see that $||f_k-f_m||_{\infty} = 1 > \epsilon \implies \overline{B}_1(0)$ not compact in $(\mathbb{R},||\cdot||_{\infty})$

Coming now back to my actual question: Could anyone give me a push in the right direction, what the best way would be to define my $h_k(f)$ or maybe tell me if I am on the complete wrong track with my idea?
It's been some weeks since we introduced the $C[0,1]$ but I am still struggling a bit to work with it thus having a hard time solving this particular excercise.
Thank you in advance :)
P.S.: Since I don't know if $C[0,1]$ is a general used definition: We defined $C[0,1]$ as the space of continuous functions

A: For each $n\in\mathbb{N}$, define a function $f_n\in C\bigl([0,1]\bigr)$ such that:

*

*$x\notin\left[\frac1{n+1},\frac1n\right]\implies f_n(x)=0$;

*$(\forall x\in[0,1]):-1\leqslant f_n(x)\leqslant 1$;

*$f_n(x_n)=1$ for some $x_n\in\left[\frac1{n+1},\frac1n\right]$.

It follows from this that $m\neq n\implies\|f_m-f_n\|_\infty=1$. Therefore, $(f_n)_{n\in\mathbb N}$ has no Cauchy subsequence, and therefore no convergent subsequence.


text:
Q: how to load the items in array at run time I have three tableView one containg cateogry one containg type and other product name i want that when user selct any category the type array should be loaded at run time getting the same type of the selected category
In my example if i select category Herbicide then it should insert the contents of the
typeHerbicides in arrayType but when i load table second it does not show any values
 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  return 1;
  }

// Customize the number of rows in the table view.
  - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

   if (tableView ==tblSimpleTable )

    return [categoryArray count];

   else if(tableView==tblSimpleTableType)

     return [typeArray count];

   else if(tableView==tblSimpleTableProduct)

    return [productArray count];

   else if(tableView==tblSimpleTableOneSection)

    return [categorySectionOneArray count];
   else if(tableView==tblSimpleTableTypeSection)

    return [typeArraySection count];
    else

    return  [productArraySection count];
     }

// Customize the appearance of table view cells.
   - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

     if (cell == nil) {
     cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
     }

    if (tableView ==tblSimpleTable ) {

cell.textLabel.font=[UIFont fontWithName:@"Arial" size:16];

cell.textLabel.text = [categoryArray objectAtIndex:indexPath.row];
    return cell;

   }

    else if (tableView==tblSimpleTableType){

    cell.textLabel.font=[UIFont fontWithName:@"Arial" size:16];

    cell.textLabel.text = [typeArray objectAtIndex:indexPath.row];
    return cell;

   }

   else if(tableView==tblSimpleTableProduct) {

    cell.textLabel.font=[UIFont fontWithName:@"Arial" size:16];

    cell.textLabel.text = [productArray objectAtIndex:indexPath.row];
    return cell;

   }

   else if(tableView==tblSimpleTableOneSection){

    cell.textLabel.font=[UIFont fontWithName:@"Arial" size:16];

    cell.textLabel.text = [categorySectionOneArray objectAtIndex:indexPath.row];
    return cell;

    }

    else if(tableView==tblSimpleTableTypeSection){
    cell.textLabel.font=[UIFont fontWithName:@"Arial" size:16];

    cell.textLabel.text = [typeArraySection objectAtIndex:indexPath.row];
    return cell;

   }

   else {

    cell.textLabel.font=[UIFont fontWithName:@"Arial" size:16];

    cell.textLabel.text = [productArraySection objectAtIndex:indexPath.row];
    return cell;

   }
   }

     - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

     if (tableView ==tblSimpleTable ) {

    titleCategory=[categoryArray objectAtIndex:indexPath.row];

    NSLog(@"This is titleCategory Selected %@",titleCategory);

    NSString*test=@"Herbicides";

    if([titleCategory isEqualToString:test]){

     typeHerbicides=[[NSArray alloc] initWithObjects:@"ACCLAIM EXTRA",@"ILLOXAN",@"REVOLVER",nil];

    typeArray=[[NSArray alloc] initWithArray:typeHerbicides copyItems:YES];
    }

    else {
        typeArray=[[NSArray alloc] initWithObjects:@"ILLOXAN",@"REVOLVER",nil];

        typeArray=[[NSArray alloc] initWithArray:typeHerbicides copyItems:YES];

    }

    }

    else if(tableView==tblSimpleTableType)

    titleType=[typeArray objectAtIndex:indexPath.row];

   else if(tableView==tblSimpleTableProduct)

    titleProduct=[productArray objectAtIndex:indexPath.row];

   else if(tableView==tblSimpleTableOneSection)

    titleSectionOneCategory=[categorySectionOneArray objectAtIndex:indexPath.row];

    else if(tableView==tblSimpleTableTypeSection)

    titleTypeSection=[typeArraySection objectAtIndex:indexPath.row];
    else

    titleProductSection=[productArraySection objectAtIndex:indexPath.row];
    }

A: When user selects any category then in didSelectRowAtIndexPath you can initialize your typeArray based on category selected:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView == tblSimpleTableType)
    {
       //initialize typeArray;

       //Once typeArray is initialized just reload the tableview as follows:
       [tblSimpleTableType reloadData];
    }
}

A: Just try by returning the cell at last of the function only and see.


text:
Q: Size of image not fitting into storyboard view for compact w regular h size class I've added a bunch of images to my program and have set them in the appropriate spots 1x, 2x etc. in the image assets file (and have also set them for their respective sizes) but when I try to drag the image directly from the media library onto my view (for the compact width and regular height size class - iPhone size in portrait), the image that is going in is the iPad's version and so it doesn't fit. I first added an image view to test this, and while this gets the image fitting the image view, it is still the same iPad version that is getting selected.
The media library just shows one image and then the number 6 beside it to show the different ones, but I can't seem to be able to select the specific image I want from here. Is there an easy way to resolve this?
It seems to be adding the iPad version into my iPhone compact w regular h view.
This is the set of images I have added:

A: You're thinking about this wrong. Distinguish resolution from size.

*

*Your job is to set the size of the image view that will hold this image.

*The runtime will automatically pick the version of the image that is correct for the current device's screen resolution.


text:
Q: Codeigniter using foreach in view I'm using Codeigniter on an Apache xampp set up and attempting to use foreach in a view for the first time and I just can't get it to work.
My Controller code:
class Test extends CI_Controller {

        public function index($page = 'testv')
    {
            if ( ! file_exists(APPPATH.'/views/'.$page.'.php'))
            {
                show_404();
            }
                $this->load->model('testm');
                $data['news'] = $this->testm->get_news();

                $this->load->view('headder');
                $this->load->view($page, $data);
                $this->load->view('footer');
    }
}

My Model:
class Testm extends CI_Model {

    public function __construct()
    {
        parent::__construct();
    }

    Public function get_news()
    {
        $query = $this->db->query('SELECT id, date, text FROM news');

        foreach ($query->result_array() as $row)
        {
            echo $row['id'];
            echo $row['date'];
            echo $row['text'];
        }
    }
}

My View:

    <img src='<?php echo base_url(); ?>img/logo.png' id='small_logo' alt="Logo">

News

            <?php foreach($news as $news) { ?>

<?php echo $news->date; ?>

                        <?php echo $news->text; ?>

            <?php } ?>

At present I get the following warning message:
A PHP Error was encountered

Severity: Warning

Message: Invalid argument supplied for foreach()

Filename: views/testv.php

Line Number: 18

Backtrace:

File: C:\xampp\htdocs\tsh\CI\application\views\testv.php
Line: 18
Function: _error_handler

File: C:\xampp\htdocs\tsh\CI\application\controllers\test.php
Line: 16
Function: view

File: C:\xampp\htdocs\tsh\public_html\index.php
Line: 292
Function: require_once

But the text from my database does appear at the top of the page outside of the headder so I know the database is connecting and the data from it is being collected. Can anyone tell me where I'm going wrong?

A: In your controller you're correctly assigning the result of the model to a variable:
$data['news'] = $this->testm->get_news();

but in your model you're ECHOING the result, not RETURNING them. SO $data['news'] is null (since the model's method doesn't return anything), and you can't iterate over null of course -> and that's the error in your view. Change your model to return an array, for example:
Public function get_news()
{
    $query = $this->db->query('SELECT id, date, text FROM news');
    return $query->result_array();
}

the text from my database does appear at the top of the page

because, indeed, you're echoing it (as pointed out above) before the views are outputted, that's why you see them before the rendered html

A: please try this:
in your view page:
<?php foreach($news->result() as $new) { ?>

<?php echo $new->date; ?>

                <?php echo $new->text; ?>

    <?php } ?>

A:         <?php foreach($news as $new) { ?>

<?php echo $new->date; ?>

                    <?php echo $new->text; ?>

        <?php } ?>

Try foreach($news as $new) instead of foreach($news as $news).

A: you just have issue in your model function foreach loop just replace that with:
$query = $this->db->query('SELECT id, date, text FROM news');
$result = $query->result_array();
return $result;

A: use
foreach($thing as $something): //it is important if not compulsory to use a different name for variables!!
some HTML
endforeach;

instead

A: Try this for your answer:
your controller:
public function index($page = 'testv')
{
        if ( ! file_exists(APPPATH.'/views/'.$page.'.php'))
        {
            show_404();
        }
            $this->load->model('testm');
            $data['news'] = $this->testm->get_news();

            $this->load->view('headder');
            $this->load->view($page, $data);
            $this->load->view('footer');
}

model function :
Public function get_news()
{
    $query = $this->db->query('SELECT id, date, text FROM news');
    return $query;
}

in view file :
<?php foreach($news->result() as $new) { ?>

<?php echo $new->date; ?>

            <?php echo $new->text; ?>

<?php } ?>

A: you can use HTML compatible PHP version. that will help customize HTML code with PHP
<?php echo $var; ?> is equal to <?= $var ?>
<?php foreach($allNews as $news): ?>

<?= $news->date ?>

        <?= $news->text ?>

<?php endforeach; ?>


text:
Q: Proper way to store authentication in a Phonegap application Let's say i have a phonegap application connecting to a web service to validate login credentials. Once authenticated, i want to have persistent authentication just like a standard web app that stores a cookies in a browser.
What are the guidelines for these? With security, reliability and standards are considered.
Please don't make this as a "native app vs html5 wrapped app " debate.
I appreciate all logical answers. Thank  you.

A: is this an issue of generating authentication or storing it?
To generate, since you can't use UDID anymore, keep FB or twitter id is fine.
To store, you can write to UserDefaults or to an actual file (there was localStorage but it's currently unreliable).


text:
Q: how to update a existing report & dashboard in production i have 2015 revenue reports in production,in that same report  i added extra field like 2016 revenue field in sandbox(i also added some records in that existing report). Now i want to show 2016 revenue report in production. How can i do this please help me.

A: you can use chain sets- reference doc- http://salesforcedeveloperblog.blogspot.in/2011/05/change-set-deployment-steps.html
or Eclipse - reference doc -http://wiki.developerforce.com/page/Force.com_IDE_Installation_for_Eclipse_3.3.x


text:
Q: How does my PC know what to boot on restart? It is clear that there is some boot sector on my PC which contains the loader with menu, which allows me to choose the OS to load. But, I have noticed that PC does not display me this menu after Windows-restart or Linux-suspend. How does PC, which has lost all RAM decides to bypass the primary boot and load something different?

From what I read about the POST:

In the case of a hard reboot, the northbridge will direct this code fetch (request) to the BIOS located on the system flash memory. For a warm boot, the BIOS will be located in the proper place in RAM and the northbridge will direct the reset vector call to the RAM.

I see that my guess that RAM is lost on restart is wrong.

A: I only know how this works with linux, but I can explain from the grub point of view (a Linux bootloader, others are available).
Basically, the first thing the boot loader does is check what options it has (it looks at a list of drives). From this, it will see that after a hibernation, your swap partition (Again, there's other ways of storing hibernation data but this is the easiest) contains data and this data is infact hibernation data.
Once it's seen this, it instantly goes to booting whatever hibernation data exists instead of displaying the boot menu asking which O/S you wish to boot.
As a side note, I have Grub still display the boot menu even when hibernation data is found, and I can choose to boot without it as an extra option - you might see this if your resuming fails some how.


text:
Q: RuntimeError: RUNTIME ERROR: undefined external variable: jsonlines_embedding_format When I run the command, ant got this issue. The version of the  allennlp is 0.9.
allennlp train /root/code/python/share/scidocs/data/recomm/train_similar_papers_model.json -s /root/code/python/share/scidocs/data/recomm-tmp --include-package scidocs.recommender
And the key message of the train_similar_papers_model.json is here:
local stringToBool(s) =
  if s == "true" then true
  else if s == "false" then false
  else error "invalid boolean: " + std.manifestJson(s);
local EMBEDDINGS_PATH = std.extVar("EMBEDDINGS_PATH");
local CUDA_DEVICE = std.parseInt(std.extVar("CUDA_DEVICE"));
local EMBEDDINGS_DIM = std.parseInt(std.extVar("EMBEDDINGS_DIM"));
local PAPER_METADATA_PATH = std.extVar("PAPER_METADATA_PATH");
local TRAIN_PATH = std.extVar("TRAIN_PATH");
local VALID_PATH = (if std.extVar("VALID_PATH")!="" then std.extVar("VALID_PATH") else null);
local TEST_PATH = std.extVar("TEST_PATH");
local PROP_SCORE_PATH = std.extVar("PROP_SCORE_PATH");
{
    "random_seed": 7,
    "pytorch_seed": 7,
    "numpy_seed": 7,
    "dataset_reader": {
      "type": "simclick_data_reader",
      "paper_features_path": PAPER_METADATA_PATH,
      "paper_embeddings_path": EMBEDDINGS_PATH,
      "max_results_per_query": 10,
      "jsonlines_embedding_format": stringToBool(std.extVar('jsonlines_embedding_format'))
    },

    ....
  }

A: Your config contains:
"jsonlines_embedding_format":stringToBool(std.extVar('jsonlines_embedding_format'))}
which is trying to read an environment variable named jsonlines_embedding_format and convert it to a boolean value.
The error says that the environment variable is not defined, so you need to define it first, before calling the train command.


text:
Q: Not able to fetch Facebook friend photo I not able to get user friends photos not profile picture. I can easily get profile picture
but not able to get user friend photos
I wrote this code but it is not working for me
 FB.api('me/friends?fields=albums', function(response) {
   for (var i=0; i<response.data.length; i++) {
      var album = response.data[i];
      FB.api('/'+album.id+'/photos', function(photos){
        if (photos && photos.data && photos.data.length){
        for (var j=0; j<photos.data.length; j++){
            var photo = photos.data[j];
            // photo.picture contain the link to picture
                var image = document.createElement('img');
            image.src = photo.picture;
            document.body.appendChild(image);
        }
    }
   });
  }
});

Given all the required permission friends_photos,publish_stream
But still no luck .
Please help

A: Your graph url is off. To get a specific users photo album list you need:
{user_id}/albums?fields={list_of_album_fields}

In conjunction with
user_photos and/or friends_photos permissions

The Facebook graph explorer is an excellent tool for getting your graph url's right before coding. Try it out to verify this solution.
If you're looking to get all albums for all friends in a single pass you'll need to formulate this as either FQL or a batch request.


text:
Q: Given a vector field, how to determine values of parameter such that the the work done along a curve is $0$? The vector field is the following: $V_A$ = $(2xyz - z, x^2z + 1,x^2y - x + Ay)$.
I've already verified that it's conservative as long as $A=0$.
Then, the exercise asks to determine values of parameter $A$ such that the the work done along the curve $\gamma(t)$ = $(2^t - t^2 - 1, cos(\pi t), t^2)$,  $t \in [0,1]$ is $0$.
I have the solution with me and it starts by writing the vector field like this: $V_A = V_0 + (0,0,Ay)$ and I can't seem to understand where $(0,0,Ay)$ comes from.


text:
Q: Exiting an infinite process in python subprocess i have the following code
c = open("text.txt", 'a')

output = subprocess.Popen('ping -t 127.0.0.1', stdout=subprocess.PIPE).communicate()[0]

c.write(str(output))

But as the ping is infinite , the code stucks at line two till i close the cmd
how can i close the infinite subprocess

i use python 2

A: You can use -n argument (in linux) for ping to set limited number of ping signals:
process = subprocess.Popen('ping -n 1 127.0.0.1', shell=True, stdout=subprocess.PIPE)
output = process.communicate()[0]
with open("text.txt", 'a') as f:
    f.write(str(output))

Or read a single first line only:
process = subprocess.Popen('ping 127.0.0.1', shell=True, stdout=subprocess.PIPE, universal_newlines=True)

output = process.stdout.readline()
process.stdout.close()
process.kill()

with open("text.txt", 'a') as f:
    f.write(str(output))

A: Alternatively you can use check_output and add a timeout:
from subprocess import check_output

output = check_output('ping -t 127.0.0.1', timeout=seconds)

A: process = subprocess.Popen('ping -t 127.0.0.1', stdout=subprocess.PIPE)
time.sleep(10)
process.kill()
output=process.stdout.read()

with this code , subprocess runs and data will be given stdout,
we don't need to use communicate
when ever you want to stop the process,
use process.kill()
and get data using stdout.read()


text:
Q: tooltip data doesn't update Does anyone know why the tooltip here doesn't update? When I change the title, it should update. Is there something wrong? How can I solve this?

here is the image of output

A: The tooltip needs to be updated programmatically once the title attribute has been changed, it will not automatically render changes made to the div.
Solution from this stackoverflow question;
$(element).attr('title', 'NEW_TITLE')
      .tooltip('fixTitle')
      .tooltip('show');


text:
Q: angularJs custom directive not working with templateUrl I am new to AngularJs. I am writing my custom angular directive which contains a template of some html content. When I use the template with the below code it works fine.
demoApp.directive('demoCarousel', function() {
  return {
    restrict: 'E',
    replace:'true',
    template: "
This is from the custom directive..
"
  };

});
But when I replace the template with templateUrl pointing to a html inside a partial I am getting error.
demoApp.directive('demoCarousel', function() {
  return {
    restrict: 'E',
    replace:'true',
    templateUrl: "/partials/carousel.html"
 };

});
The javascript error is something like:

Error: [$compile:tplrt] http://errors.angularjs.org/1.2.15/$compile/tplrt?p0=glassCarousel&p1=%2Fpartials%2Fcarousel.html

Please let me know where I am going wrong and what the correct way to use the templateUrl
Note: I am using only pure html code inside the carousel.html file.

A: The error sais: Template for directive 'glassCarousel' must have exactly one root element. /partials/carousel.html
this means that you have something like this in your template:

...

...

It is not allowed, you should have one root element:

...

...


text:
Q: Saiku ui deployed separately saiku No query found with name I am trying to integrate saiku-ui with my custom web application (say x.com). This communicates with saiku-server deployed somewhere else (say y.com)
I've modified security settings so that users are authenticated anonymously which I got using these changes to application-context-saiku-webapp.xml
<security:http auto-config='true' access-denied-page="/login.jsp">
<security:intercept-url pattern="/serverdocs/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<security:intercept-url pattern="/rest/saiku/session*" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<security:intercept-url pattern="/rest/saiku/session/" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<security:intercept-url pattern="/rest/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<security:intercept-url pattern="/json/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />

The problem I am facing is that I am not able to save query anonymously
When I do this post call,
curl -X POST -H "Content-Type: application/json" --data '{"schema":["FoodMart"],"formatter":["flattened"],"connection":["foodmart"],"catalog":["FoodMart"],"cube":["HR"],"type":["QM"]}' http:///saiku/rest/saiku/admin/query/3A956804-01EC-6B3D-A8B9-31EEB8CC2747
I get this response
{"uniqueName":"[foodmart].[FoodMart].[FoodMart].[HR].[3A956804-01EC-6B3D-A8B9-31EEB8CC2747]","name":"3A956804-01EC-6B3D-A8B9-31EEB8CC2747","cube":{"uniqueName":"[foodmart].[FoodMart].[FoodMart].[HR]","name":"HR","connectionName":"foodmart","catalogName":"FoodMart","schemaName":"FoodMart","caption":"HR","visible":true,"cubeName":"[HR]"},"mdx":"SELECT\nFROM [HR]","type":"QM","properties":{"saiku.olap.query.limit":"true","saiku.olap.query.filter":"true","org.saiku.query.explain":"true","org.saiku.connection.scenario":"false","saiku.olap.query.nonempty":"true","saiku.olap.query.nonempty.rows":"true","saiku.olap.query.nonempty.columns":"true","saiku.olap.query.drillthrough":"true"},"saikuAxes":[{"uniqueName":"COLUMNS","name":"COLUMNS","dimensionSelections":[],"ordinal":0,"sortOrder":null,"sortLiteral":null,"limitFunction":null,"limitFunctionN":null,"limitFunctionSortLiteral":null,"filterCondition":null},{"uniqueName":"ROWS","name":"ROWS","dimensionSelections":[],"ordinal":1,"sortOrder":null,"sortLiteral":null,"limitFunction":null,"limitFunctionN":null,"limitFunctionSortLiteral":null,"filterCondition":null},{"uniqueName":"FILTER","name":"FILTER","dimensionSelections":[],"ordinal":-1,"sortOrder":null,"sortLiteral":null,"limitFunction":null,"limitFunctionN":null,"limitFunctionSortLiteral":null,"filterCondition":null}]}
and catalina.out says
2014-01-01 17:50:09,877 DEBUG [org.saiku.web.rest.resources.QueryResource] TRACK        /query/3A956804-01EC-6B3D-A8B9-31EEB8CC2747 POST     xml:false
but when I try to get the same query using
curl -XGET http:///saiku/rest/saiku/admin/query/3A956804-01EC-6B3D-A8B9-31EEB8CC2747
I get "No query found using name"

org.saiku.service.util.exception.SaikuServiceException: No query found using name: 3A956804-01EC-6B3D-A8B9-31EEB8CC2747
org.saiku.service.olap.OlapQueryService.getIQuery(OlapQueryService.java:1015)
org.saiku.service.olap.OlapQueryService.getQuery(OlapQueryService.java:175)
org.saiku.web.rest.resources.QueryResource.getQuery(QueryResource.java:126)
org.saiku.web.rest.resources.QueryResource$$FastClassByCGLIB$$e130f1a0.invoke(<generated>)
net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:617)
org.saiku.web.rest.resources.QueryResource$$EnhancerByCGLIB$$e19ca8a4.getQuery(<generated>)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
java.lang.reflect.Method.invoke(Method.java:597)
com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288)
com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)

What is going wrong here?

A: This was happening because, there was no session context.
Got around by simulating login from my web service!


text:
Q: jQuery select next closest class I have a simple list of FAQ's

Q:

Question

A:

Answer

Q:

Question

A:

Answer

All I am trying to do is a toggle the visable state of the next answerr when the question is clicked.
So far I have got
   $('.qcontainer').bind("click", function (e) {
        $('.qcontainer').next('.acontainer').toggle(400);
    });

But this toggles all the items, what i want to do is just target teh answer for the clicked  question. so the next item in the list from the clicked object.

A: Try like below,
$('.qcontainer').bind("click", function (e) {
    $(this).next().toggle(400);
});

For the markup you have, .next of qcontainer is acontainer and so you can simply use .next to toggle acontainer and not worry about a thing :)

A: $('.qcontainer').bind("click", function (e) {
        $('.acontainer:visible').hide(0);
        $(this).nextAll('.acontainer').show(400);
    });

A: It looks like you were close!
$('.qcontainer').bind("click", function () {
    $(this).next('.acontainer').toggle(400);
});

A: Try this, tell me if it works. In the answer DIV you have one unclosed "DIV".

Q:1

Question

A:

Answer

Q:2

Question

A:

Answer


text:
Q: How can i change the image URL's text in javascript? I'm using this line to change a specific word in a text to other word:
 document.body.innerHTML = document.body.innerHTML.replace(/katt/g, "smurf");

Now I'm trying to use the same line to change an image URL in HTML but it doesn't work. I trying this code:
document.body.innerHTML = document.body.innerHTML.replace(/"https://oldimage.jpg"/g, "https://newimage.jpg");

A: Escape // inside Regex like \/\/. You also should not have surrounding "":

document.body.innerHTML = "https://oldimage.jpg"
document.body.innerHTML = document.body.innerHTML.replace(/https:\/\/oldimage.jpg/g, "https://newimage.jpg");


text:
Q: Error de exclusión en proyeccion de query en MongoDB Tengo una duda y es que yo estoy aplicando la proyección sólo con la parte de la proyección y no el query, por ejemplo:
 db.empleados.find({},{nombre: 1, apellido: 0})

Sin embargo, me sale un error, no se si estoy usando la sintaxis bien o algo asi pero me dice esto:
error: {
        "ok" : 0,
        "errmsg" : "Cannot do exclusion on field apellido in inclusion projection",
        "code" : 31254,
        "codeName" : "Location31254"
}

A: Cuando usas un valor 1 indicando inclusión del campo nombre en tu proyección, todas las propiedades restantes (excepto _id) se sobreentienden en 0 (exclusión). Es por ello el mensaje de error, ya que estás indicando a la vez un valor de inclusión sobre nombre y uno de exclusión sobre apellido, lo cual no es correcto.
Esto quiere decir que tu proyección debe escribirse sólo en términos de inclusión o sólo en términos de exclusión. Por ejemplo:
// inclusión
db.empleados.find({},{nombre: 1});  // incluye sólo nombre y _id

// exclusión
db.empleados.find({},{apellido: 0});  // excluye sólo apellido

La única excepción a esta regla es sobre el campo _id que siempre es devuelto (siempre se incluye en la respuesta) a menos que se indique lo contrario explícitamente en la proyección:
// inclusión (excluye _id y el resto de campos)
db.empleados.find({},{nombre: 1, _id: 0});  // incluye sólo nombre

// exclusión (excluye apellido y _id)
db.empleados.find({},{apellido: 0, _id: 0});  // excluye sólo apellido y _id

Espero que esto te ayude a resolver el problema.
EDICIÓN
Al parecer falta hacer hincapié en el hecho de que no se puede mezclar una proyección de inclusión con una de exclusión. Y es que muchos tutoriales no dejan claro este concepto.
Supongamos que tengo el siguiente documento almacenado en la colección users de mi base de datos:
{
  _id: ObjectId("6176c88a48c86d4c72acc522"),
  nombre: "Mauricio",
  apellidos: "Contreras Canepa",
  email: "mauricio@email.com",
  edad: 0x69,
}

Si deseo obtener una lista de todos los documentos de mi colección users que incluyan sólo el campo nombre, la consulta sería la siguiente:
db.users.find({},{ nombre: 1 });

El resultado de la consulta anterior sería:
{
  ObjectId("6176c88a48c86d4c72acc522"),
  nombre: "Mauricio",
}

Como observamos trae, además del campo nombre, el campo _id.
La consulta anterior es una consulta de inclusión, estoy indicando explícitamente los campos que deseo obtener en el resultado.
No sólo puedes usar 1 y 0 como indicador, también puedes usar true y false. La siguiente consulta es totalmente válida y equivalente a la anterior:
db.users.find({},{ nombre: true });

Ahora, si no deseamos incluir en el resultado de la consulta el campo _id, debemos excluirlo explícitamente. Este campo, siendo un campo especial de MongoDB siempre se considerará incluido en el resultado y es el único campo que puedo excluir explítamente en una proyección de inclusión. El resto de campos no puedo excuirlos explícitamente, ya que por defecto, todo campo no incluido en una proyección se considera excluido. Asimismo, todo campo que no sea excluido explícitamente en una proyección se considera incluido.
db.users.find({},{ nombre: 1, _id: 0 });

// o usando true y false:

db.users.find({},{ nombre: true, _id: false });

Consideremos el escenario planteado en la pregunta y supongamos que el documento contiene los campos establecidos en este ejemplo. Si deseamos incluir el campo nombre, muy bien, usamos como proyección: { nombre: 1 }. Eso indica que todos los campos restantes estarán excluidos (excepto el campo _id).
Ahora, supongamos que deseo excluir sólo el campo apellidos, entonces la proyección de exclusión será: { apellidos: 0 }, y el resto de campos se considera incluido en la respuesta.
Por último, supongamos que quiero el campo nombre pero no quiero el campo apellidos, entonces se me ocurre escribir la siguiente proyección (errónea como ya hemos dicho): { nombre: 1, apellidos: 0 }. ¿Qué pasa con el resto de campos? ¿Los incluyo? ¿Los excluyo? Si los incluyo ¿significa que la proyección de exclusión le gana a la inclusión? Si los excluyo ¿entonces es al contrario? ¿De qué manera puedo determinar lo que haré con el resto de campos?.
Es por ello que las proyecciones en MongoDB sólo se pueden escribir en términos de inclusión o de exclusión.
De todas formas, la documentación es bastante específica al respecto:
Original:

Note
With the exception of the _id field, you cannot combine inclusion and exclusion statements in projection documents.

Traducción propia:

Nota
A excepción del campo _id, no se puede combinar sentencias de inclusión y exclusión en documentos de proyección.