text:
Q: Set the maximum and current speed of a car in Phaser I am making a top-down racing game using the Phaser framework which uses JS. I am having some trouble getting the car to slow down, at the moment it just stops when no button is pressed. I want it to slow down to stopped. Here is my code so far:
    create: function () {
    //run in canvas mode
    this.game.renderer.clearBeforeRender - false;
    this.game.renderer.roundPixels = true;

    //Add arcade physics
    this.game.physics.startSystem(Phaser.Physics.ARCADE);

    //Add background sprites
    this.game.add.sprite(0, 0, 'background');
    this.game.add.sprite(0, 0, 'track');

    //Add car sprite
    car = this.game.add.sprite(800, 135, 'car-concept');

    //Car physics settings
    this.game.physics.enable(car, Phaser.Physics.ARCADE);

    car.body.drag.set(100);
    car.body.maxVelocity.set(200);
    car.body.maxAngular = 500;
    car.body.angularDrag = 500;
    car.body.collideWorldBounds = true;

    //Game input
    cursors = this.game.input.keyboard.createCursorKeys();
    this.game.input.keyboard.addKeyCapture([ Phaser.Keyboard.SPACEBAR]);

    //pivot point
    car.pivot.x = car.width * .3;
    car.pivot.y = car.height * .5;
    car.anchor.setTo(0.3, 0.5);

    //scale the car
    car.scale.setTo(0.3, 0.3);
},

update: function () {

    car.body.velocity.x = 0;
    car.body.velocity.y = 0;
    car.body.angularVelocity = 0;

    if(cursors.left.isDown)
    {
      car.body.angularVelocity = -200;
    }
    else if(cursors.right.isDown)
    {
      car.body.angularVelocity = 200;
    }
    if(cursors.up.isDown)
    {
      this.game.physics.arcade.velocityFromAngle(car.angle, -200, car.body.velocity)
      if(this.currentSpeed < this.maxSpeed)
      {
        this.currentSpeed += 10;
      }
    }
    else
    {
      if(this.currentSpeed > 0)
      {
        this.currentSpeed -= 10;
      }
    }
    if(cursors.down.isDown)
    {
      this.game.physics.arcade.velocityFromAngle(car.angle, 200, car.body.velocity)
      if(this.currentSpeed > 0)
      {
        this.currentSpeed -= 30;
      }
    }

},

speed: function()
{
  this.maxSpeed = 100;
  this.currentSpeed = 0;
},

I have looked a few questions on here about the same problem and this is how I got to the point where I am now. I have set the maxSpeed and currentSpeed but for some reason it won't allow me to actually use it. The console in the browser does not give me any errors, so if anyone can guide me on this, that would be great!
Thanks.

A: The reason it stops dead is because you're moving it with velocity, not acceleration - and are setting velocity to zero in your update loop (this effectively says "stop, now!").
Remove those lines and in your call to velocityFromAngle you should feed that into body.acceleration instead of body.velocity.
Here is an update loop you can use, although you'll need to mix in your currentSpeed settings and such like:
function update() {

    if (cursors.up.isDown)
    {
        game.physics.arcade.accelerationFromRotation(sprite.rotation, 200, sprite.body.acceleration);
    }
    else
    {
        sprite.body.acceleration.set(0);
    }

    if (cursors.left.isDown)
    {
        sprite.body.angularVelocity = -300;
    }
    else if (cursors.right.isDown)
    {
        sprite.body.angularVelocity = 300;
    }
    else
    {
        sprite.body.angularVelocity = 0;
    }

}

A: you never used currentSpeed. You set your speed to -200 and 200 in velocityFromAngle.


text:
Q: Fabric.js adding simple path not working I'm trying to create a simple path object using Farbic.js. When the path is added to canvas, it does not appear to be positioned correctly. Here is my code:
HTML
<canvas id="c" height="300" width="300"></canvas>

JS
var canvas = new fabric.Canvas('c');
canvas.backgroundColor = '#f5f5f5';
var line = new fabric.Path('M 0 0 L 100 100',{
    stroke: 'black',
    fill: ''
});
canvas.add(line);

According to the data I'm passing in, the path should start at point 0,0 and draw a line to point 100, 100. However, my line is actually being placed at point 50,50, as you can see by the alert.
Why isn't the path starting at point 0,0?
Here's a fiddle: http://jsfiddle.net/flyingL123/h14th5pf/3/

A: You can specify the position properties of your path explicitly.
line.set({top: 0, left: 0});

Fabric.JS seems to include some sort of computed padding by default, based on the line length and canvas size. Try adjusting your canvas dimensions and line length and you'll see the top and left values update automatically.
Edit: It appears Fabric.JS may use the center of the canvas to calculate the X,Y positions for canvases. It may use a similar scheme for path origin points. See this related StackOverflow question:
Canvas coordinates in Fabric.js have offset
It seems to be part of how the library calculates positions automatically. Per the comments of the linked question, you can fix this with:
fabric.Object.prototype.originX = true;
fabric.Object.prototype.originY = true;

And you wont have to adjust the originX or originY properties on each path object.

redpajama_set_name: RedPajamaStackExchange


text:
Q: jQuery plugin returning undefined I have a plugin to translate dom nodes. This it what it does:
$.fn.jqTranslate = function (pkg, options) {
    var self = this;
    Translate.initialize(pkg, options).done(function () {
        return self.each(Translate.translate);
    });
};
translate: function () {
    var elem = $(this),
        key = elem.data('translate');
    if (Translate.translatable) {
        if (Translate.translatedStrings[key]) {
            if (Translate.translatedStrings[key].length === undefined) {
                // The key have nested keys
                Translate.translateElement(elem, Translate.translatedStrings[key].text);
                delete Translate.translatedStrings[key].text;
                elem.attr(Translate.translatedStrings[key]);
            }
            else Translate.translateElement(elem, Translate.translatedStrings[key]);
        }
    }
    if (typeof Translate.options.onComplete === 'function') Translate.options.onComplete.apply(this, arguments);
    return elem;
}

If you see, it's returning self so the plugin could be theoretically chained like this:
$('p').jqTranslate('global').addClass('translated')

Should work but it says:

Uncaught TypeError: Cannot call method 'addClass' of undefined

What am I doing wrong?
You can check the full code in GitHub.

A: You are implicitly returning undefined from your plugin. When you have no return statement, a function returns undefined.
$.fn.jqTranslate = function (pkg, options) {
    var self = this;
    Translate.initialize(pkg, options).done(function () {
        return self.each(Translate.translate);
    });
    return this; //add return statement
};


text:
Q: Is it considered grey/black hat SEO if I modify the sizing of the headings? The situation is the following:
The page's title is H3, the article's title is H2 and some keyword/important sentence is H1 in the article. They have custom css classes on them, so the H3 looks like a H1, and the H1 looks like normal text. Is this considered grey/black hat SEO, or Google doesn't care about their rendered size?

A: AS far as I know Google is not interested in how it looks like. But the heading structure is more important.
So the H1 is the most important tag with your relevant SEO text. After that the H2 tag with related information to the H1 tag etc.
An good article you can read is this page:
https://yoast.com/headings-use/
And ofcours Google own Userguide is an must read:
http://static.googleusercontent.com/media/www.google.com/en//webmasters/docs/search-engine-optimization-starter-guide.pdf
Good luck!


text:
Q: Date validation function scala I have RDD[(String, String)]. String contains datetimestamp in format ("yyyy-MM-dd HH:mm:ss"). I am converting it in epoch time using the below function where dateFormats is SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
def epochTime (stringOfTime: String): Long = dateFormats.parse(stringOfTime).getTime

I want to modify the function so as to delete the row if it contains null/empty/not-right formatted date and how to apply it to the RDD[(String, String)] so the string value get converted to epoch time as below
Input
(2020-10-10 05:17:12,2015-04-10 09:18:20)
(2020-10-12 06:15:58,2015-04-10 09:17:42)
(2020-10-11 07:16:40,2015-04-10 09:17:49)
Output
(1602303432,1428653900)
(1602479758,1428653862)
(1602397000,1428653869)

A: You can use a filter to determine which value is not None. To do this you need to change the epochTime method so that it can return Option[Long],def epochTime (stringOfTime: String): Option[Long] inside your method make a check to see if the string is null with the .nonEmpty method, then you can use Try to see if you can parse the string with dateFormats.
After these changes, you must filter the RDD to remove None, and then unwrap each value from Option to Long
The code itself:
    val sparkSession = SparkSession.builder()
      .appName("Data Validation")
      .master("local[*]")
      .getOrCreate()

    val data = Seq(("2020-10-10 05:17:12","2015-04-10 09:18:20"), ("2020-10-12 06:15:58","2015-04-10 09:17:42"),
      ("2020-10-11 07:16:40","2015-04-10 09:17:49"), ("t", "t"))

    val rdd:RDD[(String,String)] = sparkSession.sparkContext.parallelize(data)

    def epochTime (stringOfTime: String): Option[Long] = {
      val dateFormats = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
      if (stringOfTime.nonEmpty) {
        val parseDate = Try(dateFormats.parse(stringOfTime).getTime)
        parseDate match {
          case Success(value) => Some(value)
          case _ => None
        }
      } else {
        None
      }
    }
    rdd.map(pair => (epochTime(pair._1),epochTime(pair._2)))
      .filter(pair => pair._1.isDefined && pair._2.isDefined)
      .map(pair => (pair._1.get, pair._2.get))
      .foreach(pair => println(s"Results: (${pair._1}, ${pair._2})"))}


text:
Q: $q$-analogs confusion in some steps I am understanding the proof of the general version of the Jacobi triple product, that is $$\prod_{k=1}^{\infty}(1+xq^{2k-2})=\sum_{k=0}^{\infty}\frac{q^{k(k-1)}}{(q^2)_k}x^k$$
In the proof to this identity, there is this one step where it goes;
$$\sum_{l=0}^{\infty}(-1)^l \frac{q^{l^2+l+2kl}}{(q^2)_l}-\sum_{k=-\infty}^{\infty}q^{k^2}x^k\sum_{l=0}^{\infty}(-1)^l \frac{q^{l^2+l+2kl}}{(q^2)_l}=\sum_{l=0}^{\infty}\sum_{k=-\infty}^{\infty}\frac{(-q)^lq^{(k+l)^2}}{(q^2)_l}x^k$$
Can anyone help me with the understanding of this part, if I just understand this part, then I am nearly done with understanding the whole proof.

A: I get
$$\sum_{l=0}^\infty\sum_{k=-\infty}^\infty\frac{(-q)^lq^{(k+l)^2}}{(q^2)_l}x^k
=\sum_{k=-\infty}^\infty
\sum_{l=0}^\infty(-1)^l \frac{q^{k^2+2kl+l^2+l}}{(q^2)_l}x^k
=\sum_{k=-\infty}^\infty q^{k^2}x^k
\sum_{l=0}^\infty(-1)^l \frac{q^{l^2+l+2kl}}{(q^2)_l}$$
which isn't what you have on the left, but maybe should be?


text:
Q: opencv SolvePnPRansac error I'm following this tutorial about opencv and camera calibration.
When I'm executing the below code I get the error message:
MacBook-Pro:src marvineffing$ python3 pose\ estimation.py
OpenCV Error: Assertion failed (d == 2 && (sizes[0] == 1 || sizes[1] == 1 || sizes[0]*sizes[1] == 0)) in create, file /tmp/opencv320151207-39796-10do3cp/opencv-3.0.0/modules/core/src/matrix.cpp, line 2294
Traceback (most recent call last):
  File "pose estimation.py", line 31, in <module>
    rvecs, tvecs, inliers = cv2.solvePnPRansac(objp, corners2, mtx, dist)
cv2.error: /tmp/opencv320151207-39796-10do3cp/opencv-3.0.0/modules/core/src/matrix.cpp:2294: error: (-215) d == 2 && (sizes[0] == 1 || sizes[1] == 1 || sizes[0]*sizes[1] == 0) in function create

Code:
import cv2
import numpy as np
import glob

def draw(img, corners, imgpts):
    """draws line on xyz axis for a corner"""
    corner = tuple(corners[0].ravel())
    img = cv2.line(img, corner, tuple(imgpts[0].ravel(), (255, 0, 0)))
    img = cv2.line(img, corner, tuple(imgpts[1].ravel(), (0, 255, 0)))
    img = cv2.line(img, corner, tuple(imgpts[2].ravel(), (0, 0, 255)))
    return img

with np.load('matrix.npz') as X:
    mtx, dist, _, _ = [X[i] for i in ('mtx', 'dist', 'rvecs', 'tvecs')]

criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
objp = np.zeros((6*7, 3), np.float32)
objp[:, :2] = np.mgrid[0:7, 0:6].T.reshape(-1, 2)

axis = np.float32([[3, 0, 0], [0, 3, 0], [0, 0, -3]]).reshape(-1, 3)

for fname in glob.glob('../sample_images/left*.jpg'):
    img = cv2.imread(fname)
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    ret, corners = cv2.findChessboardCorners(gray, (7, 6),None)

    if ret == True:
        corners2 = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), criteria)
        # Find the rotation and translation vectors.
        rvecs, tvecs, inliers = cv2.solvePnPRansac(objp, corners2, mtx, dist)

        # project 3D points to image plane
        imgpts, jac = cv2.projectPoints(axis, rvecs, tvecs, mtx, dist)

        img = draw(img, corners2,imgpts)
        cv2.imshow('img', img)
        k = cv2.waitKey(0) & 0xff
        if k == 's':
            cv2.imwrite(fname[:6]+'.png', img)

cv2.destroyAllWindows()

I tried the solutions offered after searching the internet, but this did not help me. Any help is welcome. I checked every argument, and they appear to be correct, but I'm very new to both python and opencv.

A: change
objp = np.zeros((6*7, 3), np.float32)
objp[:, :2] = np.mgrid[0:7, 0:6].T.reshape(-1, 2)
to
objp = np.zeros((6*7, 1, 3), np.float32)
objp[:,:,:2] = np.mgrid[0:7,  0:6].T.reshape(-1,1,2)
change
rvecs, tvecs, inliers = cv2.solvePnPRansac(objp, corners2, mtx, dist)
to
_, rvecs, tvecs, inliers = cv2.solvePnPRansac(objp, corners2, mtx, dist)


text: Q: Export SoapUI test report in human readable format I try to export a SoapUI test report, which contains failed requests, responses and expected results too. I found just a simple list in result window, which contains test steps with result OK or FAILED status like this: Step 3 [checkHealth] OK: took 10602 ms.


text:
Q: Undefined boolean in an object javascript I attempted the following task but i am stuck on defining a boolean:

Define a function getWalletFacts that receives wallet, an object.
getWalletFacts should return a sentence stating the wallet's color and
cash state.

My attempted code
const hascash = Boolean();

let wallet ={
    color:"",
    hascash:true||false,
    write: function(sentence){
        console.log(sentence);
    }
};
function getWalletFacts(wallet){
    let sentence= "my wallet is " + wallet.color+ " and  " + wallet.hascash;
    return sentence;
}

whenever i check my answer it tells me that hascash is undefined i.e
    Expected: "My wallet is Black and has cash"
        Received: "my wallet is Black and  undefined"

from my understanding of the question hascash accepts a boolean
Given example
const wallet = {
    color: "Black",
    hasCash: true
};

getWalletFacts(wallet); // => 'My wallet is Black and has cash'

const wallet2 = {
    color: "Grey",
    hasCash: false
};

getWalletFacts(wallet2); // => 'My wallet is Grey and does not have cash'

A: It's hasCash, not hascash -- JavaScript is case-sensitive.
You also need a conditional to turn the true/false values into proper English.

function getWalletFacts(wallet) {
  let sentence = "my wallet is " + wallet.color + " and " + (wallet.hasCash ? "has cash" : "does not have cash");
  return sentence;
}

const wallet = {
    color: "Black",
    hasCash: true
};

console.log(getWalletFacts(wallet)); // => 'My wallet is Black and has cash'

const wallet2 = {
    color: "Grey",
    hasCash: false
};

console.log(getWalletFacts(wallet2)); // => 'My wallet is Grey and does not have cash'


text:
Q: Include XAML Trigger To ControlTemplate I am pretty new with WPF and am doing some custom control stuff...
My problem is that the code in one file is going to be way to much, so i want
to split the code in seperate files, so other people looking in that code aren´t going to be overwhelmed.
Okay to my question...
I got a ResourceDictionary... the "Generic.xaml"
In this file a got the template of an DataGrid:
    <Style TargetType="{x:Type local:BADataGrid}">
    <Style.Setters>
        <Setter Property="Control.Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:BADataGrid">
                    <Border BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}"
                        Background="{TemplateBinding Background}"
                        Padding="{TemplateBinding Padding}"
                        SnapsToDevicePixels="True">

           <!-- *SOME TEMPLATE CODE* -->

                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="GridStyle" Value="CUSTOMER">
                            <Trigger.Setters>
                                <Setter Property="ColumnHeaderStyle">
                                    <Setter.Value>
                                        <Style TargetType="{x:Type DataGridColumnHeader}">
                                            <Setter Property="Background">
                                                <Setter.Value>
                                                    <ImageBrush>
                                                        <ImageBrush.ImageSource>
                                                            <Binding  Path="HeaderBackground" RelativeSource="{RelativeSource AncestorType=local:BADataGrid}">
                                                                <Binding.TargetNullValue>
                                                                    <ImageSource>
                                                                        headerBack.png
                                                                    </ImageSource>
                                                                </Binding.TargetNullValue>
                                                            </Binding>
                                                        </ImageBrush.ImageSource>
                                                    </ImageBrush>
                                                </Setter.Value>
                                            </Setter>
                                        </Style>
                                    </Setter.Value>
                                </Setter>
                            </Trigger.Setters>
                        </Trigger>
                    </ControlTemplate.Triggers>

                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style.Setters>
</Style>

Now I want the "ControlTemplate.Triggers" part of the code above in another .XAML File.
Is this even possible?

A: it´s me again. Sorry it took me so long to answer.
I am a few steps ahead now... I got the Trigger in an additional ResourceDictionary, and if I impletment it in the "Window.Resources" where I implement the control everything works just fine.
My problem now is... I don´t want to implement the ResourceDictionary in the "Window.Resources" but in the "ControlTemplate.Resources" of my custom control.   But when I do so it tell´s me :
"Unable to cast object of type 'Microsoft.Expression.Markup.DocumentModel.DocumentCompositeNode' to type 'System.Windows.ResourceDictionary'.
                    <ControlTemplate.Resources>
                        <ResourceDictionary>
                            <ResourceDictionary.MergedDictionaries>
                                <ResourceDictionary
                                Source="Customer.xaml" />
                            </ResourceDictionary.MergedDictionaries>
                        </ResourceDictionary>
                    </ControlTemplate.Resources>

If I copy the code inside the Customer.xaml ResourceDictionary into the ControlTemplate.Resources it works... but I want it in an additional file...
Any ideas?

A: Look into Resource Dictionaries. That should allow you to split styles across files.

A: Did it with a nasty workaround... I´ll just share it with you.
I just implemented an event that is fired when the DataGrid is loaded.
In this event I load the ResourceDictionarys i wanted to add to the control template
in ResourceDictionary object´s. Then i iterate through all entrys in the ResourceDictionary object and add each seperate to the ControlTemplate´s resources...
Here´s the code:
void DataGridLoaded(object sender, RoutedEventArgs e)
    {
        BADataGrid dg = (BADataGrid)VisualTreeHelper.GetParent((DependencyObject)sender);

        List<string> resourceList = new List<string>();
        resourceList.Add(Properties.Resources.Customer);

        foreach (string s in resourceList)
        {
            System.Xml.XmlReader xmlReader = new System.Xml.XmlTextReader(new System.IO.StringReader(s));
            ResourceDictionary resource = (ResourceDictionary)XamlReader.Load(xmlReader);

            foreach (System.Collections.DictionaryEntry item in resource)
            {
                dg.Resources.Add(item.Key, item.Value);
            }
        }


text:
Q: $\int_{0}^{2} (x-1)^3 dx + 2\int_{-1}^{2} (x-1)x dx$ $\int_{0}^{2} (x-1)^3 dx + 2\int_{-1}^2 (x-1)x dx$
$\int_{0}^{2} u^3 du + 2\int_{-1}^2 x^2 - x dx$
I get 4 + 3 = 7
But the answer is 3. Where am i wrong? Any hints anyone?

A: $$I=(\frac{(x-1)^4}{4})|_{0}^{2}+(2\frac{x^3}{3}-x^2)|_{-1}^{2}=\frac{1}{4}-\frac{1}{4}+[(2\frac{8}{3}-4)-(2\frac{-1}{3}-1)]=\frac{4}{3}+\frac{5}{3}=3$$


text:
Q: include sign when double-clicking numbers I am working on a c++ project on windows 7 64-bit. I have a textbox field of type EDITTEXT on my GUI that stores numbers.
Currently every time I double click on it, the numbers are selected but not their signs. I would like to include the sign as well when I double click on it.
Are there any ways I can solve this problem? Is it a configuration problem on windows, or I need to implement a separate event handler (which I currently don't know how) in my project?

A: This is not a solution but a work around for my problem.
I found out my project uses dialog-based windows to handle input data.
From that I can create a static control as a LABEL for my edittext control (http://msdn.microsoft.com/en-us/library/ms997560.aspx) with SS_NOTIFY style (to capture mouse click messages) right before my edittext control.
Then in my custom DialogProc function (http://msdn.microsoft.com/en-us/library/windows/desktop/ms645469(v=vs.85).aspx) I can handle what will happen if the user click/double click the LABEL of my edittext. For my case, I use EM_SETSEL message (msdn.microsoft.com/en-us/library/windows/desktop/bb761661(v=vs.85).aspx) to select everything in the edittext control
Because I cannot figure out how to capture messages sent when user clicking inside an edittext control, I have to implement it on the LABEL instead. This does not solve the root of the problem but at least it works  and its not a bad work around.


text:
Q: .htaccess works fine in local machine but not in server I am developing a website in core PHP and I want the pages to automatically redirect to my custom page (404.php) when someone enters invalid URL after the domain name. For example, I have a URL like www.abcdefg.com/abcd.php and if someone enters www.abcdefg.com/abzzcd.php, instead of showing the 404 error, I want to display the custom message.
It works fine in the local machine (XAMPP - localhost). Website is hosted in HostDime.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /sunday/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /sunday/404.php [L]
</IfModule>

A: Make a files info.php on your server and run on browser for check mod_rewrite enable or not
eg: http://localhost/info.php
echo phpinfo();

A: thanks for your suggestions and help. I got the solution by myself.
ErrorDocument 404 /admin/production/page_403.html

Simply added this at the end of my code and it works perfectly !
Thank you.


text:
Q: How to install python 2.6.8 on windows 7? I have downloaded the two releases of python 2.6.8 from here http://www.python.org/getit/releases/2.6.8/ and I don't know how to install that on my Windows 7 64bit OS. Please someone help me. I searched but I can't find good tutorial.
Thanks!

A: 2.6.8 is a source only release. Download either 2.6.6 or 2.7.3 depending on your requirements, which come with Windows installers.

A: If you want to install Python 2.6.8 on a Windows machine, you can do the following:
If you don't have Microsoft Visual Studio, install it: the Express edition is available here: http://www.microsoft.com/visualstudio/eng/products/visual-studio-express-products
Unzip your source code to a folder (lets call it E:\Python) and open E:\Python\PCbuild\pcbuild.sln in Visual Studio.
Set your build configuration to Debug for Win32 (available under Build => Configuration Manager.
Build your solution. You should see errors, these are related to modules for which patches were released such as zlib and sqlite. Fixing those is a little outside my expertise regarding a Python Windows install but there are patches available as I've resolved some of them on my Unix builds.
In any case, there should now be a python_d.exe file in your E:\Python\PCbuild folder. This is your Python executable.


text:
Q: Sencha Touch Free Commercial License (11. Support and Updates Clause) I just started a project with the newly release Sencha Designer Beta, and I was researching the free commercial license. Someone pointed out on a blog post comment that the 11. Support and Updates section of the license agreement is very restrictive and deceptive. After reading this section, I cannot fully understand it, as I have little experience in interpreting software license agreements.
Can anyone decode this for me in terms of what it really means about receiving updates to the Sencha Touch framework and what is means for someone who is creating an end-user mobile app?

11 . SUPPORT AND UPDATES
You are not entitled to any support for the Software under this
  Agreement. All support must be purchased separately and will be
  subject to the terms and conditions contained in the Sencha support
  agreement. You are entitled to receive minor version updates to the
  Software (i.e. versions identified as follows (X.Y, X.Y+1). You are
  not entitled to receive major version updates (i.e. X.Y, X+1.Y) or bug
  fix updates to the Software (X.Y.Z, X.Y.Z+1). Major version updates
  and bug fix updates to the Software are available separately for
  purchase.

I'm fully clear on the fact that you have to pay for support, but not about the availability of updates. When they release updated versions of the framework, how does this prevent someone from just updating their packages? What are the hidden pitfalls here? As long as we aren't directly requesting bug fixes and support, what in this text would prevent me from just downloading and updating my local framework to the latest release?
Here is a link to the blog post which contains the comment that caused me confusion on the matter: http://mobile.dzone.com/articles/sencha-touch-or-jquery-mobile
Please note that I do not endorse the view taken by this blog comment. I am only linking for the reason that it brought my questions to the surface.

A: As the person who wrote much of that text - originally for our Ext JS license - I can tell you that the intent was not to be deceptive, but some of the text doesn't make sense when it's applied to a free license like the Sencha Touch developer license (and legalese can be read with the wrong tone)
Here's what it means.

*

*You've just downloaded version 1.0 of the software, good for you

*You're entitled to get version 1.1, and 1.2, and 1.3 as well if and when we ship them

*You're not entitled to get version 1.1.1, 1.1.2, 1.1.3 (if and when we ship them) - that's a benefit just for our technical support subscribers

*You're not entitled to file technical support tickets either.

Does that make sense?
(Incidentally, I am a little upset by the implications of the comment in the post you linked and will reply to it now. Our support subscribers allow us to pay for developers to develop patches, which then we make available only to our support subscribers. All patches are rolled into the next minor release.)


text:
Q: How can I set the default values in a ComboBox multicolumns? I have a multi columns combobox. After combo population, I try to set the default values, but I get this error message
Object reference not set to an instance of an object.
This my code
Property

public ObservableCollection<Model_Sedi> Sedi { get; set; }
private Model_Sedi _Sedi_Search;
public Model_Sedi Sedi_Search {
get { return _Sedi_Search; }
set {
    _Sedi_Search = value;
    OnPropertyChanged("Sedi_Search");
    }
    }

this is XAML
  <ComboBox x:Name="Cmb_Sede"
        ItemsSource="{Binding Sedi, Mode=TwoWay}"
                      SelectedValuePath="Value"
                      SelectedItem="{Binding Sedi_Search, Mode=TwoWay}"

                      VerticalAlignment="Top" Width="189">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding IdSede, UpdateSourceTrigger=PropertyChanged}"></TextBlock>
                    <TextBlock Text="{Binding Sede, UpdateSourceTrigger=PropertyChanged}" Padding="10,0,0,0"></TextBlock>
                </StackPanel>
            </DataTemplate>
        </ComboBox.ItemTemplate>
        <ComboBox.Effect>
            <DropShadowEffect Color="#FF0A0A0A" Opacity="0.6"/>
        </ComboBox.Effect>
    </ComboBox>

Now, how can I set the default values ? (like this doesn't work)
Sedi_Search.Sede = "ABC"
Sedi_Search.IdSede = 111

A: You need to set the Sedi_Search property to a matching object from the Sedi collection. Just use LINQ for this:
Sedi_Search = Sedi.SingleOrDefault(x => x.Sede == "ABC" && x.InSede == 111);

Another way of writing this:
Func<Model_Sedi, bool> isMatch = delegate(Model_Sedi x)
{
    return x.Sede == "ABC" && x.InSede == 111;
};

Sedi_Search = Sedi.SingleOrDefault(isMatch);

The first version is just a shorthand version of the second. x is just a variable name used by the delegate/lambda expression. This SO question might prove useful: Linq and lambda expression.

A: Change SelectedValuePath="IdSede" in XAML and in View Model you have to do what Steven Rands is saying.


text:
Q: getSharedPreferences crashes with path-based preferences I was doing:
mPrefs = theActivity.getSharedPreferences("SomeApp/SomePrefs.prefs", Context.MODE_PRIVATE);

and this caused Android to crash. Not sure what exception it was throwing.
When I changed that string to "SomeApp_SomePrefs.prefs" things started working.
Where is it documented that a slash is verboten?
How can I find out what exception is being thrown?

A: name parameter of getSharedPreferences class is a file name. / is not allowed in file names.


text:
Q: IcmpSendEcho returns 183 I adapted this code example from MSDN here. It works fine if I build it alone, but if I add it to my application it fails. For convenience I include the exact adaptation of the class I have.
I only want to do a simple ping every second. Raw Sockets don't work without admin rights, and this ICMP.dll approach doesn't work within my application and I don't understand why. Error 183 goes along the lines of "Cannot create a file because it already exists" which makes no sense in this context.
Can anyone spot the problem? Thanks so much for your help.
Ping.h
    #pragma once
    #include "Ping.h"
    #include "LogBase.h"
    class WinPing :
        public Ping
    {
    public:
        WinPing(char* address, int period);
        ~WinPing();

        unsigned long           GetRTT();
    private:
        HANDLE                  _hIcmpFile;
        unsigned long           _ipaddr;
        DWORD                   _dwRetVal;
        LPVOID                  _replyBuffer;
        DWORD                   _replySize;

        static HANDLE           _inputTimer;

        int                     _period;
        unsigned long           _lastRTT;

        static DWORD WINAPI     AsyncPingHandler(void* Param);
        void                    DoPing();

    };

WinPing.h
    #pragma once
    #include "Ping.h"
    #include "LogBase.h"
    class WinPing :
        public Ping
    {
    public:
        WinPing(char* address, int period);
        ~WinPing();

        unsigned long           GetRTT();
    private:
        HANDLE                  _hIcmpFile;
        unsigned long           _ipaddr;
        DWORD                   _dwRetVal;
        LPVOID                  _replyBuffer;
        DWORD                   _replySize;

        static HANDLE           _inputTimer;

        int                     _period;
        unsigned long           _lastRTT;

        static DWORD WINAPI     AsyncPingHandler(void* Param);
        void                    DoPing();

    };

WinPing.cpp
    #include "WinPing.h"
    #include <winsock2.h>
    #include <iphlpapi.h>
    #include <icmpapi.h>
    #include <stdio.h>
    #include "utils.h"

    #pragma comment(lib, "iphlpapi.lib")
    #pragma comment(lib, "ws2_32.lib")

    HANDLE WinPing::_inputTimer = NULL;
    char SendData[32] = "Data Buffer";

    unsigned long WinPing::GetRTT()
    {
        return _lastRTT;
    }

    void WinPing::DoPing()
    {
        LARGE_INTEGER t;
        t.HighPart = t.LowPart = 0;
        SetWaitableTimer(_inputTimer, &t, _period, NULL, NULL, TRUE);

        while (true)
        {
            int r = WaitForSingleObject(_inputTimer, _period * 2);
            if (r != WAIT_OBJECT_0)
            {
                LogLog("InputHandler: Bad Timer return", LogError);
            }

            _dwRetVal = IcmpSendEcho(_hIcmpFile, _ipaddr, SendData, sizeof(SendData),
                NULL, _replyBuffer, _replySize, 1000);
            if (_dwRetVal != 0) {
                PICMP_ECHO_REPLY pEchoReply = (PICMP_ECHO_REPLY)_replyBuffer;
                struct in_addr ReplyAddr;
                ReplyAddr.S_un.S_addr = pEchoReply->Address;
                LogLog("\tSent icmp message to %s\n", LogDebug, _address);
                if (_dwRetVal > 1) {
                    LogLog("\tReceived %ld icmp message responses\n", LogDebug, _dwRetVal);
                    LogLog("\tInformation from the first response:\n", LogDebug);
                }
                else {
                    LogLog("\tReceived %ld icmp message response\n", LogDebug, _dwRetVal);
                    LogLog("\tInformation from this response:\n", LogDebug);
                }
                LogLog("\t  Received from %s\n", LogDebug, inet_ntoa(ReplyAddr));
                LogLog("\t  Status = %ld\n", LogDebug,
                    pEchoReply->Status);
                LogLog("\t  Roundtrip time = %ld milliseconds\n", LogDebug,
                    pEchoReply->RoundTripTime);

                //needs synchronization here. Probably not very important
                _lastRTT = pEchoReply->RoundTripTime;
                LogLog("\t  Roundtrip time = %ld milliseconds\n", LogDebug, _lastRTT);
                IcmpCloseHandle(_hIcmpFile);
            }
            else {
                LogLog("\tCall to IcmpSendEcho failed.\n", LogError);
                LogLog("\tIcmpSendEcho returned error: %ld\n", LogError, GetLastError());

            }

        }
    }

    DWORD WINAPI WinPing::AsyncPingHandler(void* Param)
    {
        _inputTimer = CreateWaitableTimer(NULL, false, NULL);
        if (!_inputTimer)
        {
            LogLog("Unable to create input waitable timer", LogError);
            return 1;
        }

        LogLog("RTT Ping Thread started", LogDebug);
        WinPing* This = (WinPing*)Param;
        This->DoPing();

        return 0;

    }

    WinPing::WinPing(char* address, int period)
        :Ping(address),
        _period(period)
    {
        // Declare and initialize variables
        _ipaddr = INADDR_NONE;
        _dwRetVal = 0;
        _replyBuffer = NULL;
        _replySize = 0;

        _ipaddr = inet_addr(address);
        if (_ipaddr == INADDR_NONE) {
            LogLog("Not an IP Address:%s", LogError, address);
            return;
        }

        _hIcmpFile = IcmpCreateFile();
        if (_hIcmpFile == INVALID_HANDLE_VALUE) {
            LogLog("\tUnable to open handle.\n", LogError);
            LogLog("IcmpCreatefile returned error: %ld\n", LogError, GetLastError());
            return;
        }

        _replySize = sizeof(ICMP_ECHO_REPLY) + sizeof(SendData);
        _replyBuffer = (VOID*)malloc(_replySize);
        if (_replyBuffer == NULL) {
            LogLog("\tUnable to allocate memory\n", LogError);
            return;
        }

        //Spawn thread on AsyncPingHandler()
        CreateClassThread(AsyncPingHandler, this);

    }

    WinPing::~WinPing()
    {
    }

A: You are not calling GetLastError() immediately after IcmpSendEcho() fails (same when calling IcmpCreateFile()).  You are calling LogLog() first, which is likely altering the error code that GetLastError() returns, for instance if it is logging to a file that cannot be found.  ALWAYS call GetLastError() before doing anything that may call a system function.
else {
    DWORD dwErrCode = GetLastError(); // <-- call GetLastError() first
    LogLog("\tCall to IcmpSendEcho failed.\n", LogError);
    LogLog("\tIcmpSendEcho returned error: %u\n", LogError, dwErrCode); // <-- then use the value when needed
    return;
}

A: I found out that a much easier, much more stable way of doing ping is using GetRTTandHopCount. Here is an example.
UINT ip = inet_addr(serverAddress);
ULONG hopCount = 0;
ULONG RTT = 0;

if (GetRTTAndHopCount(ip, &hopCount, 30, &RTT) == TRUE) {
    printf("Hops: %ld\n", hopCount);
    printf("RTT: %ld\n", RTT);
}
else {
    printf("Error: %ld\n", GetLastError());
}

return RTT;


text:
Q: Airflow - Run backfill command month by month I've read the Airflow documatation and I realized the backfill command will run my dags for each day of the date range that I provided. But is there a way to run my dags once per month using backfill? E.g. I provide the range 2020-01-01 to 2020-12-01 and I need to run once on January, once on February, and so.
Thanks for your help!

A: backfill will rerun failed previous runs of a specified dag given its dag_id.
It will not run for each day unless your dag identified by dag_id is run each day.
If the dag identified by dag_id is run once eevry month, backfill will follow that frequency.
A dag can easily be scheduled to run every day using a cron.


text:
Q: How can one determinate if a function will return sub-functions without execution It the context of a one-page application development, I need to transform a string into an executable function.
var repo = {};

I used strings in 2 formats :
repo.toto = "function toto(){\
    alert('Hello, I am toto');\
}";

repo.titi = "function titi(){\
    this.sub1 = function() {};\
    this.sub2 = function() {};\
    this.sub3 = function() {};\
}";

I want to know if a function once executed will give, or not, an object of sub-functions.
Below is a full case that illustrate my problem. Eval is not a solution.
var createFunc = function(name) {
    var string = repo[name];
    var func = Function("return new "+string+"");
    repo[name] = func;
};

typeof repo.toto; //string
typeof repo.titi; //string

createFunc('toto');
createFunc('titi');

typeof repo.toto; //function
typeof repo.titi; //function

repo['toto'](); //alert('Hello, I am toto');
//Object {}

repo['titi']();
//Object { sub1: anonymous/titi/this.sub1(), sub2: anonymous/titi/this.sub2(), sub3: anonymous/titi/this.sub3() }

Do you know a way to determinate if the function will give an empty object
(like in the "toto" example) or not (like the "titi" example), without having to execute the function?

A: I will agree that it's not possible for every scenario.
But with the two sample inputs, the main difference is that one has properties and the other does not.
Note that with the return new you're instantiating the functions from the strings and returning the new instance. Any code directly inside the function will be executed (like a constructor) and the result will be an object of the properties and methods. So... that's why the first one returns an empty object.
You could tell if it will return an empty object or not if there isn't any this.(something)=. But it might not be the best solution, I don't see the use of this.


text:
Q: Can't find the php.ini file in XAMPP I recently installed XAMPP and now I want to change some settings in the php.ini file, but I can't find it anywhere. Instead, in the xampp/php directory I found two files: php.ini-development and php.ini-production. Can I use these in order to do the changes I want?

A: php.ini is hidden by Default. You need to show it using CP folder settings

A: Important Configuration Files And Directories

opt/lampp/bin/ - The XAMPP commands home. /opt/lampp/bin/mysql calls for example the MySQL monitor.

/opt/lampp/htdocs/ - The Apache DocumentRoot directory.

/opt/lampp/etc/httpd.conf - The Apache configuration file.

/opt/lampp/etc/my.cnf - The MySQL configuration file.

/opt/lampp/etc/php.ini - The PHP configuration file.

/opt/lampp/etc/proftpd.conf - The ProFTPD configuration file. (since 0.9.5)

/opt/lampp/phpmyadmin/config.inc.php - The phpMyAdmin configuration file.


text:
Q: How to return an incremented variable to next recursion call on the recursion stack? So I am answering a question where we are given a flight of stairs that we need to climb and some target height. We are told the maximum number of steps we can take with each step. And we are asked to return the number of ways we can reach this target height, using recursion.
let's say that target height is 3, and the max steps is 2.
Then the solution would be 3, since we can take the following steps #1,1,1 #1,2 and #2,1 to reach the target height.
Here is my code below:
def staircaseTraversal(height, maxSteps):
    numberOfWays = 0
    staircaseTraversalHelper(height, maxSteps, 0, 0)
    if numberOfWays:
        return numberOfWays
    return -1

def staircaseTraversalHelper(height, maxSteps, currentHeight, numberOfWays):
    for step in range(1, maxSteps+1):
        newHeight = currentHeight + step
        if newHeight == height:
            return numberOfWays + 1
        elif newHeight < height:
            staircaseTraversalHelper(height, maxSteps, newHeight, numberOfWays)

My question is regarding updating the numberOfWays when we hit such a point where the current step we are on (newHeight) is equal to the target height, and we increment the numberOfWays by 1, I am then struggling to return this numberOfWays to the next recursion call on the recursion stack!
At the moment I am doing return numberOfWays + 1 - but I don't think this is correct. I also tried incrementing numberOfWays by 1, then simply breaking out of the for loop, then returning nothing to get to the next recursion call in the recursion stack, but this doesn't seem to work either.
Also, it would be great if I could get feedback on the set up of my overall recursive solution, as I am quite new to the ideas, albeit I do understand it quite comprehensively.

A: I think you can do something like below.
Here, height argument means the "remaining height", so I subtract steps for the recursive calls.
Note that you may also use sum to reduce the number of lines.
def staircaseTraversal(height, maxSteps):
    if height == 0:
        return 1
    if height < 0:
        return 0

    out = 0
    for step in range(1, min(height, maxSteps) + 1):
        out += staircaseTraversal(height - step, maxSteps)
    return out

staircaseTraversal(3, 2)
# 3

A: This is a simple solution to your answer, instead of adding a new argument "currentHeight", you can do it like this
def staircaseTraversal(height, maxSteps):
    numbersOfWays = 0
    for step in range(1, maxSteps+1):
        if height == step:
            numbersOfWays +=1
            break
        elif height < step:
            break
        else:
            numbersOfWays += staircaseTraversal(height -step, maxSteps)
    return numbersOfWays
print(staircaseTraversal(3,2))


text:
Q: Add toolbar - error "no object added" I'm trying to add Hawths Tools to by Toolbar selection.  I'm running ArcMap/ArcInfo v.9.3.1. Hawths Tools is not supported in v.10.  I've dowloaded the zip file, extracted the files, adn ran teh .exe file.  When I go to "customize" Tools, add from file, and select under Program files "HawthsTools3.dll", an "Added Objects..." menu pops up that reads: No new objects added.
If you then open ArcMap, select View, then Toolbars, Hawths Tools does not show up.
Can anyone provide assistance?

A: Unfortunately there are heaps of things which can result in "No new objects added". However as you are installing someone else's work rather than developing it should be more straightforward. First, try selecting the .tlb file instead of the .dll. If this doesn't work I can expand with other suggestions.

A: You should register HawthsTools by double clicking HawthsTools3 Registration entries..and then...follow the procedure that you been done...


text:
Q: NA outcome when running over() between a SpatialPoints and SpatialPolygonsDataFrame I am having a problem when over() doesn't give a value but keep giving meNA for every field in the outcome data.frame. The aim is to have the counts of tardigrade occurrences in each biogeoregion.
Here is my data set and its compositions.
#extention=europe area
> tardigrade <- <- gbif("Eutardigrada",ext=e, sp=T, removeZeros=T, download=T)

> tardigrade_sp <- as(tardigrade, "SpatialPoints")

tardigrade_sp

class       : SpatialPoints
features    : 2033
extent      : -8.250667, 32.14889, 34.66667, 66.28333  (xmin, xmax, ymin, ymax)
crs         : +proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +units=m +no_defs

biogeo # can be find at https://www.eea.europa.eu/data-and-maps/data/biogeographical-regions-europe-3

class       : SpatialPolygonsDataFrame
features    : 12
extent      : 943611, 8500000, 6e+05, 7800000  (xmin, xmax, ymin, ymax)
crs         : +proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +units=m +no_defs
variables   : 4
names       : short_name, pre_2012,    code,                           name
min values  :     alpine,      ALP,  Alpine, Alpine Bio-geographical Region
max values  :    steppic,      STE, Steppic,                 outside Europe

> over (biogeo, tardigrade_sp)
1  2  3  4  5  6  7  8  9 10 11 12
NA NA NA NA NA NA NA NA NA NA NA NA

Can anyone tell me what did I do wrong and what should I do?

A: The most important part you missed was setting the projection on the first tardigrade object and then converting either tardigrade or biogeo object to the CRS of the other object using spTransform. It is relevant for answers to include the libraries that were used.
It is also recommendable to use library sf for the sake of speed and logic when using spatial data. After the over function, I included a sf version of the code.
library(dismo)
library(sp)
library(rgdal)

# extent from original post
e = extent(-8.250667, 32.14889, 34.66667, 66.28333)
tardigrade = gbif("Eutardigrada", ext = e, sp = T, removeZeros = T, download = T)
# you missed this important step; object tardigrade was not having CRS:
proj4string(tardigrade) <- CRS("+init=epsg:4326")

# download and unzip at print(getwd())
download.file("https://www.eea.europa.eu/data-and-maps/data/biogeographical-regions-europe-3/zipped-shapefile-format-vector-polygon/zipped-shapefile-format-vector-polygon/at_download/file",
              "biogeo.zip")
unzip("biogeo.zip")

biogeo = readOGR("BiogeoRegions2016.shp")
# transform to epsg:4326 (long-lat)
biogeo = spTransform(biogeo, CRS("+init=epsg:4326"))

over(tardigrade, biogeo)
# PK_UID  short_name pre_2012        code                                name
# 1        4    atlantic      ATL    Atlantic    Atlantic Bio-geographical Region
# 2        6      boreal      BOR      Boreal      Boreal Bio-geographical Region
# 3        6      boreal      BOR      Boreal      Boreal Bio-geographical Region
# 4        6      boreal      BOR      Boreal      Boreal Bio-geographical Region
# 5        7 continental      CON Continental Continental Bio-geographical Region

# SF code ---------------
e = extent(-8.250667, 32.14889, 34.66667, 66.28333)
tardigrade = gbif("Eutardigrada", ext = e, sp = T, removeZeros = T, download = T)
tardigrade = st_as_sf(tardigrade) %>%
  st_set_crs(4326)

# the file is already downloaded
biogeo = read_sf("BiogeoRegions2016.shp")
# transform to epsg:4326 (long-lat)
biogeo = st_transform(biogeo, 4326)

st_join(tardigrade, biogeo) %>%
  dplyr::filter(!is.na(PK_UID)) %>%
  dplyr::select(-1)
# PK_UID  short_name pre_2012        code                                name
# 1       4    atlantic      ATL    Atlantic    Atlantic Bio-geographical Region
# 2       6      boreal      BOR      Boreal      Boreal Bio-geographical Region
# 3       6      boreal      BOR      Boreal      Boreal Bio-geographical Region
# 4       6      boreal      BOR      Boreal      Boreal Bio-geographical Region
# 5       7 continental      CON Continental Continental Bio-geographical Region


text:
Q: Construct a sample space $\Omega$ when interested in the probability of having conducting $i$ number of trails for $r$ times of success I know that for a random variable $X$ follows Pascal distribution $PA(r,\theta)$, the random variable refers to the number of trails needed for $r$ success. I have no problem in writing the probability distribution, as it is easily thinkable that if we want $r$ success, suppose we conduct $i$ times of the experiment, the $i$-th trail must be the $r$-th success, and for the $r-1$ previous trails, it is nothing but a binomial probability,  for the $i-1$ number of trails, select $r-1$ number of trails for being a success, the total number of combinations $\left(\begin{array}{l}
i-1 \\
r-1
\end{array}\right)$ times the probability of having $r-1$ success in a total of $i-1$ trails, which is $\theta^{r-1}(1-\theta)^{i-r}$, therefore $$P(X=i)=\left(\begin{array}{c}
i-1 \\
r-1
\end{array}\right) \theta^{r}(1-\theta)^{i-r}$$
However, I always have difficulty to link these distributions to what I have told in the measure-theoretic probability, for example, in this case, if I go back to the definition of a random variable, $X:(\Omega,\mathcal{A},\mathbb{P})\rightarrow(R,\mathcal{B})$, what $\Omega$, $\mathcal{A}, \mathbb{P}$ would look like? Would it be problematic if I write $P(X=i)=\mathbb{P}(\{w:X(w)=i\})$? In that case, what would $\Omega$ look like?
My first instinct is to suppose $r=1$, denotes failure as $0$, success as $1$, $\Omega=\{\{1\},\{0,1\},\{0,0,1\},...\}$, however the problem is that if I change $r$, the whole $\Omega$ would look complete different! Wouldn't that suggest the distribution of a random variable depends on the specification of the measure space?

A: Here is one possibility.
Consider $\Omega=\{0,1\}^{\mathbb{N}}$ (infinite sequences of $0$s and $1$s) endowed with the product $\sigma$-algebra $\mathscr{F}:=\bigotimes_n\mathcal{P}(\{0,1\})$ and the product measure $P(\{(\omega_1,\ldots,\omega_n)\})=\prod^n_{j=1}\theta^{\omega_j}(1-\theta)^{1-\omega_j}$
This is basically the abstract space where Bernoulli trials are defined so that $P(\{\omega:\omega_1=1\})=\theta$ and $P(\{\omega:\omega_1=0\})=1-\theta$.
For each $n\in\mathbb{N}$, define the function $X_j=\boldsymbol{\omega}=(\omega_1,\omega_2,\ldots)\mapsto \omega_j$, that is, $X_j(\boldsymbol{\omega})=\omega_j$ is the projection onto the $j$-th component.
Define $S_0=0$ and $S_n=\mathbb{1}_{\{1\}}(X_1)+\ldots+ \mathbb{1}_{\{1\}}(X_n)$ for $n\in\mathbb{N}$. For each $n\in\mathbb{Z}_+$, $S_n$ gives the number of ones that are in the first $n$ components of $\boldsymbol{\omega}$ (number of successes in $n$ consecutive experiments if you will).
Define
$$X_r(\boldsymbol{\omega}):=\min\{n\geq1: S_n(\boldsymbol{\omega})=r\}$$
It is not difficult to check that $X_r$ is an $\mathscr{F}$-$\mathbb{B}(\mathbb{R})$ measurable function (random variable) taking values on $\mathbb{N}$. The law (distribution) of $X$ is what you described in the OP as the Pascal distribution.


text:
Q: Laravel pivot table test I've got a test where I check if records in a pivot table are being removed. The test looks like this:
/** @test */
public function when_a_relation_is_destroyed_linked_products_will_go_away()
{
    $products = create(Product::class, [], 3)->toArray();
    $relation = create(Relation::class)->syncProducts($products);

    $this->actingAs($this->user)->deleteJson('/relaties/'.$relation->id);

    $this->assertDatabaseMissing('product_has_relations', [
        "product_id" => "1", "relation_id" => "1",
        "product_id" => "2", "relation_id" => "1",
        "product_id" => "3", "relation_id" => "1"
    ]);
}

When I test this in my real application the records in the pivot table are removed correctly. But my test keeps failing:
Failed asserting that a row in the table [product_has_relations] does not match the attributes {
    "product_id": "3",
    "relation_id": "1"
}.

Found: [
    {
        "product_id": "1",
        "relation_id": "1"
    },
    {
        "product_id": "2",
        "relation_id": "1"
    },
    {
        "product_id": "3",
        "relation_id": "1"
    }
].

This is not working aswel:
$this->assertDatabaseMissing('product_has_relations', [
    ["product_id" => "1", "relation_id" => "1"],
    ["product_id" => "2", "relation_id" => "1"],
    ["product_id" => "3", "relation_id" => "1"]
]);

Any idea what could be wrong here?

A: Your problem is here $this->actingAs($this->user)->deleteJson('/relaties/'.$relation->id);.
Records are not deleted hence the test fails.


text:
Q: Using adverb before or after a verb, what is the difference? I have seen following two varients of the sentences

John and the team have worked tirelessly

and

John and the team have tirelessly worked

I believe "tirelessly" is an adverb. Which of the above sentences is correct? If both the sentences are correct, when to use which form?

A: While English is usually very strict about word order, when it comes to adverbs and the verb they modify, it can go either way. You can say "we worked tirelessly" or "we tirelessly worked". Both mean the same thing.
Without doing a statistical analysis, I think we usually put the adverb after the verb. "I worked tirelessly", "I ran quickly to the door", "I grabbed selfishly", etc.
Just to make it more complicated, if the verb has a direct object, you can put the adverb before the verb or after the direct object, but not between the verb and the direct object. Like you could say, "I suddenly found the solution", or you could also say, "I found the solution suddenly." But a fluent speaker would NOT say, "I found suddenly the solution."
As to when to put the adverb first and when to put it later, I can't think of any general rule. If someone else on here can suggest a rule, I'm happy to hear it. I think it's mostly about emphasis. If the adverb is important, you tend to put it after. Like if I said, "I worked tirelessly", that puts more emphasis on the claim that I was tireless, but if I said "I tirelessly worked", that puts more emphasis on the fact that I simply worked. But it's often a very subtle difference.

A: Yes, tirelessly is a verb. Both of them are absolutely correct.
Although people prefer using the adverb before the verb. If an adverb strongly modifies the main verb, put it before the main verb, not after the first helping verb (in a compound verb with three or more words.
A verb is a word for an action or a state of being. An adverb is a word used to modify a verb, an adjective, or another adverb.
Therefore using the first one would be more appropriate


text:
Q: Finding a maximum in inverse parabola iteratively I have an array that represents an inverse parabola and I want to find the maximum which can be anywhere in the array. In my application I cannot take the derivative and I have to loop through the array.
I implemented this by iterating through the array starting on the left and until I get a value lower that the previous iteration:
import numpy as np

def simulation(n):
    # create inverse parabola
    num = 21
    parabola= np.linspace(-8, 12, num=num)
    parabola= -np.abs(parabola) ** 2
    return parabola[n]

previous_iteration = -1000 # some initialization
for n in range(num):

    # Configure the entire system
    # Run simulation

    # simulation(n) - a function returning simulation result with configuration "n"
    simulation_result = simulation(n)

    if previous_iteration < simulation_result :
        previous_iteration = simulation_result
    else:
        best_iteration = n-1
        break

print(best_iteration)
print(previous_iteration)

Is there a faster way to do this?
Edit:
The actual implementation will be on a FPGA and for every iteration I have to configure the system and run a simulation so every iteration costs a lot of time. If I run the simulation with all possible configurations, I will get a parabola vector but that will be time consuming and very inefficient.
Im looking for a way to find the maximum value while generating as less points as possible. Unfortunately the for loop has to stay because that is representation of how the system works. The key here is to change the code inside the for loop.
I edited the code to better explain what I mean.

A: What you want to do is called a grid search. You need to define your search grid points (here in 'x') and calculate all the values of the parabola for these points (here in 'y'). You can use np.argmax to find the index of the argument that yields the maximum value:
import numpy as np

# Define inverse parabola
parabola = lambda x: -np.abs(x)**2

# Search axis
x = np.linspace(-8, 12, 21)

# Calculate parabola at each point
y = parabola(x)

# Find argument that yields maximum value
xmax = x[np.argmax(y)]
print(xmax)           # Should be 0.0

A: An inverse parabola (sampled at evenly spaced points) has the property that the differences between adjacent points always decreases. The maximum is just before the differences go negative.
If the difference between the first two points is negative or zero, the maximum is the first point in the array.
Otherwise, do a binary search to find the smallest positive difference between two adjacent points. The maximum will be the second of these two points.

A: I edited the post hopefully the problem clearer now.

A: What you're looking for is called a "ternary search": https://en.wikipedia.org/wiki/Ternary_search
It works to find the maximum of any function f(x) that has an increasing part, maybe followed by an all-equal part, followed by a decreasing part.
Given bounds low and high, pick 2 points m1 = low +(high-low)/3 and m2 = low + (high-low)*2/3.
Then if f(m1) > f(m2), you know the maximum is at x<=m2, because m2 can't be on the increasing part.  So set high=m2 and try again.
Otherwise, you know the maximum is at x>=m1, so set low=m1 and try again.
repeat until high-low < 3 and then just pick whichever of those values is biggest.


text:
Q: How to import local c++ shared library .so into Android studio 1.5? I have a simple question, but very specific.
I built in a c++ project (non-android) a shared library .so which I'm using for others projects.
I want to use it now to develop an Android app with Android NDK. In the /app/src/main/jni folder, I have the cpp file and I would like to use the functions of my library. Here the content of the .cpp file
#include <string.h>
#include <jni.h>
#include <mysharedlibrary.h>

jstring
Java_com_example_nativeapp_MyActivity_stringFromJNI( JNIEnv* env,
                                                jobject thiz ) {

      ObjectFromSharedLibrary obj;
      functionFromSharedLibrary(obj);
      ...

}

But I really don't know how to do it. I spent the last 2 day looking for an answer but I found nothing
Here my environment:

*

*OS Linux Ubuntu 14.04 LTS

*Android studio 1.5

*Gradle 2.8

*my .so is located in /usr/local/lib and *.h in /usr/local/include/mysharedlibraryname/

I want to know if it's possible and how to do it properly from scratch.
Thanks in advance

A: First build your .so shared libraries using eclipse . Now add Your generated *.so files in Android Studio using gradle 0.7.2+. First create the jniLibs at this location /app/src/main/ location and copy all the folder with *.so files (armeabi, armeabi-v7a, mips, x86) in the jniLibs. As shown in this Link


text:
Q: Handling compound primary keys in NHibernate event listeners I'm trying to extract the primary key property name and value of the original entity from within an NHibernate event listener and I want it to be able to handle compound primary keys.
The problem I'm having is that in my event handler, when dealing with a compound primary key, the Id property of the event that gets fired seems to get bound to the entire original entity:

How do I get at the original ID property names and corresponding values?

A: I would use the following code for components:
if (@event.Persister.IdentifierType.IsComponentType)
{
    var componentType = (IAbstractComponentType) @event.Persister.IdentifierType;
    var values = componentType.GetPropertyValues(@event.Id);
    var propertyNames = componentType.PropertyNames;
    for (int i = 0; i < values.Length; i++)
    {
        Console.WriteLine($"PropertyName: {propertyNames[i]}, Value: {values[i]}");
    }
}

A: if (@event.Persister.IdentifierType is NHibernate.Type.EmbeddedComponentType identifierType)
{
    // This entity has a composite primary key.

    foreach (var propertyName in identifierType.PropertyNames)
    {
        // Because we only have the name of the property we have to use reflection to get
        // the corresponding value.
        object propertyValue = @event.Id.GetType().GetProperty(propertyName).GetValue(entityId);
    }
}


text:
Q: Python Anaconda Prompt: ¿Como acceder a una ruta de disco con espacios? En 'Anaconda Prompt' estoy intentando acceder a una ruta con espacios, introducida entre comillas, y me da el siguiente error:
cd "D:1- Programación\\2\"

El sistema no puede encontrar la ruta especificada.
La misma ruta la uso en el CMD de Windows y sí funciona.

A: En todos los lenguajes de programación existen las llamadas secuencias de escape, y se representan escribiendo en primer lugar una barra invertida (\).
Por ejemplo, para representar un salto de línea utilizarías la cadena "\n", o para una tabulación "\t".
Para representar una barra invertida debes utilizar "\\" (así indicas que no estás representando una secuencia de escape).
Otra opción es utilizar las barras no invertidas "/" para indicar la ruta (aunque estés en Windows funcionará).


text:
Q: MongoDB retrieval error I am retrieving a document from MongoDB using find() in Node.js, while printing the result I am not getting the retrieved values. Here my code..
       db.collection("Product").find({'entry_id':entryID},function(err, result) {
        console.log("Output:",result);

A: You could just about place money on entry_id is an ObjectId value and what you are passing as a variable is actually just a string.
But the other obvious thing is that you are using .find() in the wrong way. The "result" returned is a
"cursor". If you want something that looks like a whole result set, then use .toArray() or other similar method of conversion:
       var ObjectID = require('mongodb').ObjectID;

       db.collection("Product").find({
           'entry_id': new ObjectID(entryID)
       }).toArray(function(err, result) {
        console.log("Output:",result);
       });


text:
Q: Curl function is not working? I am trying to fetch a data from a site using curl method. Before i can able to get data by using curl.Recently client taken ssl certificate for that site from then onwards i can't able to get the data using curl. But when i try the URL in browser i can able to see data. Can any one tell me why it is not working.did i need to try in some another way.
Below is my code
// create curl resource
    $ch = curl_init();

    // set url
    curl_setopt($ch, CURLOPT_URL, "https://qa.myhealth.today/myhealth-portal/nirvahak/public/validateSessionttt?username=pavithra@gmail.com");

    //return the transfer as a string
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    // $output contains the output string
    $output = curl_exec($ch);

    // close curl resource to free up system resources
    curl_close($ch);
  $output=json_decode($output);
     print_r($output);

A: There are 2 fixes:
1) SSL certified websites do not trust any non-SSL requests. So, we need to win trust of SSL enabled client.
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);

2) Provide him the security certificate.
Go the the respective site. Save the SSL certificate and pass the certificate path to the CURL request.
So, the final code should be:
// create curl resource
    $ch = curl_init();
$url = "https://qa.myhealth.today/myhealth-portal/nirvahak/public/validateSessionttt?username=pavithra@gmail.com";

    // set url
    curl_setopt($ch, CURLOPT_URL, $url);

    //return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CAINFO, getcwd() . "/CAcerts/BuiltinObjectToken-EquifaxSecureCA.crt");
    // $output contains the output string
    $output = curl_exec($ch);

    // close curl resource to free up system resources
    curl_close($ch);
  $output=json_decode($output);
     print_r($output);

Detailed instructions on how to do it are place here:

A: Set CURLOPT_SSL_VERIFYHOST and CURLOPT_SSL_VERIFYPEER to false.
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

CURLOPT_SSL_VERIFYHOST
1 to check the existence of a common name in the SSL peer certificate. 2 to check the existence of a common name and also verify that it matches the hostname provided. In production environments the value of this option should be kept at 2 (default value).

CURLOPT_SSL_VERIFYPEER
FALSE to stop cURL from verifying the peer's certificate. Alternate certificates to verify against can be specified with the CURLOPT_CAINFO option or a certificate directory can be specified with the CURLOPT_CAPATH option.

Source: http://php.net/manual/en/function.curl-setopt.php


text:
Q: How do I start a .NET process with idle priority? I'm using System.Diagnostics.ProcessStartInfo to set up the parameters for launching a process from a .NET program. Once the the process is started, I can use
myProcess.PriorityClass = ProcessPriorityClass.Idle

To change the priority for the process to idle, so that it only runs in the background, and doesn't hog my CPU power. Is there any way using the ProcessStartInfo object to specify that the process should start with an "Idle" priority, so that at no time during execution is the process running at higher than idle speed?

A: There is no provided API in the Process class to start a process with a different priority.  The best option is to just set it immediately after starting the process.  Once you start the process, you can set the Process.PriorityClass:
var myProcess = Process.Start(...);
myProcess.PriorityClass = ProcessPriorityClass.Idle;

If you wish to prevent the process from running with a higher priority, darin's answer provides a workaround using P/Invoke and the Windows API.  Even this starts the process with a normal priority, but if it's started in a suspended state, it will not run, so the priority would have no effect.

A: Start the process suspended, then change the priority, and then resume the process. You do this with the CreateProcess Win32 function using the CREATE_SUSPENDED flag but unfortunately I am not sure if there's support in .NET for this and you might need to resort to P/Invoke.


text:
Q: How to get data from jQuery ajax post with ExpressJS Hi so I have a jquery post data that i'm sending:
                 $.ajax({
                    type: "POST",
                    url: app.config.backend_2 + '/notifications/usernames',
                    data: data,
                    contentType: 'application/javascript',
                    dataType: 'json',
                    success: function (result) {
                        console.log(result);
                    }
                });

and this is my express receiver:
 exports.save_usernames_for_notifications = function (req, res, next) {
    var start = function () {
       console.log(req);
    };

     start();

};

What do I do to get the data from the ajax to log it in the save_username_for_notifications function?

A: You need a body parser middleware in your expressjs application to parse your JSON req object
https://www.npmjs.com/package/body-parser
To configure it, you need this code
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // this is used for parsing the JSON object from POST

Then to get your data in your express application just do this
console.log(req.body.data)


text:
Q: Telegram calls via Dante socks5 proxy server not working I've confugured Dante 1.4on Ubuntu 16.04 as a socks5 proxy for Telegram.
Chats are working, but voice calls are not, failing at "Connecting".
Is there something special I need to configure in order to proxy Telegram voice traffic?
I'm using a single non priveleged (>1024) TCP/UDP port + login + password for connection.
Thats piece of log while i am trying to call somebody:
Apr 15 23:05:38 (1523736338.510915) danted[22977]: info: pass(1): udp/udpassociate [: username%USER@0.0.0.0.0 192.168.1.30.36562

Apr 15 23:08:33 (1523736513.020190) danted[22989]: info: pass(1): udp/udpassociate [: username%USER@0.0.0.0.0 192.168.1.30.49065

I can answer the call at destination device but connection is looping and getting error after 30 seconds
Thanks!

A: These settings solved my problem of calls
Dante Server 1.4.2 (Ubuntu 16.04)
/etc/sockd.conf

logoutput: /var/log/socks.log
internal: 192.168.1.14 port = 8912
external: 192.168.1.14
socksmethod: username
user.privileged: root
user.notprivileged: nobody

client pass {
        from: 0.0.0.0/0 to: 0.0.0.0/0
        log: error connect disconnect
}

client block {
        from: 0.0.0.0/0 to: 0.0.0.0/0
        log: connect error
}

socks pass {
        from: 0.0.0.0/0 to: 0.0.0.0/0
        command: bind connect udpassociate bindreply udpreply
        log: error connect disconnect
}

socks block {
        from: 0.0.0.0/0 to: 0.0.0.0/0
        log: connect error
}
iptables -A INPUT -p udp -m multiport --dports 1024:65535 -j ACCEPT
With these settings, you can already call from the telegram client desktop.
In the telegram app In the proxy settings Disable the "Use for calls".

A: Add to your pass/socks pass section with client-rule "command:" content: bindreply, udpassociate and udpreply
https://www.inet.no/dante/doc/1.4.x/sockd.conf.5.html
command
              The rule applies to the given commands.  Valid commands are
              bind, bindreply, connect, udpassociate and udpreply.  Can be
              used instead of, or to complement, protocol.  The default is all commands valid for the protocols allowed by the rule.


text:
Q: How does this C code translate to MIPS instruction? I'm studying mips coding and have a solution to a given problem and I'm working to understand it and have defined each line to the best my knowledge, but I'm not picking up on a couple of lines on how they work mainly the last line with fib(n-1) + fib(n-2) how is that being returned? I see that after beq fails, and bne fails t1 is turned to 0 and exit is reached the value from t1 is stored to v0 for results/expressions and our (n) is reloaded before being deleted from the stack but I'm not quite seeing the fib(n-1) + fib(n-2) ? Help? Thank you!
C code:
int fib(int n){
if (n==0)
return 0;
else if (n == 1)
return 1;
else
fib(n-1) + fib(n–2);

NEW** answer/ transliteration I worked on

#

  #fib function
  loop:
  addi $sp, $sp, -4                 #creating item on stack -> int n given caller value
  sw $ra, 0($sp)                       #saving address to stack
  addi $t0, $zero, $zero               #temp 0 is given value of 0
  beq 0($sp), $t0, exit                #if equal return 0  (if (n == 0)
  addi $t1, $zero, 1                   #temp1 gets value of 1
  beq 0($sp), $t1, exit                #if equal return 0 (else if(n==0)
  lw $t2, 0($sp)                       #storing n to temp 2
  sub $t2, $t2, 1                      #n - 1
  lw $t3, 0($sp)                       #storing n to temp 3
  sub $t3, $t3, 2 #n-2
  add $t4, $t2, $t3                    # (fib(n-1) + fib( n-1)
  sw 0($sp), $s4                       #storing n's new value back to its original       location
  bne 0($sp), $zero, loop              #jump to loop function with new value of n
  exit: jr $ra                         #return value of register address to caller

//OLD***Partially correct answer but not correct transliteration for fibanocci
//---------------------------
compare:
addi $sp, $sp, –4 #add immediate adjusts stack for one more item
sw   $ra, 0($sp)  #saves return address on stack of our new item

add $s0, $a0, $0  #add, stores argument 0 + (0) to s0
add $s1, $a1, $0  #add, stores argument 0 + (0) to s1

jal sub           #jump and link to subtract

addi $t1, $0, 1   #add immediate, temp 1 = add 0 + 1
beq $v0, $0, exit #branch on equal, if value in 0 is equal to zero go to -> exit
slt $t2, $0, $v0  #set less than, if 0 < value at 0  then temp2 equals 1 else 0
bne $t2, $0, exit #branch on not equal, if temp2 not equal to zero go to -> exit
addi $t1, $0, $0  #add immediate, temp1 = 0 + 0

exit:
add $v0, $t1, $0  #add value at 0 = t1 + 0
lw $ra, 0($sp)    #loads register address from stack 0()
addi $sp, $sp, 4  #add immediate, deletes stack pointer pops it off stack
jr $ra            #jump register, return to caller from return address

sub:
sub $v0, $a0, $a1 #subtract, value at 0 = argument 1 - argument 2
jr $ra            #jump register, return to caller from return address

//

A: Neither version will work as suggested. I haven't tested the below code; but something like this should work (no error check (assumes $a0 non-negative); lenient procedure frame convention):
        .text
fib:  addi $sp, $sp, -24
      sw $ra, 16($sp)
      sw $a0, 20(sp)         # recursive calls will overwrite original $a0
      sw $s0. 0($sp)         # holds fib(n-1)
      # end prologue

      slti $t0, $a0, 4      # fib(i) = i for i = 1, 2, 3; fib(0) = 0 by C code
      beq $t0, $zero, L1
      addi $v0, $a0, 0      # see prior comment (assumes $a0 non-negative integer)
      j exit

      # fib(n) = fib(n-1) + fib(n-2)
L1:   addi $a0, $a0, -1
      jal fib
      addi $s0, $v0, 0       # $s0 = fib(n-1)
      addi $a0, $a0, -1
      jal fib                # upon return, $v0 holds fib(n-2)
      add $v0, $v0, $s0

exit: # unwind stack and return
      lw $s0, 0($sp)
      lw $a0, 20($sp)
      lw $ra, 16($sp)
      addi $sp, $sp, 24
      jr $ra


text:
Q: django formset and and initial data I have a simple model and a simple form. The form looks like this:
class AddForm(forms.Form):
    quantity = forms.IntegerField(label='', widget=forms.TextInput(attrs={'size':'2'}))
    product_id = forms.IntegerField(widget=forms.HiddenInput)

In my template there's a object_list containing all the model-objects.
What I want is: next to each model-object a form to enter the "quantity". The "product_id"-field has to have the id of each model as initial data.
I guess I have to use Formsets for this, but I don't understand how to set the initial data from database-data and how to make Formsets display a form for each model-object.
Thanks in advance
Jacques

A: As the form you want to add is so simple, it's easier just to add the product id in the template with something like
<input type="hidden" name="product_id" value="{{ object.id }}" />

rather than adding complicated formsets.


text:
Q: Is there any function to get the original coordinates of a point after a rotation? Imagine that I have an object, like a rectangle which is
width : 500
height : 200

the original coordinates are :
x = 300
y = 200

But if I applies an angle of 178.02° the coordinates are now :
x = 503.4
y = 396.48

My question is, just by knowing theses information, like the new position, the angle applied and the size of the object, is it possible to know where was the x and y point located before the rotation ?
Thanks


text:
Q: Intelligencia.UrlRewriter - using port other than 80 Does anyone know if it is possible to configure Intelligencia.UrlRewriter to work when accessing a site via a port other than 80?
eg http://mysite.com:70/default.aspx
Thanks

A: When writing your re-write rules, use ~/ convention

A: I think it's IIS you need to configure to listen on port 70; your re-write rules may be fine.


text:
Q: How to authenticate user using mobile number in Keycloak User has a custom attribute phoneNumber in Keycloak.
There is a default method for fetching token using username and password but would it be possible to authenticate using phoneNumber / password instead of username / password
curl \
  -d "client_id=$CLIENT_ID" -d "client_secret=$CLIENT_SECRET" \
  -d "username=$UNAME" -d "password=$PASSWORD" \
  -d "grant_type=password" \
  "$KEYCLOAKHOST/auth/realms/$REALM/protocol/openid-connect/token"

What call should I use to authenticate using a custom attribute in UserModel

A: After looking around it seems to me that you will not have that functionality provided by Keycloak out of the box. With the current Keycloak implementation it would not be feasible to use the :
curl \
  -d "client_id=$CLIENT_ID" -d "client_secret=$CLIENT_SECRET" \
  -d "phoneNumber=$PhoneNumber" -d "password=$PASSWORD" \
  -d "grant_type=password" \
  "$KEYCLOAKHOST/auth/realms/$REALM/protocol/openid-connect/token"

because neither does Keycloak itself check that the user attribute phoneNumber is a valid number nor does it check that it is a unique number. This last constrain is fundamental for obvious reasons, hence the reason why Keycloak enforces the usernames to be unique.
So you can try to extend Keycloak with that functionality, which was recently done in a production environment. Fortunately, the developer was nice enough to provide that functionality for others to implement, check this redhat blog post by the developer detailing the implementation.
However, if you only want to use the "default method for fetching " that you posted in the question, then what you can do is just say that the username itself has to be the mobile phone (similar to the WhatsApp approach), which is not as bad as it sounds because 1) Keycloak enforces that the usernames are unique, 2) Keycloak still has the fields first name and last name to identify by name the users.
Now the tricky part is to ensure that during the user registration, the user really inserts a valid phone number and not some random string. For that, you can either again extend the keycloak, and validated it there. However, if you are going this root you might as well use the feature from the RedHat blog post. Or manage the user registration with your own app, which would enforce the user to add a valid Phone Number by relying on some SMS security feature, and after the validation was performed, the app itself would register the user on Keycloak with the username field set to the user Phone Number.


text:
Q: any ways to rename auto complete parameters in android studio? I'm studying SQLiteOpenHelper in Android Studio.
There is a method
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {} that I have to override and the second and third parameters of this method are auto completed like this below.
onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1)
It's not a big problem but I would like the parameters to be completed with their original names like the one I mentioned.
The Android Studio auto complete seems to names the int parameters with just "i", but I don't really like it.
Are there any ways to change this?


text: Q: There are two circle in my xamarin form drawing using drawing using skiasharp. How can I put different touch event handler on both of this circle? I am trying to set different touch event on the circle drawing using skiasharp on my xamarin form. How can I do so? Is there any Id like android studio that I can use to track which circle am I pressing?


text:
Q: Unable to Set Developer Mode I have strange issue when I am trying to set developer mode on my website.
When I tried to set developer mode with CLI and also changed app/etc/env.php it gave an error:

Uncaught Magento\Framework\Exception\LocalizedException: Invalid Document Element 'plugin', attribute 'setOrder': The attribute 'setOrder' is not allowed. Line: 17 in /var/www/html/magento2/vendor/magento/framework/Config/Reader/Filesystem.php:160

While We have not changed any core files since recently I upgraded Magento to 2.1.8 version, but still issue not resolved.


text:
Q: .apk file generation from android-studio in ubuntu I have tried many of the times to generate .apk file from android-studio for my new application. and I am using android-studio in ubuntu. How to generate .apk file from android studio in ubuntu...? Not signed apk file.please help me..
advance Thanks

A: You just need to run your project and after that go to < your project location >/app/build/outputs/apk folder. There you will see app-debug.apk file.


text:
Q: Hard drive restore on reboot on windows embedded My company has an old out of service device with windows embedded on it that we want to re purpose.
Any changes to the drive (SD Card with 2 partitions), (ie: installed software, ip address, system settings, files) are reset/deleted when we reboot the device.
We can successfully make changes to the drive by plugging it into a PC, but that has its limitations and we would like to be able to use our device.
Can anyone tell us more about the technology used for doing this and how/if we can disable it?

A: Thin Client OEMs implement Windows XP Embedded's Enhanced Write Filter (EWF) tool to prevent write actions (and, therefore, flash-erase cycles) to the flash drive. All write actions are instead re-directed to the RAM disk (also known as the overlay).
To make any changes to the OS, such as domain connectivity or a TCP/IP static address change, you can disable EWF to allow the update to occur, and then re-enable it.
more you can read here http://msdn.microsoft.com/en-us/library/dd143259%28v=winembedded.5%29.aspx
Only Administrator accounts can access EWFMGR.EXE and the EWF API. Power User, User, and Guest accounts cannot change the state of EWF.
As an example, after you have set up your IP address and/or other system settings, you can try to run this command.
ewfmgr c: -commitanddisable -live
This commits all current level data in the overlay to the protected volume and disables the overlay.
The overlay is written to the protected volume on the next system boot. Committing the overlay can impact the speed of the boot process.
You can use the -live command for both EWF RAM and EWF RAM Reg modes to immediately commit the overlay to the protected volume and disable the overlay without having to reboot the system.
To disable EWF:
ewfmgr disk: -disable, however be aware, the longevity of flash drives is an issue, though. Both Windows XP Pro and Windows XP Embedded constantly read from and write to a disk, resulting in numerous flash erase cycles. Because both CompactFlash and mini-IDE flash drives have a limited number of these cycles, they wear out more quickly than they would if used as they would in a normal commercial environment.
More about commands/options you can read here: http://msdn.microsoft.com/en-us/library/ms940853%28v=winembedded.5%29.aspx


text:
Q: Why iptables block my port 80 traffic? I've setup a configuration on iptables to allow only the traffic I need. I opened the port 80... but with iptables enabled, I cannot reach my site.
This is the configuration... Where I've made some mistake?
-A INPUT -i eth0 -p tcp --dport 80 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p tcp --dport 80 -m limit --limit 25/minute --limit-burst 100 -j ACCEPT
-A OUTPUT -p tcp --dport 80 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT
-A INPUT -i eth0 -p tcp --dport 22 -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p tcp -m tcp --dport 10000 -j ACCEPT
-A INPUT -i eth0 -p tcp --dport 22 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT
-A INPUT  -p tcp -m tcp --dport 21 -m conntrack --ctstate NEW,ESTABLISHED,RELATED -j ACCEPT
-A INPUT  -p tcp -m tcp --dport 20 -m conntrack --ctstate NEW,ESTABLISHED,RELATED -j ACCEPT
-A INPUT  -p tcp -m tcp --sport 1024: --dport 1024: -m conntrack --ctstate NEW,ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp --icmp-type echo-request -j ACCEPT
-A INPUT -p icmp --icmp-type echo-reply -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp --sport 21 -m state --state ESTABLISHED -j ACCEPT
-A INPUT -p tcp --sport 20 -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p tcp --sport 1024: --dport 1024: -m state --state ESTABLISHED -j ACCEPT
-A OUTPUT -p tcp --dport 21 -m state --state NEW,ESTABLISHED -j ACCEPT
-A OUTPUT -p tcp --dport 20 -m state --state ESTABLISHED -j ACCEPT
-A OUTPUT -p tcp --sport 1024: --dport 1024: -m state --state ESTABLISHED,RELATED,NEW -j ACCEPT
-A FORWARD -i eth0 -o eth1 -j ACCEPT
-A OUTPUT -i eth0 -p tcp --dport 22 -m state --state ESTABLISHED,RELATED -j ACCEPT
-A OUTPUT  -p tcp -m tcp --dport 21 -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
-A OUTPUT  -p tcp -m tcp --dport 20 -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
-A OUTPUT  -p tcp -m tcp --sport 1024: --dport 1024: -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p udp -i eth0 --sport 53 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -o eth0 -j LOG --log-level 7 --log-prefix BANDWIDTH_OUT:
-A FORWARD -i eth0 -j LOG --log-level 7 --log-prefix BANDWIDTH_IN:
-A OUTPUT -o eth0 -j LOG --log-level 7 --log-prefix BANDWIDTH_OUT:
-A INPUT -i eth0 -j LOG --log-level 7 --log-prefix BANDWIDTH_IN:
-P INPUT DROP
-P FORWARD DROP


text:
Q: Java: Objects in JFrame are messed up I'm creating a simple Java JFrame in Eclipse with a label, 2 radio buttons with 2 textfields, and a JButton. When i run the program, the objects inside it are messed up, the buttons and textfields don't show up and sometimes a textfield takes the entire size of the frame. However, when I minimize/maximize the frame and then restore it, they work normally. Here's the code:
   import java.awt.BorderLayout;
   import java.awt.Dimension;
   import java.awt.event.ActionEvent;
   import java.awt.event.ActionListener;
   import java.awt.event.WindowAdapter;
   import java.awt.event.WindowEvent;

   import javax.swing.BorderFactory;
   import javax.swing.Box;
   import javax.swing.BoxLayout;
   import javax.swing.JButton;
   import javax.swing.JFrame;
   import javax.swing.JLabel;
   import javax.swing.JPanel;
   import javax.swing.JRadioButton;
   import javax.swing.JTextField;

   public class myframe {

   public static void main(String s[]) {
    JFrame frame = new JFrame("Title");
    frame.addWindowListener(new WindowAdapter() {

        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });
    // This is an empty content area in the frame
    JLabel jlbempty = new JLabel("");
    jlbempty.setPreferredSize(new Dimension(500, 400));
    frame.getContentPane().add(jlbempty, BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
    frame.setBounds(0, 0, 500, 400);

JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.NORTH);
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.add(Box.createRigidArea(new Dimension(0,5)));
panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));

JLabel label = new JLabel("My label");
panel.add(label);

JPanel buttonPane = new JPanel();
frame.add(buttonPane);
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
buttonPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JRadioButton cb = new JRadioButton("1");
buttonPane.add(cb);
JTextField tf = new JTextField(0);
tf.setText("");
buttonPane.add(tf);

JPanel panel3 = new JPanel();
frame.add(panel3);
panel3.setLayout(new BoxLayout(panel3, BoxLayout.LINE_AXIS));
panel3.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JRadioButton cb2 = new JRadioButton("2");
panel3.add(cb2);
JTextField tf2 = new JTextField(0);
tf.setText("");
panel3.add(tf2);

JPanel panel2 = new JPanel();
JButton button = new JButton("click me");
frame.add(panel2);
panel2.add(button);
button.addActionListener(new Action());

panel.add(buttonPane);
panel.add(panel3);
panel.add(panel2);
    }

static class Action implements ActionListener{

    public void actionPerformed(ActionEvent arg0) {
        JFrame frame2 = new JFrame("Clicked");
        frame2.setVisible(true);
        frame2.setSize(100, 200);
        JLabel label2 = new JLabel("You clicked me");
        JPanel panel2 = new JPanel();
        frame2.add(panel2);
        frame2.add(label2);

    }

}
}

A: In your main method you need to do this at the very end:
frame.pack();
frame.setVisible(true);

A: You should call frame.pack(); again after adding all the components, so that all the container elements can resize to fit their components best.
http://docs.oracle.com/javase/7/docs/api/java/awt/Window.html#pack()
You should also call frame.SetVisible(true); at the very end, so the form is only displayed ones all components are loaded (otherwise you can see a black box while it loads).


text:
Q: adding alternative class for sets of items in angular loop?
how can I add two classes alternatively for three three sets of items in ngFor angular. Please refer image.

A: You could use the following. Where i is the index in loop.
*ngFor="let i of [1,2,3,4,5,6,7,8,9]"
[style.background-color]="check(i) ? 'red' : 'green'"

check(i: number) {
        return Math.floor(i / 3) % 2;
}


text:
Q: Straightforward explanation of Theil inequality statistic for curve fitting I've come across a paper (here) that uses a "Thiel inequality statistic" (pages 9 and 10 of the supplementary information) to determine goodness of fit for a model with its training data. I was wondering if you might be able to point me towards a straightforward explanation of how it works, and how it could be used in this context?
They also use a simple root-mean square error, does the Thiel statistic add anything that RMSE doesn't?
I'm sorry if this is a lame question, please do let me know if you need any other information for it to make sense.


text:
Q: Create a Synthetic Vision System I would like to add this feature to my android app:
https://en.wikipedia.org/wiki/Synthetic_vision_system
In short it I believe it is a terrain heightmap.  I specifically need help with rendering the terrain.  The rest of the display I can accomplish.
After a day of google I appear to be no closer.   My research seems to point to using opengl, heightmaps and SRTM. However I have no clue how to tie it all together.   None of the java examples are android specific.
Alternatively maybe using openstreetmaps and a tile overlay but I cant establish if it is possible in 3D.
The app will be a moving map based on GPS position of the aircraft.  As the aircraft moves over the earth the terrain ahead will be updated.
Can someone point me in the right direction?

A: I can recommend you to use a vector format with few layers. For example, layer of depth, layer of landscape type and layer of objects. To build 3D from this data you need to divide the map in small tiles and load data in memory for visible area only. Your 3D builder will parse this data. E.g. a simple renderer (using OpenGL)... You create mesh as large as tile size and with enough count of vertexes. Next, you parse depth layer and move each vertex along Z-axis like it need. After you need to set color like it specified in type layer. And finally, you need create and locate objects like object layer data (it's already built-in meshes). When you build needed tiles you pass it to renderer.


text:
Q: Why can't I display chars properly in C++ WinForms Message Box? So I'm having trouble concatenating strings and chars and then displaying them using the message box because my characters get printed as numbers, and when I try to convert them to string no matter where or how the message box throws an error! Any help is appreciated!
MessageBox::Show("The most common letter is \"" + letters[biggetsNumberIndex] + "\".");
// Simplified version: MessageBox::Show("string" + 'c' + "string");

A: I managed to fix it thanks to "Jimi" I changed the "letters" variable instead of character array or std::string I used String^
// Bad
std::string letters = "abcdefghijklmnopqrstuvwxyz";

// Good
String^ letters = "abcdefghijklmnopqrstuvwxyz";


text:
Q: How should I deal with the error message of "fatal error U1077, return code '0x2' as I compiled libf2c? Language & Platform version: Microsoft Visual C++ 2010 Express
Operating system : Windows 10
Relevant software: Ipopt-3.9.3
I'm trying to compile libf2c related to Ipopt-3.9.3, I open a Visual Studio DOS prompt and go into the directory and type the command as follows:
cd C:\Ipopt-3.9.3\Ipopt\MSVisualStudio\v8\libf2c
nmake -f makefile.vc all
Then, there displayed the following error messages.
Arithchk.c
Arithchk.c(240): error C2065:'ssize_t": undeclared identifier
Arithchk.c(242): error C2065:'ssize_t":underclared identifier
NMAKE: fatal error U1077: ' "C:\Program File(x86)\Mircrosoft Visual 10.0\VC\BIN\cl.EXE"';
return code '0x2' Stop

The following is the .h files  included in arithchk.c
#include<string.h>/*possibly for ssize_t */
#include<sys/types.h>/* another possible place for ssize_t */

row 239 to 242 of the codes are as follows
#else /*}{*/
if (sizeof(size_t)!=sizeof(ssize_t))
fprintf(f,"/*sizeof(size_t)=%d but sizeof(ssize_t)=%d */\n",
(int)sizeof(size_t),(int)sizeof(ssize_t));

Since I'm just an initiate, I don't know how to correct row 240 and 242, and expect for your aid.
Thank you very much for your attention, and I'm looking forward to your kind help!

A: I've downloaded another version of arithchk.c related to libf2c from this site http://josephsmith.numis.northwestern.edu/cgi-bin/sempercvs.cgi/f2c/libf2c/arithchk.c?revision=1.2&view=markup, and then everything goes well.


text:
Q: Angular 2 support IE9? Does anyone knows what magics need to do for running application in IE9 browser?
Because even quick start application from angular.io doesn't run there. If it possible show source code of index.html and package.json files or other necessary things.

A: Maybe you have a typo similar to What is required to use Angular 2 within IE9?
For me the boilerplate from https://github.com/mschwarzmueller/angular-2-beta-boilerplate which is based on that quick start application worked also with IE9 (version on the machine I tested with is 9.0.8112.16421).


text:
Q: Adding jquery plugin to joomla 2 I am trying to add a country selector to the front page of my site for the users to be able to select a country and land on a specific page. I have not been able to find a Joomla extension for this, but I found a jquery plugin that does this, but I am not sure how to or is there a way to add this to my Joomla site.
The jquery plugin

A: There are multiple ways to do that:

*

*http://extensions.joomla.org/extension/jquery-easy
Install a plugin to include jQuery in

b. http://dabrook.org/blog/two-ways-to-include-jquery-in-your-document
  Do that for joomla template file (don't forget jQuery.NoConflict())
And at the and modify article with that country picker (put JS code in).
OR
Develop a plugin to do all that. (for more experienced user)