text:
Q: (pyspark)How to Divide Time Intervals into Time Periods I have a dataframe created by sparksql with IDs corresponding to checkin_datetime and checkout_datetime.As the picture shows.

I would like to divide this time interval into one-hour time periods. As the picture shows.

Code to create sparkdataframe:
import pandas as pd
data={'ID':[4,4,4,4,22,22,25,29],

 'checkin_datetime':['04-01-2019 13:07','04-01-2019 13:09','04-01-2019 14:06','04-01-2019 14:55','04-01-2019 20:23'
  ,'04-01-2019 21:38','04-01-2019 23:22','04-02-2019 01:00'],
  'checkout_datetime':['04-01-2019 13:09','04-01-2019 13:12','04-01-2019 14:07','04-01-2019 15:06','04-01-2019 21:32'
                       ,'04-01-2019 21:42','04-02-2019 00:23'
                       ,'04-02-2019 06:15']
}
df = pd.DataFrame(data,columns= ['ID', 'checkin_datetime','checkout_datetime'])
df1=spark.createDataFrame(df)

A: To compute hourly interval,

*

*First explode hourly intervals between checkin_datetime and checkout_datetime. We do this by computing the hours between the checkin_datetime and checkout_datetime and iterating over the range to generate the intervals.

*Once we have exploded the intervals to find the next_hour, we can use this to identify the gap between checkin_datetime and next_hour or checkout_datetime and next_hour.

from pyspark.sql import functions as F

import pandas as pd
data={'ID':[4,4,4,4,22,22,25,29],

 'checkin_datetime':['04-01-2019 13:07','04-01-2019 13:09','04-01-2019 14:06','04-01-2019 14:55','04-01-2019 20:23'
  ,'04-01-2019 21:38','04-01-2019 23:22','04-02-2019 01:00'],
  'checkout_datetime':['04-01-2019 13:09','04-01-2019 13:12','04-01-2019 14:07','04-01-2019 15:06','04-01-2019 21:32'
                       ,'04-01-2019 21:42','04-02-2019 00:23'
                       ,'04-02-2019 06:15']
}
df = pd.DataFrame(data,columns= ['ID', 'checkin_datetime','checkout_datetime'])
df1=spark.createDataFrame(df).withColumn("checkin_datetime", F.to_timestamp("checkin_datetime", "MM-dd-yyyy HH:mm")).withColumn("checkout_datetime", F.to_timestamp("checkout_datetime", "MM-dd-yyyy HH:mm"))

unix_checkin = F.unix_timestamp("checkin_datetime")
unix_checkout = F.unix_timestamp("checkout_datetime")

start_hour_checkin = F.date_trunc("hour", "checkin_datetime")
unix_start_hour_checkin = F.unix_timestamp(start_hour_checkin)
checkout_next_hour = F.date_trunc("hour", "checkout_datetime") + F.expr("INTERVAL 1 HOUR")

diff_hours = F.floor((unix_checkout - unix_start_hour_checkin) / 3600)

next_hour = F.explode(F.transform(F.sequence(F.lit(0), diff_hours), lambda x: F.to_timestamp(F.unix_timestamp(start_hour_checkin) + (x + 1) * 3600)))

minute = (F.when(start_hour_checkin == F.date_trunc("hour", "checkout_datetime"), (unix_checkout - unix_checkin) / 60)
           .when(checkout_next_hour == F.col("next_hour"), (unix_checkout - F.unix_timestamp(F.date_trunc("hour", "checkout_datetime"))) / 60)
           .otherwise(F.least((F.unix_timestamp(F.col("next_hour")) - unix_checkin) / 60, F.lit(60)))
         ).cast("int")

(df1.withColumn("next_hour", next_hour)
    .withColumn("minutes", minute)
    .withColumn("hr", F.date_format(F.expr("next_hour - INTERVAL 1 HOUR"), "H"))
    .withColumn("day", F.to_date(F.expr("next_hour - INTERVAL 1 HOUR")))
    .select("ID", "checkin_datetime", "checkout_datetime", "day", "hr", "minutes")
).show()
"""
+---+-------------------+-------------------+----------+---+-------+
| ID|   checkin_datetime|  checkout_datetime|       day| hr|minutes|
+---+-------------------+-------------------+----------+---+-------+
|  4|2019-04-01 13:07:00|2019-04-01 13:09:00|2019-04-01| 13|      2|
|  4|2019-04-01 13:09:00|2019-04-01 13:12:00|2019-04-01| 13|      3|
|  4|2019-04-01 14:06:00|2019-04-01 14:07:00|2019-04-01| 14|      1|
|  4|2019-04-01 14:55:00|2019-04-01 15:06:00|2019-04-01| 14|      5|
|  4|2019-04-01 14:55:00|2019-04-01 15:06:00|2019-04-01| 15|      6|
| 22|2019-04-01 20:23:00|2019-04-01 21:32:00|2019-04-01| 20|     37|
| 22|2019-04-01 20:23:00|2019-04-01 21:32:00|2019-04-01| 21|     32|
| 22|2019-04-01 21:38:00|2019-04-01 21:42:00|2019-04-01| 21|      4|
| 25|2019-04-01 23:22:00|2019-04-02 00:23:00|2019-04-01| 23|     38|
| 25|2019-04-01 23:22:00|2019-04-02 00:23:00|2019-04-02|  0|     23|
| 29|2019-04-02 01:00:00|2019-04-02 06:15:00|2019-04-02|  1|     60|
| 29|2019-04-02 01:00:00|2019-04-02 06:15:00|2019-04-02|  2|     60|
| 29|2019-04-02 01:00:00|2019-04-02 06:15:00|2019-04-02|  3|     60|
| 29|2019-04-02 01:00:00|2019-04-02 06:15:00|2019-04-02|  4|     60|
| 29|2019-04-02 01:00:00|2019-04-02 06:15:00|2019-04-02|  5|     60|
| 29|2019-04-02 01:00:00|2019-04-02 06:15:00|2019-04-02|  6|     15|
+---+-------------------+-------------------+----------+---+-------+
"""


text:
Q: How to apply Gradient to UIView in iOS 10 on a real device I have this extension to add a Gradient to a View in Swift:
extension UIView {
    func addGradientWithColor(colorTop: UIColor, colorButton: UIColor){
        let gradient = CAGradientLayer()
        gradient.frame = self.bounds
        gradient.colors = [colorTop.cgColor, colorButton.cgColor]

        self.layer.insertSublayer(gradient, at: 0)
    }
}

Then, I use it like that in my UIViewController:
override func viewDidLoad(){
    self.view.addGradientWithColor(colorTop: UIColor.red, colorButton: UIColor.clear)
    super.viewDidLoad()
}

I run the simulator and it works great. But when I want use my app on a real device, the Gradient does not work.
PD: I tried many ways to do a Gradient but nothing worked on a real device.

A: Try this, it's working for me. Code:
let gradientLayer:CAGradientLayer = CAGradientLayer()
gradientLayer.frame.size = self.gradientView.frame.size
gradientLayer.colors = [UIColor.white.cgColor,UIColor.red.withAlphaComponent(1).cgColor] //Use diffrent colors
gradientLayer.startPoint = CGPoint(x: 0.0, y: 1.0)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0)
self.gradientView.layer.addSublayer(gradientLayer)

For more details explanation see this: Gradient On UIView

A: The problem is that you are not resizing the layer when the size of the view changes, thus it remains at it's initial value, which mostly depends on how was the view created.
I'd recommend using an UIView subclass, and updating the layer size in the layoutSubviews method, which always gets called when the view resizes:
@IBDesignable
open class GradientView: UIView {
    @IBInspectable
    public var startColor: UIColor = .white {
        didSet {
            gradientLayer.colors = [startColor.cgColor, endColor.cgColor]
            setNeedsDisplay()
        }
    }
    @IBInspectable
    public var endColor: UIColor = .white {
        didSet {
            gradientLayer.colors = [startColor.cgColor, endColor.cgColor]
            setNeedsDisplay()
        }
    }

    private lazy var gradientLayer: CAGradientLayer = {
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = self.bounds
        gradientLayer.colors = [self.startColor.cgColor, self.endColor.cgColor]
        return gradientLayer
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        layer.insertSublayer(gradientLayer, at: 0)
    }

    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        layer.insertSublayer(gradientLayer, at: 0)
    }

    open override func layoutSubviews() {
        super.layoutSubviews()
        gradientLayer.frame = bounds
    }
}

The code above also let's you tweak the start and end colour from Xcode so you have an estimate of how the view will look like when deployed.

A: Just make sure that you're using color.cgColor instead of color.

A: This code for Gradient with transparent background in Swift 5. [transparent|white mix]
    let gradientLayer:CAGradientLayer = CAGradientLayer()
    gradientLayer.colors = [UIColor.white.withAlphaComponent(0.0).cgColor, UIColor.white.cgColor]
    gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.0)
    gradientLayer.endPoint = CGPoint(x: 0.5, y: 1.0)
    gradientLayer.frame.size = self.gradientView.frame.size

    self.gradientView.layer.addSublayer(gradientLayer)

A: Using the answers from @Cristik and another user (who's answer I can't find, so if you are that user please let me know so I can give you the credit)
I got this (which updates in storyboard/real device/simulator and allows vertical or horizontal):
Tested on Xcode 11, Swift 5:
@IBDesignable class GradientView: UIView {

    @IBInspectable
    public var firstColor: UIColor = .white {
        didSet {
            gradientLayer.colors = [firstColor.cgColor, secondColor.cgColor]
            setNeedsDisplay()
        }
    }

    @IBInspectable
    public var secondColor: UIColor = .white {
        didSet {
            gradientLayer.colors = [firstColor.cgColor, secondColor.cgColor]
            setNeedsDisplay()
        }
    }

    @IBInspectable var vertical: Bool = true {
        didSet {
            updateGradientDirection()
        }
    }

    lazy var gradientLayer: CAGradientLayer = {
        let layer = CAGradientLayer()
        layer.colors = [firstColor.cgColor, secondColor.cgColor]
        layer.startPoint = CGPoint.zero
        return layer
    }()

    // MARK: - Lifecycle

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        applyGradient()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        applyGradient()
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        applyGradient()
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        updateGradientFrame()
    }

    // MARK: - Helper

    func applyGradient() {
        updateGradientDirection()
        layer.sublayers = [gradientLayer]
    }

    func updateGradientFrame() {
        gradientLayer.frame = bounds
    }

    func updateGradientDirection() {
        gradientLayer.endPoint = vertical ? CGPoint(x: 0, y: 1) : CGPoint(x: 1, y: 0)
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Decomposing the top of a module Let $M$ be a finitely generated Artinian $R$-module. Then there exists a decomposition $M = \oplus_{i=1}^kM_i$ such that each $M_i$ is an indecomposable submodule of $M$. It is known that $\text{rad}(M) = \oplus_{i=1}^k\text{rad}(M_i)$ and $\text{soc}(M) = \oplus_{i=1}^k\text{soc}(M_i)$.
I'm able to prove that $\text{top}(M) = \oplus_{i=1}^k\text{top}(M_i)$, where $\text{top}(M) := M/\text{rad}(M)$, however I'm wondering if this result has been established in the literature? This is for my MSc thesis, and I would rather not include a proof of a result that is well-known.
Thanks.


text:
Q: How to dump a folded scalar to YAML in Python (using ruamel?) I've been scouring stackoverflow looking for a way to dump a folded scalar in YAML format using Python.  A common answer is from user Anthon who suggests using his ruamel Python library.  I took the advice but I cannot figure out how to dump a long Python string value in folded style.
In Anthon's answer's he/she often uses a hard-coded string with the folded style representer ">" to illustrate his point like so:
yaml_str = """\
long: >
  Line1
  Line2
  Line3
"""
data = yaml.load(yaml_str, Loader=yaml.RoundTripLoader)
print(yaml.dump(data, Dumper=yaml.RoundTripDumper))

I'm not sure how to translate that example into my own code where the string value I'd like to dump comes not from a hard-coded value with the folded representer already in it, but from a Django request (well it could come from anywhere really, the point is, I'm not constructing the string in my code manually with ">").
Am I really meant to do something like:
stringToDumpFolded = "ljasdfl\n\nksajdf\r\n;lak'''sjf"

data = "Key: > \n" + stringToDumpFolded

ruamel.yaml.dump(data, f, Dumper=yaml.RoundTripDumper))

Otherwise, given a long unicode string variable, how do I use ruamel to dump it to a file?

A: Starting with 0.15.61 it is possible to round-trip folded scalars in ruamel.yaml:
import sys
import ruamel.yaml

yaml_str = """\
long: >
  Line1
  Line2
  Line3
"""

yaml = ruamel.yaml.YAML()
data = yaml.load(yaml_str)
print(type(data['long']), data['long'].fold_pos, end='\n-----\n')
yaml.dump(data, sys.stdout)

which gives:
<class 'ruamel.yaml.scalarstring.FoldedScalarString'> [5, 11]
-----
long: >
  Line1
  Line2
  Line3

The print of the type is only there to show how you could establish
yourself what object to create if working from scratch:
from ruamel.yaml.scalarstring import FoldedScalarString as folded

s = folded('Line1 Line2 Line3\n')
data = dict(long=s)
yaml.dump(data, sys.stdout)

which gives a folded scalar, but probably not the way you want:
long: >
  Line1 Line2 Line3

To get this to fold you have to provide the .fold_pos attribute. That
attribute has to be a list (or some reversable iterable) with the position of
space characters in the string, where folds need to be inserted:
s = folded('Line1 Line2 Line3\n')
s.fold_pos = [5, 11]
data = dict(long=s)
yaml.dump(data, sys.stdout)

which returns the output you expected:
long: >
  Line1
  Line2
  Line3

Since you seem to want all spaces to be folded, you can also do something like:
import re
s.fold_pos = [x.start() for x in re.finditer(' ', s)]


text:
Q: Problem with Ckeditor in Symfony 3.4 app when deploying on Heroku Ckeditor didn't appear when I deploy it to Heroku but it is working perfectly at local.
How can I fix it?
Error in Console:

Thanks in advance.
Lucas.


text:
Q: How can I put a datepicker with mvc5 I have this code:

            @*@Html.LabelFor(model => model.DT_AGENDAMENTO, htmlAttributes: new { @class = "control-label col-md-2" })*@
            @Html.Label("Data de Agendamento", htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.DT_AGENDAMENTO, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.DT_AGENDAMENTO, "", new { @class = "text-danger" })

And at the end of my view, I have:
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/jqueryui")

    $(document).ready(function(){
        $(".datepicker").datepicker();
    });
}

How can I do to put a Datepicker(jquery or other) on my textbox(razor)?
Debugging the page on dev tools of chrome, I have this error:

GET http://localhost:55839/bundles/jquery-ui 404 (Not Found)

I do not know how to do.

A: For up to date browsers, the best choice is adding these data attributes to related property in class difination:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]

Then just use  @Html.EditorFor for property in view.
For bundles error check your bundles/jquery-ui  in App_Start > BundleConfig.cs . probably definition has errore


text:
Q: Chosen / Select2 Style Library for Autocomplete I've been using the Select2 library in my web application to replace the default select elements, and I really like how the library looks and how easy it is to use. Now, I'm trying to implement an autocomplete feature for a text field on the same application and I want to use a library that looks similar to Select2. (To keep the UI consistent.) Are there any such libraries that you know of? (Google isn't helping.)

A: select2 is also an autocomplete library and can replace both select elements and input elements.


text:
Q: Telegram bot - How can I create a popup message? Thanks for reaching this feed.
I would like to request the method/example/API doc for the popup "Spin Wheel" (see below image) in the Telegram doc.
I have tried a couple of keywords e.g. telegram bot custom popup, but still no luck..
Thanks for your time!

https://core.telegram.org/bots#payment-platform

A: I think now you can do similar custom controlls with telegram web apps feature:
https://core.telegram.org/bots/webapps


text:
Q: ticks on scatter plots This may be a very simple question as I already plot so many scattered plots.
I have a file with multiple columns, I want to plot a scatter plot with two columns(contains decimals values). I used different Xlim and Ylims but it does not work. Would you please have a look that where I'm repeating a mistake? It should be limited within Xlim (104,105) and Ylim (29,30).  Thanks
data example:
104.4990 29.3803
104.482 29.38342
104.480 29.4245
104.4900 29.4010
104.4899 29.39437
104.4968 29.3899
104.4902 29.38032
104.5358 29.4033
104.486 29.37633
104.4940 29.38172
104.4793 29.3925
104.5393 29.40455

plt.rcParams.update({'figure.figsize':(10,8), 'figure.dpi':100})
for cluster in os.listdir(data):
    if cluster.endswith("BXC.txt"):
        clust=os.path.join(data,cluster)
        with open (clust, "r") as myfile:
            for line in myfile:
                l= line.rstrip("\n").split(" ")
                evla=l[4][:-10]
                evlo=l[5][:-10]
                plt.scatter(evlo, evla)
            plt.show()


text:
Q: Bootstrap Tab Responsiva Estou com umas tabs e quero deixar responsiva. Achei um exemplo no codepen, utilizando a versão 3.3 do Bootstrap. No projeto que estou concertando, usaram a 4.0.0-alpha-6.
OBS.: VISUALIZAR COM A TELA MENOR QUE 480px, só aplica a regra quando for mobile.
LINK ORIGINAL: https://codepen.io/d3rsonbr/pen/PRJrmm
No meu caso, fiz algumas mudanças, e está funcionando quando avança as TABS, mas quando clica para voltar, não funciona. Se alguem puder me ajudar.

            Menu 1

            Menu 2

            Menu 3

            Menu 4

            Menu 5

        MENU 1

        MENU 2

        MENU 3

        MENU 4

        MENU 5

CSS:
@media screen and (max-width: 479px) {

    .nav-tabs-responsive > li {
        display: none;
        width: 23%;
    }

  .nav-tabs-responsive > li > a {
    max-width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    word-wrap: normal;
    width: 100%;
    width: 100%;
    text-align: center;
    vertical-align: top;
  }
  .nav-tabs-responsive > li.active {
    width: 54%;
  }
  .nav-tabs-responsive > li.active:first-child {
    margin-left: 23%;
  }
  .nav-tabs-responsive > li.active, .nav-tabs-responsive > li.prev, .nav-tabs-responsive > li.next {
    display: block;
  }
  .nav-tabs-responsive > li.prev, .nav-tabs-responsive > li.next {
    -webkit-transform: scale(0.9);
    transform: scale(0.9);
  }
  .nav-tabs-responsive > li.next > a, .nav-tabs-responsive > li.prev > a {
    -webkit-transition: none;
    transition: none;
  }
  .nav-tabs-responsive > li.next > a .text, .nav-tabs-responsive > li.prev > a .text {
    display: none;
  }
  .nav-tabs-responsive > li.next > a:after, .nav-tabs-responsive > li.next > a:after, .nav-tabs-responsive > li.prev > a:after, .nav-tabs-responsive > li.prev > a:after {
    position: relative;
    top: 1px;
    display: inline-block;
    font-family: 'FontAwesome';
    font-style: normal;
    font-weight: 400;
    line-height: 1;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
  }
  .nav-tabs-responsive > li.prev > a:after {
    content: "\f053";
  }
  .nav-tabs-responsive > li.next > a:after {
    content: "\f054";
  }
}

E o JS:
$(document).on('show.bs.tab', ' [data-toggle="tab"]', function(e) {

                    var $target = $(e.target);
                    var $tabs = $target.closest('.nav-tabs-responsive');

                    var $current = $target.closest('li');
                    var $next = $current.next();
                    var $prev = $current.prev();

                    $tabs.find('>li').removeClass('next prev');
                    $tabs.find('>li>a').removeClass('active');

                    $current.addClass('active');

                    $prev.addClass('prev');
                    $next.addClass('next');
          $('.prev a').removeClass('active');
                    $('.next a').removeClass('active');

});

LINK CODEPEN: https://codepen.io/d3rsonbr/pen/xWPGrz


text:
Q: Using qgis:selectbylocation in PyQGIS I am trying to use the processing toolbox to perform a spatial query (points in polygon). I am not sure how to use the tool and I keep getting this Error:

Wrong number of parameters.

Here is my script:
polygon_path = r"D:\PythonTesting\SelectByLocation\mitte.shp"
points_path = r"D:\PythonTesting\SelectByLocation\punkte.shp"

polygon = QgsVectorLayer(polygon_path, 'Mitte', 'ogr')
points = QgsVectorLayer(points_path, 'Berlin Punkte', 'ogr')

processing.runalg('qgis:selectbylocation', points, polygon, False, False, False, 0)

I used the documentation, which indicates that I have to use 6 parameters.
However, if I call alghelp the following is returned, indicating 5 parameters:
ALGORITHM: Select by location
    INPUT <ParameterVector>
    INTERSECT <ParameterVector>
    PREDICATE <ParameterGeometryPredicate>
    METHOD <ParameterSelection>
    OUTPUT <OutputVector>

METHOD(Aktuelle Auswahl ändern mit)
    0 - creating new selection
    1 - adding to current selection
    2 - removing from current selection

Either way I am not getting it to run correctly.

A: I used this code:
mapcanvas = iface.mapCanvas()

layers = mapcanvas.layers()

processing.runalg('qgis:selectbylocation', layers[0], layers[1], u'within', 0)

with this situation:

and it worked:

Updating for QGIS 3:
Following code works in QGIS 3.20 (Odense):
mapcanvas = iface.mapCanvas()

layers = mapcanvas.layers()

parameters = { 'INPUT' : layers[0],
               'INTERSECT' : layers[1],
               'METHOD' : 0,
               'PREDICATE' : [0] }

processing.run('qgis:selectbylocation', parameters )

I tried it out as it can be observed in following picture.


text:
Q: core location not asking permission problem :
For some reason, the app I'm working on is not asking for permission to use location services. This used to work before. Also, I created a new project in which I followed the steps described below EXACTLY in which this worked immediately.
One difference is I know the authorization status in the main app I'm working on is .Denied, it was .NotDetermined in the test project.
I read this answe on stack overflow :
Core Location not requesting user permission
'
Not many people know this, but after you uninstall an application, that application's documents and preferences are still stored on the device, here:
/var/mobile/Library/Safe Harbor/myappidentifier/Container/
in my opinion, this was not a wise move by apple, as that could have security risks, as the one you have explained above.
If an app is re-installed, iOS automatically copies those preferences back into the appropriate folder. That is the cause of the behavior you are seeing.
'
This could explain it because I did reinstall the app but it doesn't say how to solve it.
Thank you
Here's the relevant code i wrote in the App :
I set the NSLocationAlwaysUsageDescription key in info.plist
I imported core location :
import CoreLocation

implemented the right protocol:
CLLocationManagerDelegate

set this property :
var locationManager  = CLLocationManager()

set the delegate in ViewDidLoad
locationManager.delegate = self

and wrote a test function to test this :
        if CLLocationManager.locationServicesEnabled() {
println("Location Services Enabled")
        if CLLocationManager.authorizationStatus() == .Authorized {
            println("Location Services Authorized")
        } else if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
            println("Location Services Authorized WHEN IN USE")
        } else if CLLocationManager.authorizationStatus() == .NotDetermined {
            println("Location Services NOT Authorized: NOT DETERMINED")
        } else if CLLocationManager.authorizationStatus() == .Restricted {
            println("Location Services NOT Authorized: RESTRICTED")
        } else if CLLocationManager.authorizationStatus() == .Denied {
            println("Location Services NOT Authorized: DENIED")
        } else {
            println("Location Services NOT Authorized")
            locationManager.requestAlwaysAuthorization()
        }

    } else {
        println("!!! Location Services NOT Enabled !!!")
    }

Console Output :
Location Services Enabled
Location Services NOT Authorized

A: You can go into the Settings app, General, and reset Location & Privacy to get the initial permission dialog for your app again.  Otherwise, iOS saves the first answer without ever asking again.


text:
Q: R for loop on objects in global environment to subset on one variable Say I have 3 objects (A, B and C) in my global environment:
A <- data.frame(
  "Var1" = c("0", "0", "1", "0"),
  "Var2" = c("1", "0", "0", "0"),
  "Var3" = c("0","1", "1", "1"),
  "Site" = c("alpha", "alpha", "beta" ,"gamma")
)

B <- data.frame(
  "Var4" = c("0", "0", "1", "1"),
  "Var5" = c("1", "0", "0", "1"),
  "Site" = c("alpha", "beta" , "beta" ,"gamma")
)

C <- data.frame(
  "Var6" = c("0", "0", "1"),
  "Var7" = c("1", "0", "0"),
  "Site" = c("alpha", "beta" ,"gamma")
)

I would like to create a loop through all the objects in my global environment and subset on the "Site" variable and create and naming the following datasets as:
A_alpha = A[A$Site == 'alpha',]
A_beta = A[A$Site == 'beta',]
A_gamma = A[A$Site == 'gamma',]
B_alpha = B[B$Site == 'alpha',]
B_beta = B[B$Site == 'beta',]
B_gamma = B[B$Site == 'gamma',]
C_alpha = C[C$Site == 'alpha',]
C_beta = C[C$Site == 'beta',]
C_gamma = C[C$Site == 'gamma',]

How would the loop look like?


text:
Q: mongoose model inheritance within javascript prototypal object Suppose you have a route initialization like this required in your main:
module.exports = function(app) {
  for (var name in names) {
    var schema = new Schema({})  // schema that accepts anything
      , m = mongoose.model(name, schema)
      , controller = new TextController(m)
    app.get('/path', controller.create.bind(controller))
    // etc, etc

And TextController is defined externally as:
var TextController = function(Model) {
  this.Model = Model
}
TextController.prototype.create = function(req, res) {
  var aDoc = this.Model({   // this is the problematic bit
      title: req.body.title
    , content: req.body.content})
  aDoc.save(function(err) {...})
}

For some reason, mongo saves this as an empty document even though the title and content params are the expected strings. As expected, this.Model is some sort of mongoose object, but it seems to be rejecting the save or the instantiation. Any ideas or suggestions?
Note: I added the controller.method.bind(controller) because it was the only way (I knew of) to get access to this.Model.
Edit: I've also tried the following:
var TextController = function(myCollection) {
  this.myCollection = myCollection
  this.list = function(req, res) {
    this.myCollection.find({}, function { ... })
  }
}

And also tried passing in the name and initializing the model within the scope of the function function(name) { this.myCollection = mongoose.model(name)  ... }

A: This turns out to be unrelated to javascript prototypes and completely due to how mongoose does Mixed Type Schemas:
In order to tell mongoose the document has changed you need to markModified(field)
example here: http://mongoosejs.com/docs/schematypes.html#mixed


text:
Q: Semantics of "?faces-redirect=true" in  and why not use it everywhere I would like to understand what are the semantics behind appending the "?faces-redirect=true" in the action property of a <h:commandlink> tag in JSF2.0. Whether with it or with out it, the application indeed navigates to the target page specified in the action. So at first glance it seems that the only effect is cosmetic, i.e. to provide feedback to the user (if he is looking at the browser's visited URL) that he has moved to a new page. But if it is so innocuous and side-effects-free I cannot see why it is not the default behaviour. I suspect that it has to do with the post-based mechanism of JSF2.0. I 've noticed when browsing through a JSF application that the URLs one sees at his browser (when ?faces-redirect=true is not used) are the ones of the "previous" "page".
meta-NB. I am behind a firewall and plagued with the "SO requires external JavaScript from another domain" issue so I apologize for the absence of formatting. I will also provide feedback on your answers in a few hours, when I can access from another domain.

A: Page-to-page navigation should not be performed using POST at all. You should be using normal <h:link> or <h:button> for this instead of <h:commandLink> or <h:commandButton>.
So instead of
<h:commandLink value="Next page" action=nextpage.xhtml?faces-redirect=true" />

you should actually be using
<h:link value="Next page" outcome="nextpage.xhtml" />

This has the major benefit that the website is now SEO friendly. Searchbots namely doesn't index forms.
Use the <h:commandLink> only if you need to submit a form with some user input. But more than often the result is just presented in the same page, if necesary conditionally rendered/included. Only on successful submits which absolutely needs to go to a different page (e.g. login/logout), you should indeed be sending a redirect. This is the so-called Post-Redirect-Get pattern.
See also

*

*How to navigate in JSF? How to make URL reflect current page (and not previous one)

*When should I use h:outputLink instead of h:commandLink?


text:
Q: What is the function/method to open a .pdf file (in axAcroPDF...), which is stored in a folder and its file path is stored in a database? Good day.
I have a Windows forms application (C#).
With the "open file dialog" I can select a .pdf file.
Selected .pdf file is copied and stored in a pre-determined destination.
File path of selected .pdf file is stored in an SQL database.
What is the function/method to open a .pdf file (in axAcroPDF...), which is stored in a folder and its file path is stored in a database?
This is what I have, code vise:
            private void txtST1Cap_DoubleClick(object sender, EventArgs e)
        {
            SavedDocumentPath1 = @"XXX\";

            using (OpenFileDialog OpenFileDialog1 = new OpenFileDialog() { ValidateNames = true, Multiselect = false, Filter = "PDF|*.pdf" })

                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    //display PDF in reader
                    OpenedDocument1 = openFileDialog1.FileName;
                    axAcroPDF1ST1.src = openFileDialog1.FileName;

                    //code for getting REF No. from opened file name
                    OpenedDocumentREF = Path.GetFileName(openFileDialog1.FileName);
                    REFfromOpenedDocument = OpenedDocumentREF.Substring(0, 12);
                    txtST1Cap.Text = REFfromOpenedDocument;

                    //destination of to-be saved document
                    SavedDocLoc1 = (SavedDocumentPath1 + Path.GetFileName(openFileDialog1.FileName));
                    lblST1CapLocation.Text = SavedDocLoc1;
                }

        }
        private void btnST1Cap_Click(object sender, EventArgs e)
        {

            openFileDialog1.FileName=SavedDocLoc1;
            axAcroPDF1ST1.src = openFileDialog1.FileName;
        }

Button Clicl btnST1Cap does not work.
Thank you.

A: I was almost correct.
So, if one wants to open a PDF document in a "default program" System.Diagnostics.Process,... is used:
          private void btnST1Cap_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(lblST1CapLocation.Text);

       }

As mentioned, this opens a default .pdf browser.
I wanted, to open it in my form (in axAcroPDF...):
        private void btnST1Cap_Click(object sender, EventArgs e)
        {
            axAcroPDF1ST1.src = lblST1CapLocation.Text;

        }

Yaaaay 4 ME!
In above cases "lblST1CapLocation.Text" is the label where file path is stored.
Direct file path can be inserted if wished:
System.Diagnostics.Process.Start(@"c:\myPdf.pdf");


text:
Q: Java - Interface Methods Just playing around with interfaces and I have a question about something which I can't really understand.
The following code doesn't run, which is the behaviour I expect as the interface method requires the method to work for any object and the implemented method has the signature changed to only allow string objects.
interface I {
    public void doSomething(Object x);
}

class MyType implements I {
    public void doSomething(String x) {
        System.out.println(x);
    }
}

However, using the following block of code, I was shocked to see that it did work. I thought it would not work as we are expecting to return an object and the implemented method will only return a string object. Why does this work and what is the difference between the two principles here of passed parameters and return types?
interface I {
    public Object doSomething(String x);
}

class MyType implements I {
    public String doSomething(String x) {
        System.out.println(x);
        return(x);
    }
}

A: public Object doSomething(String x);

has to return something. Anything, in fact, so long as it is some type of object. So if you implement
public String doSomething(String x) {stuff}

that's fine, because it does in fact return an Object. The fact that the object it will return will always be a String is no big deal.
The reason the first example doesn't work, is because accepting only strings is more limiting than accepting any object. But returning only strings is fine.
For an analogy, let's say you got a contract to paint a building, and you're gonna hire some employees to help you out. The contract requires that you hire any painter that applies, regardless of how tall they are, but doesn't specify what color paint to use. If you only hired painters over 6 ft tall (that's the input, accepting only String instead of all Object), you'd be violating the contract. But choosing to paint with only blue paint (returning only strings) is just fine, because the contract didn't specify color, only that you must paint the building.

A: It works because a String is an Object.

A: From the java language specification:

Return types may vary among methods that override each other if the return types are reference types. The notion of return-type-substitutability supports covariant returns, that is, the specialization of the return type to a subtype.

So in other words, it works as you did it, but it would not work if the return type in the interface is String, and in the implementing class is Object.

A: The principle behind this behaviour is called covariant return type. In this particular case, the overrriding type may "narrow" the originally declared parameter type.
This means that as String is subclassing Object, Object may be substituted by String.

A: This has to do with covariant return types, introduced in Java SE 5.0.
You can see more details in http://docs.oracle.com/javase/tutorial/java/javaOO/returnvalue.html

A: The reason why the first example doesn't work and the second example does, is because function prototypes are defined by the name and all parameters only, but not the return type. In the first example, there is a difference, so the compiler thinks they are two different functions.
In the second example, the implemented function does not broaden the type, but instead specializes the type (String is a specialization of Object), so it works.
Likewise you can limit the visibility of the implemented method, but not broaden it.
Furthermore, Java has generics, which are useful in this context.
Example:
interface I<T>
{
    public void doSomething(T x);
}

class MyType implements I<String>
{
    public void doSomething(String x)
    {
        System.out.println(x);
    }
}

A: method signature does not take into account the return type. (Though is is an error to declare two methods with the same signature but different return type). So:
void doSomething(Object)
void doSomething(String)

Are simply two methods and none overrides or implements the other

A: string class is inherited from object class, so only this code works.


text:
Q: How can i update the data within my app without having the user update the app in the playstore I'm taking a break from simple game development to do something totally different. I would like to create an android/ios app (something like a news app and new technology app) that i can daily update the data in it without having the user update the app every day within the playstore. My question(s) would be , what would be the easiest and less confusing way to do so. And would I be required to have a website to correlate it to and just sync data to the app.
I've researched for days and I have gotten some leads but none that really clarifies how it's done. If someone could show me a step by step or tutorials on this topic it'll be greatly appreciated!!

A: The best way to do this is to make the data available as a web service and have the app go fetch the data.


text:
Q: Can I perform a switch statement in AMPscript? new SFMC user here. I'm just wondering if there's an equivalent of a javascript (or GTL) switch statement within AMPscript or if I'm restricted to using IF ELSE statements.
For example, If I take the example of GTL's switch, I would LOVE to do something like this in AMPscript:
  %%[
    var @value, @outcome
    set @value = RequestParameter('entered-value')

    switch
      when @value =="Banana"
        set @outcome = "Yellow"
      when @value == "Apple"
        set @outcome = "Red"
      when @value == "Pear"
        set @outcome = "Green"
    end switch
  ]%%

Otherwise, is it possible to combine GTL with AMPscript to achieve this.
Thank you!

A: No, there's no case/switch syntax in AMPScript. You would need to use IF/ELSEIF/ENDIF statements to achieve the same result:
%%[
    var @value, @outcome
    set @value = RequestParameter('entered-value')

    IF @value == "Banana" THEN
        SET @outcome = "Yellow"
    ELSEIF @value == "Apple" THEN
        SET @outcome = "Red"
    ELSEIF @value == "Pear" THEN
        SET @outcome = "Green"
    ENDIF
]%%


text:
Q: How can i trigger an action manually? I'm currently working with a Learn Management System and students can earn certificates after they completed a course. This certificate gets generated and has an "action hook" hooked to it, so i can hook in to modify it. My problem is now with the debugging:
Every time i want to test my hook i have to create a user and let them complete the course. Has anyone an idea how to trigger the action manually? This would reduce the debugging time drastically.
Thank you

A: Use do_action, you can just:
do_action( 'my_action');

if your action has a callback function that need arguments say:
function my_callback( $an_array ){
  //use the array for something here
   var_dump($an_array);
}
add_action( 'my_action', 'my_callback' );

you can specify it in the do_action like this:
do_action( 'my_action', array( 'array_for_callback') );


text:
Q: how to get list of objects involving many to many relation in django I have the following models:
class Committee(models.Model):
    customer = models.ForeignKey(Customer, related_name="committees")
    name = models.CharField(max_length=255)
    members = models.ManyToManyField(member, through=CommitteeMember, related_name="committees")
    items = models.ManyToManyField(Item, related_name="committees", blank=True)

class CommitteeRole(models.Model):
    committee = models.ForeignKey('Committee')
    member = models.ForeignKey(member)
    #user is the members user/user number
    user = models.ForeignKey(User)
    role = models.IntegerField(choices=ROLES, default=0)

class Member(models.Model):
    customer = models.ForeignKey(Customer, related_name='members')
    name = models.CharField(max_length=255)

class Item(models.Model):
    customer = models.ForeignKey(Customer, related_name="items")
    name = models.CharField(max_length=255)

class Customer(models.Model):
    user = models.OneToOneField(User, related_name="customer")
    name = models.CharField(max_length=255)

I need to get all of the Items that belong to all of the commitees in which a user is connected through the CommitteeRole.
Something like this:
committee_relations = CommitteeRole.objects.filter(user=request.user)
item_list = Item.objects.filter(committees=committee_relations__committee)

How can I accomplish this?

A: Actually, you have already accomplished it (Almost):
committee_relations = CommitteeRole.objects.filter(user=request.user).values_list('committee__pk', flat=True)
item_list = Item.objects.filter(committees__in=committee_relations)

And, if you are looking for a single query, you can try this:
items = Item.objects.filter(customer__committees__committeerole__user=request.user)

Documentation here and here


text:
Q: How to use Server 2008 as a media server (including XBox clients) Is there any way to use Windows Server 2008 R2 as a media server for XBox?  I want to be able to play (legally) ripped DVDs, stored on my server, without needing to install another computer or OS.
From what I understand, this is readily available as part of Home Server; but apparently Microsoft decided that no one running the (business) server software would have a reason to do this.

A: I suggest using "tversity" http://tversity.com/ , its easy to setup, the Free addition can stream everything (except youtube etc) to your xbox with ease .
The most important feature is that tversity , if setup correctly can auto transcode your vids/music so they work flawlessly on your xbox.


text:
Q: How to hande error null body in retrofit? Im trying to post data with retrofit with jwt bearer authentication, but when i debug response code, its
error 400, and the message is body = null
This is my Intefrace class
@Headers({"accept: text/plain","Content-Type: application/json-patch+json"    })
    @POST("services/app/ProjectService/Create")
    Call<ProjectRequest> postProject(@Header("Authorization") String token,
                                     @Body ProjectRequest projectRequest
    );

This is my model class
public class ProjectRequest {
    @SerializedName("name")
    @Expose
    private String name;

    @SerializedName("description")
    @Expose
    private String description;

    @SerializedName("ownerId")
    @Expose
    private int ownerId;

    @SerializedName("startPeriod")
    @Expose
    private String startPeriod;

    @SerializedName("endPeriod")
    @Expose
    private String endPeriod;

    @SerializedName("isDraft")
    @Expose
    private boolean isDraft;

    @SerializedName("ownerName")
    @Expose
    private String ownerName;

    @SerializedName("pitId")
    @Expose
    private int pitId;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public int getOwnerId() {
        return ownerId;
    }

    public void setOwnerId(int ownerId) {
        this.ownerId = ownerId;
    }

    public String getStartPeriod() {
        return startPeriod;
    }

    public void setStartPeriod(String startPeriod) {
        this.startPeriod = startPeriod;
    }

    public String getEndPeriod() {
        return endPeriod;
    }

    public void setEndPeriod(String endPeriod) {
        this.endPeriod = endPeriod;
    }

    public boolean isDraft() {
        return isDraft;
    }

    public void setDraft(boolean draft) {
        isDraft = draft;
    }

    public String getOwnerName() {
        return ownerName;
    }

    public void setOwnerName(String ownerName) {
        this.ownerName = ownerName;
    }

    public int getPitId() {
        return pitId;
    }

    public void setPitId(int pitId) {
        this.pitId = pitId;
    }

And the main class is
    private void initApi() {
        projectApi = ApiClient.getClient().create(ProjectApi.class);
    }

    private void postProject(final boolean isOnline) {
        if (isOnline) {
            final ProjectRequest projectRequest = new ProjectRequest();
            projectRequest.setName(projectName);
            projectRequest.setDescription(description);
            projectRequest.setOwnerId(1);
            projectRequest.setStartPeriod(dateStart);
            projectRequest.setEndPeriod(dateEnd);
            projectRequest.setDraft(true);
            projectRequest.setOwnerName("yogi kun");
            projectRequest.setPitId(1);

            Call<ProjectRequest> callProject = projectApi.postProject(" Bearer eyJ0eXAiOiJKV1QiLCJub25jZSI6Il and so . . . ",
                    projectRequest);
            callProject.enqueue(new Callback<ProjectRequest>() {
                @Override
                public void onResponse(@NotNull Call<ProjectRequest> call, @NotNull Response<ProjectRequest> response) {
                    if (response.isSuccessful()) {
                        try {
                            Toast.makeText(getContext(), "Success", Toast.LENGTH_SHORT).show();
                        } catch (Exception e) {
                            String message = "";
                            if (e.getMessage() != null) {
                                message = e.getMessage();
                            }
                            Toast.makeText(getContext(), "Failed " + message, Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(getContext(), "Failed " + response, Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(@NotNull Call<ProjectRequest> call, @NotNull Throwable t) {
                    Toast.makeText(getContext(), "Failure" + t, Toast.LENGTH_SHORT).show();
                }
            });
}

And the error is
enter image description here
And
enter image description here

A: Might be an issue with how the JSON is formatted, compared to what you're expecting. Are you able to use something like Postman and try this API call to see the format it comes back? Can't tell that much but the error message shown is finding some array somewhere in the JSON


text:
Q: No match for Java Regular Expression I am running into an issue where my code is unable to find regex occurrences. Code:
String content = "This\ is\ an\ example.=This is an example\nThis\ is\ second\:=This is second"
String regex = "\"^.*(?=\\=)\"gm";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(content);
List<String> mKeys = new ArrayList<>();
while (m.find()) {
   mKeys.add(m.group());
}

mKeys turns out to be empty. I have already validated my regex here https://regex101.com/r/YResRc/3. I am expecting the list to contain two keys from the content.

A: Your content contains no " quotes, and no text gm, so why would you expect that regex to match?
FYI: Syntaxes like "foo"gm or /foo/gm are something other languages do for regex literals. Java doesn't do that.
The g flag is implied by the fact that you're using a find() loop, and m is the MULTILINE flag that affects ^ and $ and you can specify that using the (?m) pattern, or by adding a second parameter to compile(), i.e. one of these ways:
Pattern p = Pattern.compile("foo", Pattern.MULTILINE);

Pattern p = Pattern.compile("(?m)foo");

Your regex should simply be:
(?m)^.*(?==)

which means: Match everything from the beginning of a line up to the last = sign on the line.
Test
String content = "This is an example.=This is an example\nThis is second:=This is second";
String regex = "(?m)^.*(?==)";
Matcher m = Pattern.compile(regex).matcher(content);
List<String> mKeys = new ArrayList<>();
while (m.find()) {
   mKeys.add(m.group());
}
System.out.println(mKeys);

Output
[This is an example., This is second:]


text:
Q: what for need into anonymous function pass jquery object Case with bootstrap:
Example code
function( $ ){

}( window.jQuery );

A: That's done so you can guarantee $ is actually jQuery within that function. Sometimes libraries will attempt to use the same symbol and conflicts can occur (e.g. Prototype and jQuery can both use $). This is particularly important in code that is widely distributed and may be used in many environments and configurations, like bootstrap.
Using this idiom can also help prevent the introduction of unwanted variables into the global scope.

A: To avoid collision with other library jQuery gets out of global scope and here
(function($){

  // Code here

})(jQuery);

a closure is being used and jQuery has been passed in to the inner function as an argument and it has been received with the droller sign function($) so we can use $ inside our function.
Reference: jquery plugin writing and closures


text:
Q: Insert inline images in README.md Is it possible to insert an inline image (base64 encoded) via HTML or Markdown in README.md (GitHub)?
For example, this doesn't work:
<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
    AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
        9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />

A: Such a possibility exists:
![image](data:image/png;base64,<BASE64_HERE>)

But I would rather add an image to the project, similar to the README.MD itself, and only refer to the image that is part of the project.
More info: https://github.com/YourUserAccount/YourProject/blob/master/DirectoryPath/ReadMe.md


text:
Q: Express.js Cannot read property 'req' of undefined My Express.js app has been throwing Cannot read property 'req' of undefined. In essence, it listens for a GET request, grab the content query, and then reply with a table. Here's the parts that present the problem.
index.js
var panels = require('./modules/panels.js');
app.get('/panel', function (req, res) {
    var user;
    if (user = req.session.user) {
        panels.getContents(req.query.content, user.innId, res.send);
    } else {
        res.sendStatus(401);
    }
});

modules/panels.js
exports.getContents = function(panelName, innId, callback) {
    var response = "";
    switch (panelName) {
        case 'tenants':
            con.query(queryString, queryParams, function(err, rows) {
                if (err) {
                    handle(err);
                } else {
                    if (rows.length == 0) {
                        var tenants = 0;
                        var debtors = 0;
                    } else {
                        var tenants = rows[0].tenants;
                        var debtors = rows[0].length;
                    }
                    response = convertToHTMLTable(rows);
                }
                callback(response); /*THE ERROR POINTS HERE */
            });
            break;

        /* other cases here */

        default:
            response += "Invalid Request";
            callback(response);
    }
}

What did I do wrong? My guess is that I'm not suppose to pass res.send as a callback. So, how can I fix it?

A: I also experienced this error, and after chewing on the error message for a bit and staring at my code for too long, It clicked.
I (and the asker above) had code that looked like this:
  somethingAsync
  .then(res.send) // <-- storing send() divorced from parent object "res"
}

The problem is that when res.send gets called later, it is divorced from its dynamic scope--which means that calls to this inside of the send method, which would normally refer to res, now refer to global. Evidently, res.send contains a reference to this.req, given the error message.
An equivalent scenario:
res = {
    send: function() {
        console.log(this.originalMessage.req);
    },
    originalMessage: { req: "hello SO" },
};

res.send();
// # "hello SO"
const x = {};
x.send = res.send;
x.send();
// # Uncaught TypeError: Cannot read property 'req' of undefined

Or, to put it another way:
new Promise(_ => _())
.then(_ => console.log(this.msg.req));
// # Uncaught (in promise) TypeError: Cannot read property 'req' of undefined

Two solutions:
handler(req, res) {
  somethingAsync
  .then(() => res.send())
   // ^ send will be called as a method of res, preserving dynamic scope
   // that is, we're storing a function that, when called, calls
   // "res.send()", instead of storing the "send" method of "res" by itself.
}

And a theoretically more idiomatic approach is
handler(req, res) {
  somethingAsync
  .then(res.send.bind(res))
  //^ res is explicitly bound to the saved function as its dynamic scope
}

Pernicious little gotcha of dynamic scoping, that one. Seems like express should ditch the dynamic scoping there, or at least throw a better error...

A: try this in index.js
panels.getContents(req.query.content, user.innId, res);

and into panels.js
exports.getContents = function(panelName, innId, response) {
    var response = "";
    switch (panelName) {
        case 'tenants':
            con.query(queryString, queryParams, function(err, rows) {
                if (err) {
                    handle(err);
                } else {
                    if (rows.length == 0) {
                        var tenants = 0;
                        var debtors = 0;
                    } else {
                        var tenants = rows[0].tenants;
                        var debtors = rows[0].length;
                    }
                    response.send(convertToHTMLTable(rows));
                }
            });
            break;

        /* other cases here */

        default:
            error += "Invalid Request";
            response.send(error)
    }
}

A: When you passed res.send as an argument to the getContents function (panels.getContents(req.query.content, user.innId, res.send);) it is passed in a new variable and you called it callback.
So res.send is now stripped from it's original/supposed-to-be lexical context/binding
which is the res object in this case, and it appears that res.send uses the req property in the res object using this.req.
What you've done here is unintentionally changing the value of this for the function send to be the global object.
Solution
there are two ways to fix this problem

*

*panels.getContents(req.query.content, user.innId, () => res.send);
// OR

*

*panels.getContents(req.query.content, user.innId, res.send.bind(res));
in the second solution, you bind the function res.send to always treat any value of this to be the res object (bind it to the res object)


text:
Q: Permission denial when calling from Android fragment. Uses-permission IS set I got a little problem here and it is driving me crazy.
I want to call a person with the ACTION_CALL intent in Android and I do it with the following code in a fragment:
Intent callIntent = new Intent(Intent.ACTION_CALL);
       Ansat a = container.adapter.getItem(position);
       callIntent.setData(Uri.parse("tel:" + a.mobil.replace(" ", "").trim()));
       container.startActivity(callIntent);

container is the main activity context passed to the fragment, because fragments don't have its own activity.
I have set the permission in Android manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.CALL_PHONE" />

<permission
    android:name="mithfogvuc.android.svhfvuc.dk.app.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />

<uses-permission android:name="mithfogvuc.android.svhfvuc.dk.app.permission.C2D_MESSAGE" />

<uses-feature
    android:name="android.hardware.camera"
    android:required="true" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme.NoActionBar"
    tools:replace="android:icon">
    <activity
        android:name=".SplashActivity"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".MainActivity"
        android:screenOrientation="portrait" />
    <activity
        android:name=".NewsActivity"
        android:screenOrientation="portrait" />

    <receiver
        android:name="com.google.android.gms.gcm.GcmReceiver"
        android:exported="true"
        android:permission="com.google.android.c2dm.permission.SEND">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />

            <category android:name="mithfogvuc.android.svhfvuc.dk.app" />
        </intent-filter>
    </receiver>

    <service
        android:name=".GCMPushReceiverService"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        </intent-filter>
    </service>
    <service
        android:name=".GCMRegistrationIntentService"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.android.gms.idd.InstanceID" />
        </intent-filter>
    </service>

    <activity
        android:name=".FravaersregistreringActivity"
        android:screenOrientation="portrait" />
    <activity
        android:name=".FremmoederegistreringActivity"
        android:screenOrientation="portrait"/>
</application>

WHY am I getting the following error:
FATAL EXCEPTION: main
      Process: mithfogvuc.android.svhfvuc.dk, PID: 23045
      java.lang.SecurityException: Permission Denial: starting Intent {
      act=android.intent.action.CALL dat=tel:xxxxxxxx cmp=com.android.server.telecom/.components.UserCallActivity }
      from ProcessRecord{6c1ee2e 23045:mithfogvuc.android.svhfvuc.dk/u0a251} (pid=23045, uid=10251) with revoked permission android.permission.CALL_PHONE

A: From Android 6.0 (Api lvl 23) onwards the OS allows users to revoke permissions from applications. You need to look into Runtime Permissions
It looks like your app needs to poll one of the requestPermissions() methods to be granted access to the call_phone API!

A: You Can Do Like This
             if (ContextCompat.checkSelfPermission(getActivity(),
                           android.Manifest.permission.CALL_PHONE)
                            != PackageManager.PERMISSION_GRANTED) {

                        // Should we show an explanation?
                        if

           (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                               android.Manifest.permission.CALL_PHONE)) {

                            // Show an expanation to the user *asynchronously* -- don't block
                            // this thread waiting for the user's response! After the user
                            // sees the explanation, try again to request the permission.

                            Toast.makeText(getActivity(),"Its Necessary To Call",Toast.LENGTH_LONG).show();

                            ActivityCompat.requestPermissions(getActivity(),
                                    new String[]     {Manifest.permission.CALL_PHONE},
                                    MY_PERMISSIONS_REQUEST_CALL_PHONE);

                        } else {

                            // No explanation needed, we can request the     permission.

                            ActivityCompat.requestPermissions(getActivity(),
                                    new String[]   {Manifest.permission.CALL_PHONE},
                                    MY_PERMISSIONS_REQUEST_CALL_PHONE);

                            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                            // app-defined int constant. The callback method gets the
                            // result of the request.
                        }
                    }else{
                        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number));
                        startActivity(intent);

                    }


text:
Q: Does rsnapshot save binary diffs? I use rsnapshot for some years under Kubunt/Linux. But I am not sure how it (and underlying rsync) handles binary diffs: Image a large Thunderbird mailbox file or a 10 MB jpg photo and I change the EXIF data by adding a tag or a rating. What does rsnaphot do:

*

*copy the new file (10 MB) completly or

*only add the new EXIF data of new bytes?

If rsnapshot does not handle this binary diffs what tools do? rdiff-backup?

A: It will copy the new file completely in the sense it will write a complete new file, but it can detect changes and only transmit these over the network.
Writing only diffs is not possible as traditional filesystems (e.g. extX) don't support these kind of diffs and every backup set is supposed to contain all files (mostly hardlinked in).


text:
Q: Some error occurred message in payUmoney integration after generating successfully Hashkey I was trying to integrate payment gateway of payUmoney. I was following this method
Hash key was successfully generated but still i am not able to go to payment page using live credential.
I am using this Code for generating the HashKey--
<?php
/**
 * Created by PhpStorm.
 * User: Mayur Dusane
 * Date: 21-12-2017
 * Time: 11:27
 */
/**************
Below is the test card details for doing a test transaction in the testing mode.
Card No - 5123456789012346
Expiry - 05/2020
CVV - 123
****************/
/***************** NECESSARY FIELDS GOES HERE ***********************/
$key=$_POST["key"]; //posted merchant key from client
$salt="e5iIg1jwi8"; // add salt here from your credentials in payUMoney dashboard
$txnId=$_POST["txnid"]; //posted txnid from client
$amount=$_POST["amount"]; //posted amount from client
$productName=$_POST["productInfo"]; // posted product info from client
$firstName=$_POST["firstName"]; // posted firstname from and must be without space
$email=$_POST["email"]; // posted email from client
/***************** USER DEFINED VARIABLES GOES HERE ***********************/
//all varibles posted from client
$udf1=$_POST["udf1"];
$udf2=$_POST["udf2"];
$udf3=$_POST["udf3"];
$udf4=$_POST["udf4"];
$udf5=$_POST["udf5"];
/***************** DO NOT EDIT ***********************/
$payhash_str = $key . '|' . checkNull($txnId) . '|' .checkNull($amount)  . '|' .checkNull($productName)  . '|' . checkNull($firstName) . '|' . checkNull($email) . '|' . checkNull($udf1) . '|' . checkNull($udf2) . '|' . checkNull($udf3) . '|' . checkNull($udf4) . '|' . checkNull($udf5) . '||||||'. $salt;
function checkNull($value) {
            if ($value == null) {
                  return '';
            } else {
                  return $value;
            }
      }
$hash = strtolower(hash('sha512', $payhash_str));
/***************** DO NOT EDIT ***********************/
$arr['result'] = $hash;
$arr['status']=0;
$arr['errorCode']=null;
$arr['responseCode']=null;
$output=$arr;
echo json_encode($output);
?>

when i was sending this hash key generated from above code using this method:
  private class GetHashesFromServerTask extends AsyncTask<String, String, String> {
    private ProgressDialog progressDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("Please wait...");
        progressDialog.show();
    }

    @Override
    protected String doInBackground(String... postParams) {

        String merchantHash = "";
        try {
            //TODO Below url is just for testing purpose, merchant needs to replace this with their server side hash generation url
            URL url = new URL("https://payu.herokuapp.com/get_hash");

            String postParam = postParams[0];

            byte[] postParamsByte = postParam.getBytes("UTF-8");

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", String.valueOf(postParamsByte.length));
            conn.setDoOutput(true);
            conn.getOutputStream().write(postParamsByte);

            InputStream responseInputStream = conn.getInputStream();
            StringBuffer responseStringBuffer = new StringBuffer();
            byte[] byteContainer = new byte[1024];
            for (int i; (i = responseInputStream.read(byteContainer)) != -1; ) {
                responseStringBuffer.append(new String(byteContainer, 0, i));
            }

            JSONObject response = new JSONObject(responseStringBuffer.toString());

            Iterator<String> payuHashIterator = response.keys();
            while (payuHashIterator.hasNext()) {
                String key = payuHashIterator.next();
                switch (key) {
                    /**
                     * This hash is mandatory and needs to be generated from merchant's server side
                     *
                     */
                    case "payment_hash":
                        merchantHash = response.getString(key);
                        break;
                    default:
                        break;
                }
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return merchantHash;
    }

    @Override
    protected void onPostExecute(String merchantHash) {
        super.onPostExecute(merchantHash);

        progressDialog.dismiss();
        payNowButton.setEnabled(true);

        if (merchantHash.isEmpty() || merchantHash.equals("")) {
            Toast.makeText(MainActivity.this, "Could not generate hash", Toast.LENGTH_SHORT).show();
        } else {
            mPaymentParams.setMerchantHash(merchantHash);

            if (AppPreference.selectedTheme != -1) {
                PayUmoneyFlowManager.startPayUMoneyFlow(mPaymentParams, MainActivity.this, AppPreference.selectedTheme, mAppPreference.isOverrideResultScreen());
            } else {
                PayUmoneyFlowManager.startPayUMoneyFlow(mPaymentParams, MainActivity.this, R.style.AppTheme_default, mAppPreference.isOverrideResultScreen());
            }
        }
    }
}

Is the code is ok for generating hash key
Thanks in Andvance

A: Make sure your keys which you are sending to the payUmoney gateway are same as defined in PHP script hash generation
for example: key for product name is productInfo make sure of each character is same.
else the code is perfect this is only where you might have mistaken

A: Generate hash with keyword firstName and productInfo and check the udf parameter also.


text:
Q: How to import private API in iOS 10, Xcode 8?
Please check the image. Thats what I get when I try import private frameworks.

A: It looks like you are trying to build your application for simulator while your library/framework is compiled for the ARM (device) only). The simplest solution is to use device as the target and debug directly on iPhone/ iPad.
Either you can build this framework/library with simulator as target.
The third option - create universal version of framework, which includes binaries both for simulator (X86_64) and for the device (ARM).
If you have no access to source code your only way - debug on the device.


text:
Q: Rails 3 and encrypted cookies with IE9 I am using encrypted cookies to pass data to my rails app. Once these cookies get set, they are being passed just fine to my app from Chrome, Firefox, Safari (iOS and OSX version), etc.
However, the cookie isn't being passed back when I do the same on Win7/IE9.
I'm using Ruby 1.9 and Rails 3, and using the cookies.permanent.encrypted method of setting the cookie. E.g:
cookies.permanent.encrypted[:some_data] = object.some_data

Any ideas about what's going on?

A: It turns out it has to do with my P3P policy not getting passed correctly prior to the cookies being set. IE prevents cookies if that's the case, other browsers apparently don't care about that.


text:
Q: arima python - ошибка на этапе прогнозирования Нужно спрогнозировать значения временного ряда. Исходные данные в excel-формате со следующими столбцами: дата, группа1, группа2, группа3. Нужно для каждой группы предсказать значения. Я начинала с того, что отделила первую группу данные в отдельный df. Признак "дата" перевела в соответствующий формат и назначила индексом. Модель не принимает df, перевела в asarray. Модель строится, но дальше в предикте ничего не получается. Не могу найти в чем дело. Может данные не в таком виде нужно передать или признаки в предикт не правильно передаю, код ниже. Данные по которым нужно сделать прогноз после кода.
import pandas as pd
from datetime import datetime
import numpy as np

custom_datetime = lambda x: datetime.strptime(x, '%m.%Y')
df = pd.read_excel('datasetDM2.xlsx', parse_dates=['Дата'], date_parser=custom_datetime)
df = df.dropna(axis=0)
df.columns = ['date', 'группа1', 'группа2', 'группа3']

group1 = pd.Series(df['группа1'])
data = pd.Series(df['date'])
data = pd.to_datetime(data)
group1.index = data

group1_np = np.asarray(group1)

from statsmodels.tsa.arima_model import ARIMA
p1, d1, q1 = 1, 1, 1
model = ARIMA(group1_np, order=(p1,d1,q1)).fit()

from sklearn.metrics import r2_score
pred = model.predict(group1_np, '2019-08-01', '2019-10-01')
r2 = r2_score(group1_np[:-3], pred)

Ошибка выдается следующая:
KeyError: 'The start argument could not be matched to a location related to the index of the data.'

Дата
Группа1
Группа2
Группа3

01.2017
33100
38000
38000

02.2017
31000
38000
38000

03.2017
29800
38300
38300

04.2017
27900
37800
38100

05.2017
26700
36900
38400

06.2017
27400
36500
38800

07.2017
29100
37400
39000

08.2017
33000
41000
42000

09.2017
36000
44000
45900

10.2017
33500
43800
49000

11.2017
31800
42000
49200

12.2017
33400
41300
48000

1,2018
35200
42000
48200

2,2018
33000
43000
48500

3,2018
34100
43200
49300

4,2018
36300
43500
51400

5,2018
38100
43800
51400

6,2018
36600
43700
51000

7,2018
37200
43200
50000

8,2018
41000
42000
50000

9,2018
39200
42000
50200

10,2018
37400
41700
49000

11,2018
36200
41400
46100

12,2018
36000
40500
45000

1,2019
34300
40000
44400

2,2019
36100
39800
43500

3,2019
40000
40000
44000

4,2019
39000
40100
43800

5,2019
39100
40000
43600

6,2019
40200
40300
43900

7,2019
39500
41800
44000

8,2019
37600
43000
45000

9,2019
36100
42100
43600

10,2019
33000
39500
41000

11,2019

12,2019


text:
Q: How to configure Application Insights sampling on Net Core HostBuilder? I'm building .Net Core background service, using ApplicationInsights.WorkerService nuget package. The documentation regarding sampling configuration says to refer to this:
https://learn.microsoft.com/en-us/azure/azure-monitor/app/sampling#configure-sampling-settings
And it shows this:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, TelemetryConfiguration configuration)
{
  var builder = configuration.DefaultTelemetrySink.TelemetryProcessorChainBuilder;
  // For older versions of the Application Insights SDK, use the following line instead:
  // var builder = configuration.TelemetryProcessorChainBuilder;

  // Using adaptive sampling
  builder.UseAdaptiveSampling(maxTelemetryItemsPerSecond:5);

  // Alternately, the following configures adaptive sampling with 5 items per second, and also excludes DependencyTelemetry from being subject to sampling.
  // builder.UseAdaptiveSampling(maxTelemetryItemsPerSecond:5, excludedTypes: "Dependency");

  // If you have other telemetry processors:
  builder.Use((next) => new AnotherProcessor(next));

  builder.Build();

  // ...
}

Now on HostBuilder I don't see any extension methods that would give me the TelemetryConfiguration, source code of the nuget doesn't have it either:
https://github.com/microsoft/ApplicationInsights-aspnetcore/blob/develop/NETCORE/src/Microsoft.ApplicationInsights.WorkerService/ApplicationInsightsExtensions.cs
So how do I get either TelemetryConfiguration or TelemetryProcessorChainBuilder on a HostBuilder? At the moment it looks like this:
Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<Worker>();
                    services.AddApplicationInsightsTelemetryWorkerService();
                });

A: You should use it as below:
Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<Worker>();

                    services.Configure<TelemetryConfiguration>((config)=>
                    {
                        var builder = config.DefaultTelemetrySink.TelemetryProcessorChainBuilder;

                        builder.UseAdaptiveSampling(maxTelemetryItemsPerSecond: 5);
                        builder.Build();
                    }
                    );

                   // Your other code
                });


text: Q: Book where people are sent to a distant destination and babies are awakened out of sleep when nearby, problems ensue I read this book MANY years ago. A space mission is sent to a destination many light years away. A set of babies and people to tend/raise them are frozen and awakened when near the destination. The babies are raised, and the usual problems of child-rearing arise to the point that the mission cannot continue. Then the adults are told that this was a practice session, the real babies are now ready to be raised after this practice session.


text:
Q: Synchronisation of Foreign Key in Mobile Push and Contact Key in Contact Builder I am implementing Marketing Cloud MobilePush for one of my clients and I need some clarification regarding the data model of Mobile Push system tables and their relation with the populations.

*

*The MDM will be Service Cloud that will push Contacts to Marketing
Cloud as a Population (ContactKey = Salesforce ID).

*The mobile app
uses a ClientID (Foreign key) to identify the customer. The J4Apps
SDK will only have the CliendID and will use it in the ContactKey
registration call (Documentation
:http://salesforce-marketingcloud.github.io/JB4A-SDK-Android/features/subscriber-key.html).

*Service Cloud will also have the ClientID in the Contact record so
    It can be retrieved in Marketing Cloud via the Data Stream.

*Marketing Coud will have a ClientID/SalesforceID reference table as an attribute set linked to the population in Contact Builder.

My concern is that the ContactKey in Marketing Cloud is the Salesforce ID and in the mobile Apps is the ClientID.
Is mobile push able to match ClientID with ContactKey?
Or should I call Service Cloud APIs within the mobile app to retrieve the Salesforce ID before registration ?

A: MobilePush SDK needs to set the correct ContactKey in order to match the Device with the Contact in Contact Builder.
Thus, in the context of this question, the mobile App has to know the Salesforce ID of the Contact prior to setting the ContactKey during the device registration.
In my use case, the mobile App performs an API call to Salesforce Core APIs to retrieve the Salesforce ID from the Client Id (which is known in the app context).


text:
Q: PHP - Looping through JSON Array without "string"? So I have question. I have an JSON Array
Here's the JSON: http://pastebin.com/raw/XEzAEdfg
How could I loop it through? Here's what I've tried at the moment:
$output = json_decode($result2);
foreach($output as $SuiFag){
    echo $SuiFag->aaData[6];
}
?>

A: I suppose you data json data should be an object attribute named "aaData" of type array so only a [ character should be there, and { and } should define the start and the end of the json object(traling comma is not allowed):
$result2='{
   "aaData": [
         "Knife",
         "/id/1676/",
         "★ Karambit | Stained (Field-Tested)<\/a>",
         "234.87",
         "224.85",
         "5907380460<\/a>",
         "0.2123493403<\/a>",
         "Inspect<\/a>"
      ]
}';

So you can use direct object attribute access (you need foreach to scan an array but not the attribute of an object):
$output = json_decode($result2);
echo $output->aaData[6];

OR
if your json structure is something like this:
allowed):
$result2='{
    ...
   "aaData": [
        [
         "Knife",
         "/id/1676/",
         "★ Karambit | Stained (Field-Tested)<\/a>",
         "234.87",
         "224.85",
         "5907380460<\/a>",
         "0.2123493403<\/a>",
         "Inspect<\/a>"
        ],
        ...
    ]
}';

then your code should be:
$output = json_decode($result2);
foreach($output->aaData as $SuiFag){
    echo $SuiFag[6];
}

TO print every 6th element of every element of the array "aaData";

A: You need to loop through the aaData array then output the 6th line. The below will output the 6th line of every aaData array
$output = json_decode($result2);
foreach($output as $SuiFag) {
    for($i=0; $i<count($SuiFag);$i++) {
        echo $SuiFag[$i][6] . '
';
    }
}
?>

Of course you can add a third loop if you want to echo each item of the array out
$output = json_decode($result2);
foreach($output as $SuiFag) {
    for($i=0; $i<count($SuiFag);$i++) {
        for($x=0; $x<count($SuiFag[$i]);$x++) {
            echo $SuiFag[$i][$x] . '
';
        }
    }
}
?>

Since you have only the aaData in your json you could shorten this down to but above allows for further items in your json array:
foreach($output->aaData as $SuiFag) {
    for($i=0; $i<count($SuiFag);$i++) {
        echo $SuiFag[$i] . '
';
    }
}

Credits to lamp76


text:
Q: Jackson JSON Not Formatting Correctly I have data that looks like this:
{
    "status": "success",
    "data": {
        "irrelevant": {
            "serialNumber": "XYZ",
            "version": "4.6"
        },
        "data": {
            "lib": {
                "files": [
                    "data1",
                    "data2",
                    "data3",
                    "data4"
                ],
                "another file": [
                    "file.jar",
                    "lib.jar"
                ],
                "dirs": []
            },
            "jvm": {
                "maxHeap": 10,
                "maxPermSize": "12"
            },
            "serverId": "134",
            "version": "2.3"
        }
    }
}

Here is the function I'm using to prettify the JSON data:
public static String stringify(Object o, int space) {
    ObjectMapper mapper = new ObjectMapper();
    try {
        return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(o);
    } catch (Exception e) {
        return null;
    }
}

I am using the Jackson JSON Processor to format JSON data into a String.
For some reason the JSON format is not in the format that I need. When passing the data to that function, the format I'm getting is this:
{
    "status": "success",
    "data": {
        "irrelevant": {
            "serialNumber": "XYZ",
            "version": "4.6"
        },
        "another data": {
            "lib": {
                "files": [ "data1", "data2", "data3", "data4" ],
                "another file": [ "file.jar", "lib.jar" ],
                "dirs": []
            },
            "jvm": {
                "maxHeap": 10,
                "maxPermSize": "12"
            },
            "serverId": "134",
            "version": "2.3"
        }
    }
}

As you can see under the "another data" object, the arrays are displayed as one whole line instead of a new line for each item in the array. I'm not sure how to modify my stringify function for it to format the JSON data correctly.

A: You should check how DefaultPrettyPrinter looks like. Really interesting in this class is the _arrayIndenter property. The default value for this property is FixedSpaceIndenter class. You should change it with Lf2SpacesIndenter class.
Your method should looks like this:
public static String stringify(Object o) {
    try {
        ObjectMapper mapper = new ObjectMapper();
        DefaultPrettyPrinter printer = new DefaultPrettyPrinter();
        printer.indentArraysWith(new Lf2SpacesIndenter());
        return mapper.writer(printer).writeValueAsString(o);
    } catch (Exception e) {
        return null;
    }
}

A: I don't have enough reputation to add the comment, but referring to the above answer Lf2SpacesIndenter is removed from the newer Jackson's API (2.7 and up), so instead use:
printer.indentArraysWith(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE);

Source of the solution


text:
Q: Why isn't a simple sieve proof of Bertrand's Postulate? I wish to show a prime in $(n,2n)$. I make a list of numbers $n+1$ through $2n-1$.
I check $n+1$ for prime factors $p_i<\sqrt{2n}$. It has a factor of $p_1$. I cross off numbers $\equiv n+1 \pmod {p_1}$.
I check $n+2$, it has $p_2$, I cross off remaining numbers $\equiv n+2 \pmod{ p_2}$. And so on, you know how sieves work.
There are only $\pi(\sqrt{2n})$ factors I have to rule out before I get a prime. Even in the naive absolute worst-case totally impossible scenario of running into a Jacobsthal $h(n)$ run of small factors and using the conservative upper bound for that, I think that still comes out to a prime popping out before $2n$, although I'll admit I haven't checked carefully, because I would hope you could rule that out anyway.
I know this is not a proof, but it seems like it could be without much work if the principle is sound; that said, the principle seems so obvious that I'm sure I'm missing something.
What am I missing?

A: What you are missing, is induction on $n$. Just because it works for one value of $n$, does not prove it for all other values of $n$. Proving any finite number of cases, doesn't always prove things for all $n$. That's why cover sets, and induction are so important. $n+1$ induction is a cover set for the natural numbers starting with a base case of 0 or 1. Any complete residue system for a given modulus form a trivial covering set, of the integers .  All primes except the prime factors of a modulus, are covered by the equivalence classes forming the modular multiplicative group.


text:
Q: i'm new to hibernate,my code is about the hibernate table per hierarchy using annotation.. i'm getting the following error 0 [main] INFO org.hibernate.cfg.annotations.Version - Hibernate Annotations 3.4.0.GA
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
109 [main] INFO org.hibernate.annotations.common.Version - Hibernate Commons Annotations 3.1.0.GA
1920 [main] INFO org.hibernate.cfg.search.HibernateSearchEventListenerRegister - Unable to find             org.hibernate.search.event.FullTextIndexEventListener on the classpath. Hibernate Search is not     enabled.
2077 [main] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class:   com.rtr.annotation.Employee2Ann
2139 [main] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity com.rtr.annotation.Employee2Ann on table empAnn10
2202 [main] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.rtr.annotation.Regular_Employee2Ann
2217 [main] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.rtr.annotation.Contract_Employee2Ann
Exception in thread "main" org.hibernate.exception.GenericJDBCException: Cannot open connection
    at        org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
   at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:420)
at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:144)
at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:119)
at org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:57)
at org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1326)
at com.rtrsi.annotation.StoreData4Ann.main(StoreData4Ann.java:19)
Caused by: java.sql.SQLException: Access denied for user ''@'localhost' (using password: YES)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3515)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3447)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:911)
at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3953)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1276)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2048)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:723)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:302)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:282)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:417)
... 5 more

and  my cfg.xml is
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hbm2ddl.auto">create</property>
<property name="connection.url">jdbc:mysql://localhost:3306/rea</property>
<property name="connectiuon.username">root</property>
<property name="connection.password"></property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.show_sql">true</property>
<mapping class="com.rtri.annotation.Employee2Ann"/>
<mapping class="com.rtri.annotation.Regular_Employee2Ann"/>
<mapping class="com.rtri.annotation.Contract_Employee2Ann"/>
</session-factory>
</hibernate-configuration>

main class is
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;

public class StoreData4Ann {
    public static void main(String[] args) {
        //1.
        Configuration config=new AnnotationConfiguration();
        config.configure("employee2Ann.cfg.xml");
        //2.
        SessionFactory factory=config.buildSessionFactory();
        //3
        Session session=factory.openSession();
        //4.
        Transaction t=session.beginTransaction();

        Employee2Ann e2=new Employee2Ann();
        e2.setName("rahul");

        Regular_Employee2Ann r2=new Regular_Employee2Ann();
        r2.setSalary(50000);
        r2.setName("arun");

        Contract_Employee2Ann c2=new Contract_Employee2Ann();
        c2.setName("ravi");
        c2.setContract_duration("5 Months");
        c2.setPay_per_hour(150);

        session.saveOrUpdate(e2);
        session.saveOrUpdate(r2);
        session.saveOrUpdate(c2);

        t.commit();
        session.close();
        System.out.println("succefully saved");

    }
}

and my persitant class
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;

@Entity
@Table(name="empAnn10")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="classname", discriminatorType=DiscriminatorType.STRING)
@DiscriminatorValue(value ="emp2ann")
public class Employee2Ann {
    @Id
    @Column(name="id")
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    @Column(name="name")
    private String name;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

}

another persistant
@Entity
@DiscriminatorValue(value="regemp2ann")
public class Regular_Employee2Ann extends Employee2Ann {
    @Column(name="bonus")

    private int bonus;
    @Column(name="salary")
    private float salary;
    public int getBonus() {
    return bonus;
    }
    public void setBonus(int bonus) {
    this.bonus = bonus;
    }
    public float getSalary() {
    return salary;
    }
    public void setSalary(float salary) {
    this.salary = salary;
    }
}

another persistant class
@Entity
@DiscriminatorValue(value="contemp2ann")
public class Contract_Employee2Ann extends Employee2Ann{

    @Column(name="pay_per_hour")
    private float pay_per_hour;
    @Column(name="contract_duration")
    private String contract_duration;
    public float getPay_per_hour() {
        return pay_per_hour;
    }
    public void setPay_per_hour(float pay_per_hour) {
        this.pay_per_hour = pay_per_hour;
    }
    public String getContract_duration() {
        return contract_duration;
    }
    public void setContract_duration(String contract_duration) {
        this.contract_duration = contract_duration;
    }
}

i've used hibernate validator, common annotation,annotation, hibernate3,log4j,asm,dom4j,cglib,common logging,common colllection,ejb3 persistance,slf4j,mysql connector jars

A: Type-O in configuration
<property name="connectiuon.username">root</property>

change to
<property name="connection.username">root</property>

and try again


text:
Q: Add days & dispaly output in string I need to add days to given string date and display calculated date in string
This is what I have tried, but I could not make it work.
$date = date_create('1-Feb-2012');
$newDate = date_modify($date, '+2 day');
echo 'Your date is' . $newDate . '.';

This gives an error

Object of class DateTime could not be converted to string

A: Use DateTime::format function.
usage:
echo 'Your date is' . $newdate->format('Y-m-d H:i:s') . '.';

or
echo 'Your date is' . date_format($newdate, 'Y-m-d H:i:s') . '.';

A: You need to tell the DateTime object how to format its output using DateTime::format. So, for example:
$date = new DateTime('1-Feb-2012');
$date->modify('+2 day');
echo 'Your date is' . $newDate->format('Y-m-d H:i:s') . '.';

Also note that modify directly modifies the DateTime - it doesn't just return a new one, as the documentation might lead you to believe - so I've removed the second variable. I've taken the liberty of changing the objects to the object-oriented form as well, which you should be using :)
Here's a working demo.


text:
Q: Flutter websocket onOpen? I'm trying to create a websocket connection in Flutter.
I followed this tutorial and this
My query is that how can we know once the websocket connection is established? Like there is onOpen event in Javascript.
My code in flutter is:
void main() async {
  final channel = IOWebSocketChannel.connect('wss://my.server.org');

  channel.stream.listen(
    (dynamic message) {
      debugPrint('message $message');
    },
    onDone: () {
      debugPrint('ws channel closed');
    },
    onError: (error) {
      debugPrint('ws error $error');
    },
  );
}

A: This is what I used in one project to connect to AWS AppSync service. The communication is implemented over websockets.
What you do is parse the messages you receive through web socket. Messages will carry the data, but also there are messages to tell you that the connection was established, keep alive message etc.
I don't remember if the messages below are AppSync specific, or are applicable to any websocket server - but it should at least give you an idea how this could work.
var channel=IOWebSocketChannel.connect(url, protocols: ['graphql-ws']);

channel.sink.add(json.encode({"type": "connection_init"}));

channel.stream.listen((event) {
      var e = json.decode(event);

      switch (e['type']) {
        case 'connection_ack':
          wsTimeoutInterval = e['payload']['connectionTimeoutMs'];

          var register = {
            'id': uniqueKey,
            'payload': {
              'data': json.encode(query),
              'extensions': {'authorization': header}
            },
            'type': 'start'
          };
          var payload = json.encode(register);
          channel.sink.add(payload);
          break;
        case 'data':
           // calling a callback function Function(Map<String, dynamic>) listener
          listener(e);
          break;
        case 'ka':
          print('Keep alive message received!!!');
          break;
        case 'start_ack':
          print('Ws Channel: Subscription started');
          break;
        default:
          print('Unimplemented event received $event');
      }
    }, onError: (error, StackTrace stackTrace) {
      // error handling
      print('Ws Channel: $error');
    }, onDone: () {
      // communication has been closed
      channel.sink.close();
      print('Ws Channel: Done!');
    });


text:
Q: Why is the determinant of this matrix unstable? A colleague has encountered an instability when computing the determinant of a matrix.
For this matrix :
$$\begin{bmatrix}
123.585 &-1.33458 &78.9871 &43.2638\\
-1.33458 &190.581 &88.7218 &100.524\\
78.9871 &88.7218 &167.465 &0.244369\\
43.2638 &100.524 &0.244369 &143.544
\end{bmatrix}$$
the determinant is: $2077.34$
While, for this matrix (rounding of the digits)
$$\begin{bmatrix}
123.6 &-1.335 &78.99 &43.26\\
-1.335 &190.6 &88.72 &100.5\\
78.99 &88.72 &167.5 &0.2444\\
43.26 &100.5 &0.2444 &143.5
\end{bmatrix}$$
This gives the determinant : $138949$
Why/Where is the instability coming from ?
Bonus : is there a way to have a stability ?

A: Let us call $M_1$ and $M_2$ the two matrices.
They have the resp. spectra :
$$ S_1=\{0.000294498,
   121.945486280,
   177.683446086,
   325.545773134\}$$
$$S_2= \{0.019697264,
   121.950561034,
   177.688725537,
   325.541016164\}$$
(I am fully conscious that there are too many decimals, considering the roundoff or entries).
Remark : $M_1$ and $M_2$ are symmetric definite positive (all their eigenvalues are $>0$) : a category of matrices that can not be ranked among the worst a priori.
There are different levels of explanations. I will only consider two.
Here is a first one : the "condition numbers" (ratios $\sigma_1/\sigma_4$ of singular values) of these matrices are very high, especially  for $M_1$ : $1.1 \times 10^6$ which is huge, indicating that intrinsically $M_1$ is very unstable.
Having a closer look at the spectra, we see that, set apart the first pair of eigenvalues, the rsp. ratios of the other ones are very close to $1$.
Therefore, it will not come as a surprize (the determinant of a matrix being the product of its eigenvalues) that the ratio of the first two eigenvalues,  $\approx 66.8840$ is very close to the ratio of determinants which is $\approx 66.8879$.
This shows that this issue of sensibility of determinants can be transfered into an issue of sensibility of the smallest eigenvalue.
I will only provide an insight about the situation by using the pencil of matrices
$$A_x=M_2+x(M_1-M_2)$$
and the attached following functions :
$f(x):=\det(A_x)$ and $g(x) :=  $ smallest eigenvalue of $A_x$,
for $x=0$ (case of matrix $M_2$) to $x=1$ (case of matrix $M_1$).
What do we see ? That when $x=1$, we are very close to a "catastrophic" situation where, at approximately $x \approx 1.0152$, i.e., at a very small distance of $M_1$, we have a zero determinant... As we have said, this trend can be as well rendered by function $g$ (that has been represented on the same graphic, but with ordinate axis unit multiplied by $10^7$...

Fig. 1 : Graphical representation of functions $f$ (blue) and $g$ ($\times 10^7$) (red) displaying a very similar behavior.
How to go further ? There are many sophisticated ways to analyse  sensitivity of eigenvalues. I will not enter into this highly specialized domain, using very specific tools like pseudospectra, etc.

A: Let $A$ be the original matrix and $B$ be the rounded one. Both are symmetric and therefore have very stable eigen-elements. For example, if $Av=\lambda v$, where $v$ is unitary, then $\Delta \lambda=v^T(\Delta A) v$.
In particular $||\Delta \lambda||\leq ||\Delta A||_2=||B-A||_2\approx 0.052$.
Yet, $\det(A)$ is stable only when $A$ has no eigenvalues close to $0$. Unfortunately, $A$ admits the couple of eigen-element $\lambda\approx 0.00029,v\approx 1/2[-1,-1,1,1]^T$. Then
$\Delta\lambda\approx 0.0194$ and $\dfrac{\Delta(\det(A))}{\det(A)}\approx\dfrac{\Delta\lambda}{\lambda}\approx 66.9$.
The key of the problem is the bad condition number of $A$. More precisely, the true key is the formula
$\det(B)-\det(A)\approx tr(adj(A)(B-A))\approx 136883$. (cf., above, the @Ian comment), where $adj(A)$ is the adjugate of $A$.
This large value does not depend on the choice of $B$; indeed $B-A$ is quasi random and has (with probability $1$) a non zero component on the eigenvector associated to the maximum eigenvalue of the operator $X\mapsto adj(A)X$; but it depends on the fact that $||adj(A)||_2\approx 7.10^6$ is large (compare with $||A||_2\approx 326$).
What the OP didn't tell us is that

which explains many things.

A: If you take the product along the main diagonal in the second matrix, you get
$$ 123.6 \times 190.6 \times 167.5 \times 143.5 \approx 5.662 \times 10^8. $$
This is roughly $4000$ times as large as the determinant you found.
The product of the main diagonal of the first matrix is also roughly that large.
The only reason the determinants in either case are as small as they are is because the product along the main diagonal, and other positive products that go into the determinant was nearly canceled (to within one part in $4000$ or better) by negative products.
If you do this calculation with numbers that are not precise to much better than $1$ part in $4000$, for example by rounding them as in the second matrix, you get catastrophic cancellation.