Is the following bash script correct?

Question: what's wrong in the following code?
while read -r -u 3 line1 && read -r -u 4 line2
do
    if [ $line2 = "moon" ] #can i do this?
       echo "hi"
    fi
done
done 3<file1 4<file2

file1 and file2 are text files and script is part of a larger scrit.  The error I am getting is syntax error near unexpected token elif [[ "$line2" = "moon" ]].
Comment: Are you using single brackets or double brackets? If double brackets, make sure you script is run by `bash`; `sh` doesn't recognize the double-bracket expression. More generally, your error message doesn't match the code you posted, which doesn't have an `elif` clause.
Comment: why is there two "done" at the end?
Answer: if [[ "$line2" = "moon" ]];
then
echo "hi"
fi

Always quote string variables while doing string operation.
And [[ ]] is a better option.
Read about it here and here
Comment: @user2613272, it's still an interpreted variable whether or not it has those quotes. The quotes protect against problems sometimes encountered with empty strings.
Comment: line2 is a variable not a string
Comment: The conditional expression doesn't require parameter expansions to be quoted, as it doesn't perform word expansion in that setting.
Answer: What is the point of script? The script can only be verified against a specification. Does it do what you want? Does it give you an error?
The main issues I see if that you are reading from two files but only using the second. It's seems your script could be replaced by:
$ grep -qF "moon" file2 && echo "hi"

Comment: And we are meant to know that how? This kind of information is necessary, please read http://stackoverflow.com/help/asking B.T.W The error message you post doesn't match the script you posted!?
Comment: actually , it's part of my script ,it's part of elif so the error is syntax error near unexpected token elif [[ "$line2" = "moon" ]]

Is the following bash script correct?


Dismiss ViewController which was programmatically presented in ViewController nested in NavigationController crashes, but not every time

Question: When i try to dismiss a ViewController which was presented programmatically in a ViewController which is nested in a NavigationController i seem to get a
libc++abi.dylib: terminating with uncaught exception of type NSException
every once in a while without further information given.
My ViewController which is presented modally above the nested one:
class RefreshController: UIViewController {

@IBOutlet var label: UILabel!
@IBOutlet var main: UIView!
@IBOutlet var spinner: UIActivityIndicatorView!

override func viewDidLoad() {
    super.viewDidLoad()

    spinner.startAnimating()
    label.text = .localized("refreshing") + " ..."

    main.layer.cornerRadius = 5
}

public func hideRefresh(_ contr: UIViewController, completion: @escaping (() -> Swift.Void)){
    contr.presentedViewController?.dismiss(animated: true, completion: {
        refreshController = nil
        completion()
    })
}

class func showRefresh(_ contr: UIViewController!, completion: @escaping (() -> Swift.Void)){
    refreshController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "refreshController") as! RefreshController

    contr.present(refreshController, animated: true, completion: {
        completion()
    })
}
}

I have a global variable refreshController which defines itself as the currently presented controller when it is shown to access it at every time.
In the nested ViewController i call:
refreshController.hideRefresh(self, completion: {
//code goes here, after the controller dismissed
}

(The completion part is due to the animations, which sometimes conflicts with UIAlerts which should be presented)
Does anyone has experiences with this? Or is it just a bug in the latest iOS 10.2 (14C82) beta?
Answer: Call dismiss on the presenting viewController, not on the presented one:
public func hideRefresh(_ contr: UIViewController, completion: @escaping (() -> Swift.Void)){
    // instead of contr.presentedViewController?.dismiss...
    contr.dismiss(animated: true, completion: {
        refreshController = nil
        completion()
    })
}

Comment: I got it working, i think it was due to the order of calls


Javascript - Lodash / Underscore compare two objects and change values based on their keys

Question: There is a small problem
I need to compare two objects, and based on the same keys in these objects pass values from second object to the original object.
Original object
<code>{
   content: "Old Value",
   height: 200,
   id: "15a2d286-d123-1cf0-4e40-b043b055a49f",
   type: "location",
   units: "some unit value",
   width: 200,
}
</code>
Second object
<code>{
   units: "some unit value",
   content: "New Value"
}
</code>
Keys is not necessary to check for compliance
The output will be something like that
<code>{
   content: "New Value", // changed value
   height: 200,
   id: "15a2d286-d123-1cf0-4e40-b043b055a49f",
   type: "location",
   units: "some unit value", // changed value
   width: 200,
}
</code>
Is there any elegant solution to this problem with Lodash or Underscore?
Comment: What is your comparison based on? The `units` value?
Comment: Seems like you just want to merge two objects?
Answer: this will do the trick (using lodash)
<code>var source = {
  content: "Old Value",
  height: 200,
  id: "15a2d286-d123-1cf0-4e40-b043b055a49f",
  type: "location",
  units: "some unit value",
  width: 200,
},
source2 = {
  units: "some unit value",
  content: "New Value"
}
_.assignIn(source , source2 );
</code>
Comment: if i may ask, what is the difference between _.assignIn and _.merge ? for , _.merge(source,source2)  seems to do the same thing !


Como remover linhas de uma tabela A que não possui relacionamento com a tabela B?

Question: Tenho 2 tabelas e quero remover as linhas da tabela A que não possui relacionamento com a tabela B?
Por exemplo: Na tabela B eu tenho um campo FK_ID e quero remover da tabela A todos as linhas que não tem relacionamento com a tabela B, ou seja, que não possui um A.FK_ID = B.FK_ID
Answer: Essa é uma maneira de fazer:
DELETE FROM TABELA_A where TABELA_A.FK_ID not in (select FK_ID FROM TABELA_B)

Answer: Usando NOT EXISTS
DELETE t_a
  FROM a t_a
 WHERE NOT EXISTS(SELECT 1
                    FROM b t_b
                   WHERE t_b.fk_id = t_a.fk_id)

Usando JOIN
DELETE t_a
  FROM a t_a
  LEFT JOIN b t_b ON t_b.fk_id = t_a.fk_id
 WHERE b.fk_id IS NULL


How to add a Signature to a File?

Question: I am coding at the moment a File Signature Program which should implement a file signing via a smart card.
I have already implemented most of it, the file readout, the algorithm, the key calculation e.g.
Now I have the problem, I have created the signature (which I have as byte array) and can export this signature as file.
But how do I actually sign the original file and adding the signature to the file ? (like a signed pdf file)
I already searched on google but didn't found anything, maybe you guys can help me.
Hoping for fast answers
Comment: The PDF specification is [ISO 32000](http://www.iso.org/iso/catalogue_detail.htm?csnumber=51502), if you want to produce a single PDF that's "signed" per the specification.  Adobe hosts a copy of the ISO specification for free download, as of Aug 2016 at http://www.adobe.com/content/dam/Adobe/en/devnet/acrobat/pdfs/PDF32000_2008.pdf
Answer: There are 2 common ways to process signed files. The most general one is to simply put the signature file near to the original file in a distinct file with same name and a .sig, .md5 or .sha extension. The original file is left untouched, so it can be used for any file format.
Some file formats come with an integrated signature protocol. PDF is indeed an example of those: you take the hash of the data part, and write it in a special location in the file. Simply any software able to process this file must be aware of the signature feature and either control it or at least ignore it. Other file formats base on a zip archive could simply add the signature as a new component of the zip. For NTFS files, you could also add a new stream to contain the signature, but you would no longer be able to transfer it on a non NTFS support, nor with anything else than a Windows file copy, because ordinary protocols only process the main stream of a NTFS file.
TL/DR: the simplest way is to store the signature in a distinct file in same folder with almost same name but with a special extension, for example .sig
Comment: ok, so basically i can't sign every file type and have this 2 different approaches.... well.... i don't have any definition what files i have to sign so first part should be the good way for me. thanks

How to add a Signature to a File?


Angular JS form submission issue

Question: I want to add an entry to my reviews array.
 Submit a review
        <form name="submitReviews" ng-controller="ReviewController as reviewCtrl" ng-submit="reviewCtrl.addReview(product)">

                Stars : {{reviewCtrl.review.stars}}
                {{reviewCtrl.review.body}}
                by: {{reviewCtrl.review.author}}

            <select ng-model="reviewCtrl.review.stars">
                <option value="1">1 Star</option>
                <option value="2">2 Star</option>
                <option value="3">3 Star</option>
                <option value="4">4 Star</option>
                <option value="5">5 Star</option>
            </select>
            <textarea ng-model="reviewCtrl.review.body">
            </textarea>
            by:
            <input ng-model="reviewCtrl.review.author" type="email" />
            <input type="submit" value="Submit Review" />
        </form>

The js file :
app.controller('ReviewController', function($scope) {
    $scope.review = {};

    $scope.addReview = function (product) {
        product.reviews.push($scope.review);
        $scope.review = {};
    };
});

The array to while I want to add(the complete object structure):
 var gems = [{
    //First gem
    name: "Dodecahedron",
    price: 2.95,
    description: "great stone",
    specification: "Very Expensive, hand crafted, African made",
    reviews: [{
        stars: 5,
        body: "test review1",
        author: "firstname.lastname@example.com",
    },
        {
            stars: 3,
            body: "not worth the price.",
            author: "firstname.lastname@example.com"
        }],
    canPurchase : true,
    soldOut: false,
    image: [
        { image1 :  "Images/img1.jpeg" },
        { image2 :  "Images/img2.jpeg" }
    ]
}

I can see all the information before the form correctly(images and current reviews predefined in the array). When I submit a new review from the HTML page, it should be added to the existing reviews(arr.push). This is not happening.
This controller(ReviewController) is nested inside another controller. Dont know if that make a difference.
Comment: I think you need to declare product.reviews as an array as product.reviews=[ ]; try this
Answer: It looks like your form is posting and reloading the page. Pass $event into your submit handler and call $event.preventDefault() or return false
 ng-submit="addReview($event, product)"

then...
$scope.addReview = function ($event, product) {
    $event.preventDefault();
    // ...
};

Comment: I understand what you are saying, since I am not saving this value anywhere, i would disappear on a page refresh. I tried your way but does not seem to work.
Answer: Try to use not scope, but contoller itself in your controller code.
Use this.reviews, instead of $scope.reviews. you are using controller as syntax, so use controller instance to store variables.
Comment: ##This is not working as well
    app.controller('ReviewController', function() {
        this.review = {};

        this.addReview = function (product) {
            product.reviews.push(this.review);
            this.review = {};
        };
    });
Comment: Hard to work without your code on plunker. Try to not clean the review after adding it to the array, may be it clears in the array after adding it.
Answer: I feel the ng-submit is not invoking your addReview() method. Check this first.
If that is the case then you can try the below
As you are using the controllerchange your code in js to below($scope to this). Also the ng-model you are using is reviewCtrl.review so use the same here as well
 this.addReview = function (product) {
    product.reviews.push($scope.reviewCtrl.review);
    $scope.reviewCtrl.review = {};
};

Answer: HTML:
Submit a review
<form name="submitReviews" ng-controller="ReviewController as reviewCtrl" ng-submit="reviewCtrl.addReview()">

        Stars : {{reviewCtrl.review.stars}}
        {{reviewCtrl.review.body}}
        by: {{reviewCtrl.review.author}}

    <select ng-model="reviewCtrl.review.stars">
        <option value="1">1 Star</option>
        <option value="2">2 Star</option>
        <option value="3">3 Star</option>
        <option value="4">4 Star</option>
        <option value="5">5 Star</option>
    </select>
    <textarea ng-model="reviewCtrl.review.body">
    </textarea>
    by:
    <input ng-model="reviewCtrl.review.author" type="email" />
    <input type="submit" value="Submit Review" />
</form>

controller:
app.controller('ReviewController', function($scope) {
    $scope.review = {};

    $scope.addReview = function () {
        var review = angular.copy($scope.review);
        // assuming gems is a global variable
        gems.reviews.push(review);
        $scope.review = {};
    };
});

I hope this helps :)

Angular JS form submission issue


How can a set be bounded and countably infinite at the same time?

Question: There is a theorem in my textbook that states,

Let $E$ be a bounded measurable set of real numbers. Suppose there is a bounded countably infinite set of real numbers $\Lambda$ for which the collection of translates of $E$, $\{\lambda + E\}_{\lambda \in \Lambda}$, is disjoint. Then $m(E) = 0$.

I'm a little confused about this theorem, because it's saying that a set is bounded and countably infinite at the same time. But if a set is bounded, isn't it supposed to be finite?
Thanks in advance
Answer: The set $\{2^{-k}\ |\ k \in \mathbb{Z}^+\}$ is bounded and countably infinite.
Answer: Hint: Consider $\Bbb Q$ intersected with any bounded set, finite or infinite. Since $\Bbb Q$ is countable, the new set is at most countable, and clearly can be made infinite; for example, $[0,1]\cap\Bbb Q$ is bounded and countable.
Answer: No: $[0,1]$ is a bounded set that isn't even countable, let alone finite. An unbounded set of real numbers is necessarily infinite, but a bounded set can be of any size up to and including the cardinality of the entire set of real numbers.
To prove this, use the well-known fact, proved in several places on this site, that there is a bijection $\varphi:\Bbb R\to(0,1)$. Let $A$ be any subset of $\Bbb R$; then $\varphi[A]$ is a subset of $(0,1)$ of exactly the same cardinality, and every subset of $(0,1)$ is bounded.


How to calculate the integral $\int\limits_0^{\pi} \ln(1-2\alpha\cos{x}+\alpha^2) dx$?

Question: How to calculate the integral $\int\limits_0^{\pi} \ln(1-2\alpha\cos{x}+\alpha^2) dx$ by Fourier Series?
I have $\dfrac{q\sin{x}}{1-2q\cos{x}+q^2}=\sum\limits_{n=0}^{\infty} q^n\sin{nx} (q<1)$ now, I tried term wise integration but I cannot figure it out.
The answer is $0$ if $|\alpha|\leqslant 1$, $2\pi\ln|\alpha|$ if $|\alpha|<1$.
Comment: See here also: http://mathimatikoi.org/old/index.php/int_%7B0%7D%5E%7B-pi%7D-ln%5E2-left-a%5E2-2a-cos-x-1-right-dx-topic-moved
Comment: @Rohan - the OP explicitly asks for by by Fourier Series.
Answer: We can recognize the cosine law in the argument:
$$1-2\alpha \cos\phi + \alpha^2 = |1-\alpha e^{i\phi}|^2.$$
Then you have $z=\alpha e^{i\phi}$, $\ln |1-z|^2=2 Re \ln (1-z)$, use the series for log (under condition $|z|<1$ for which the series converges):
$$\ln(1-2\alpha \cos \phi + \alpha^2)=2 \operatorname{Re} \ln (1-z) =2\operatorname{Re}\sum_{n=1}^\infty \frac{z^n}{n}=2 \sum_{n=1}^\infty\frac{\alpha^n \cos n\phi}{n} $$
where the last step was just using the Euler's formula and taking the real part.
But this is precisely the Fourier series of the integrant, which you can integrate term-wise and get zero because you are integrating cosine over a symmetric interval (over a whole period or over half-period from max to min value).
The above series for logarithm only works for $|z|<1$ (the convergence radius). For $|z|>1$, you have to transform the logarithm differently:
$$\ln |1-z|=\ln |z-1|=\ln(|z||1-z^{-1}|)=\ln|z|+\ln|1-z^{-1}|$$
The first term is a constant, equal to $\ln \alpha$, and the second term leads to the same cosine integrals which lead to zero. So we can ignore the second term and just get
$$\int_0^\pi 2 \ln |\alpha|d\phi+0=2\pi \ln |\alpha|$$


accessing element attributes with mootools selector

Question: I'm trying to attach a mouseover event to all img elements of a gallery in a page (using Mootools). This is easy enough using something like
$$('img.mygalleryclass').addEvents({
mouseover: function(){
    alert(id);
    }
});

My question is, how do I alert the id of the element referenced in the $$ 'loop'? That "alert(id)" returns an error every time since id is not defined.
Thanks!
Answer: Pass the event argument to the mouseover function and then get the id of the target:
$$('img.mygalleryclass').addEvents({
    mouseover: function(e) {
        alert(e.target.id);
    }
});

Here's an example.
Comment: `this.get("id")` or just `this.id` - in bound callbacks in mootools, `this` is referencing the element that triggers the event (this === e.target)
Comment: Does MooTools really not bind "this" to the element?
Comment: @sdleihssirhc-- you're right too, it does bind this, so I can use this.id as well.


Android ServiceTestCase for IntentService

Question: I'm currently writing unit tests for an android application and stumbled into the following issue:
I use the ServiceTestCase to test an IntentService like this:
@Override
public void setUp() throws Exception {
    super.setUp();
}

public void testService()
{
    Intent intent = new Intent(getSystemContext(), MyIntentService.class);
    super.startService(intent);
    assertNotNull(getService());
}

However I noticed that my IntentService is created (means that onCreate is called) but I never receive a call into onHandleIntent(Intent intent)
Has anyone already tested an IntentService with the ServiceTestCase class?
Thanks!
Comment: I'm also testing an IntentService and apparantly it isn't setUp properly by the Android Test Framwork. I see no other reason why my tests fail too. http://stackoverflow.com/questions/6975348/strange-nullpointer-exception-in-android-test-case
Answer: This is a bit late, but I just struggled with this. You could solve this by creating a class that simply overrides the onStart of you service so it calls onHandleIntent directly. So for instance, if you have a LocationUpdaterService, you could create a fake class that overrides the onStart function like this:
public class LocationUpdaterServiceFake extends LocationUpdaterService {

@Override
public void onStart(Intent intent, int startId) {
    onHandleIntent(intent);
    stopSelf(startId);
}

LocationUpdaterService is a subclass of IntentService, so when you write your tests, just use the LocationUpdaterServiceFake class like this
public class LocationUpdateServiceTest extends ServiceTestCase<LocationUpdaterServiceFake> {

public LocationUpdateServiceTest()
{
    super(LocationUpdaterServiceFake.class);
}

public void testNewAreaNullLocation()
{
    Intent intent = new Intent();
    intent.setAction(LocationUpdaterService.ACTION_NEW_AREA);

    startService(intent);
}

}
Now whenever you call startService, it will bypass the threading code in IntentService and just call your onHandleIntent function
Answer: I just got started into testing my own IntentService and it's proving to be a bit of a headache.
Still trying to work things out but for the scenario where it seems that you do not receive a call to your method onHandleIntent(), (I'm not very good with the technicalities behind junit so forgive my use of terminology) it should be because the test framework, based on your code, actually tears down or end the test method once your call to startService returns. There is insufficient time for onHandleIntent to be triggered.
I verified the above theory by adding an infinite loop within my test case - only then can I see my log statements in onHandleIntent logged.
Comment: You're right, actually the service doesn't start correctly if the unit test is teared down. I fixed it by adding a `Thread.sleep`to the test and periodically check for the service's result.
Comment: I'm currently on the path of using semaphores, but it gets rather clumsy when it comes to knowing when to release the semaphore for the test to be teared down when using IntentService with ResultReceiver. Maybe I should consider using Thread.sleep too
Answer: You just have to add a:
Thread.sleep(XXXXXXX);

Choose the XXXX after the startService, then it will let the thread go into the onHandleIntent method.
Answer: In Android Studio 1.1, when running tests using the Run/Debug Configuration | Android Tests facility on any unit under test code (UUT) that extends IntentService, the ServiceTestCase.java (JUnit?) code does not call onHandleIntent(Intent intent) method in the UUT.  ServiceTestCase only calls onCreate so the problem is in the test code.
protected void startService(Intent intent) {
    if (!mServiceAttached) {
        setupService();
    }
    assertNotNull(mService);

    if (!mServiceCreated) {
        mService.onCreate();
        mServiceCreated = true;
    }
    mService.onStartCommand(intent, 0, mServiceId);

    mServiceStarted = true;
}

In my file smSimulatorTest.java:
public class smSimulatorTest extends ServiceTestCase<smSimulator>

At this point, I'm looking for other solutions in the testing framework that test UUTs through Intents since this is how IntentService is instantiated.
http://developer.android.com/reference/android/app/IntentService.html - To use it, extend IntentService and implement onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.
I, like others, put my code in the onHandleintent() as directed by the above documentation, however, ServiceTestCase only tests onStart and onStartCommand has shown above.
Answer: This is my approach for now:

The start Intent that invokes the service specifies the Service method to test

public void test_can_do_the_work() {
    Intent startIntent = new Intent();
    startIntent.putExtra("IN_TEST_MODE", "TEST_SPECIFIC_METHOD");
    startIntent.setClass(getContext(), MyServiceToTest.class);
    startService(startIntent);
    assertNotNull(getService()); // Your assertion Service specific assertion
}

In the service onStart, we check for the specific Extra passed and call the method to test. This won't execute when Handle intent fired.

@Override
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);
    String in_test_mode = intent.getStringExtra("TEST_SPECIFIC_METHOD");
    if(in_test_mode != null){
        doServiceWork();
    }
}


As we can pass integer from razor page to controller by asp-route-id , how can we pass a string instead?

Question: With the help of anchor tag
 hyperlink

it provokes the following in C#
controller-name/method-name/1

but how can I achieve the following?
controller-name/method-name/string

Comment: You need to use string variable as a parameter to the api endpoint
Comment: i would appreciate if u please elaborate how to pass string as a parameter ? @PrasadTelkikar
Comment: @AsadMirza just put a string variable in it `asp-route-id="string"`. In fact, parameters in url are all string.
Comment: @mj1313 yes u r right , thanks , sorry for late reply
Answer: Firstlt,the default data format of string in url is controller-name/method-name/1 If you want to get string in action,you only need to use string Id rather than int Id.Here is a demo:
View:
 hyperlink

url:
https://localhost:xxxx/Test/Method/1?name=name1

Controller:
public IActionResult Method(string Id, string Name) {
            return Ok();
        }

result:
Comment: thanks dear for your brief reply , sorry could nt reply earlier ...


Open and show windows command prompt to user inside Qt application

Question: How would I go about opening the windows command prompt, then sending a command to it and showing it to the user inside my Qt application?
I know you can send commands to the command prompt and get output behind the scenes without showing the command prompt to the user, but I want the user to be able to interact with the command prompt window and send their own commands.
Answer: Found what I needed:
<code>QProcess CommandPrompt;
QStringList Arguments;

Arguments << "/K" << "echo" << "hello";
CommandPrompt.startDetached("cmd",Arguments);
</code>


Fiware Context Broker: can we subscribe to all the context updates?

Question: I am using Fiware cygnus to subscribe to orion context broker entities.
Is it possible to subscribe to all the context updates with one script?
I dont want to do it one by one.
Here is an example of subscription:
(curl 192.168.1.79:1026/v1/subscribeContext -s -S --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'Fiware-Service: test' --header 'Fiware-ServicePath: /testPath' -d @- | python -mjson.tool) <<EOF
{
    "entities": [
        {
            "type": "room",
            "isPattern": "false",
            "id": "temperature"
        }
    ],
    "attributes": [
        "tmpValue"
    ],
    "reference": "http://192.168.1.40:5050/notify",
    "duration": "P1M",
    "notifyConditions": [
        {
            "type": "ONCHANGE",
            "condValues": [
                "tmpValue"
            ]
        }
    ],
    "throttling": "PT1S"
}
EOF

Answer: You can subscribe to changes in any entity using the following:
{
    "entities": [
        {
            "type": "",
            "isPattern": "true",
            "id": ".*"
        }
    ],
    "attributes": [ ],
    "reference": "http://192.168.1.40:5050/notify",
    "duration": "P1M",
    "notifyConditions": [
        {
            "type": "ONCHANGE",
            "condValues": [
                "tmpValue"
            ]
        }
    ],
    "throttling": "PT1S"
}

Doing so, the notification willl include all the attributes of the entity and it is generated each time the tmpValue attribute changes. Currently (Orion 0.23.0) you cannot subscribe to changes in any attribute (you need to know the list of attributes to monitor at subscription time) but it is planned as a future feature.
EDIT: since Orion 0.27.0 you can subscribe to changes in any attribute. In order to do so, do the subscription omitting the condValues field (or use an empty array [] as value).
Comment: Any updates on this feature (to subscribe to all orion entities from cygnus)? is  there a fixed release on which it will be implemented? Thanks!
Comment: So Orion cannot talk automaticaly to cygnus? Example : IoTAgent and orion. All devices and value changes are sent to Orion from the IoTAgent automatically. Just by configuring the Context Broker ip in IoTAgent.
Comment: Orion can "talk" to Cygnus using NGSI10 notifications as long as the subscriptions that enable such notifications are configured and coherent with the entities/attributes used by the IoTAgent. In order to trigger notificaitons you can enumera the list of attributes used by the IoTAgent.
Comment: How do I subscribe events from Orion to CEP?
Comment: I think is better to ask that in a separate question, in order not "mixing" answers. Don't forget to tell to which CEP implementation you refer in that new question, please. Thanks!
Comment: Subscription to all entities is already supported: with id `".*"`, type `""` and isPattern `"true"`. What is pending (as in 0.24.0) is to subscribe to any attribute in the entities. You can monitor its status in github.com/telefonicaid/fiware-orion/issues/350 (and add +1 as comment if you support its implementation :)
Comment: @fgalan, last version supports subscription of the all attributes ?
Comment: Orion 0.25.0 has the same functionality than 0.24.0 regarding this
Comment: The feature will be finally included in Orion 0.27.0 (answer post has been edited in that way).


Rolling windows using for loops

Question: So I am coding up rolling windows in Julia.
There is one function I wish to replicate. The desired result I achieved was using R, zoo package, rollapply with the align="center" default.
So in order to re-create a centered rolling window I looked at the zoo source code for roll apply:
 ix <- switch(align,
      "left" = { 1:(n-k+1) },
      "center" = { floor((1+k)/2):ceiling(n-k/2) },
      "right" = { k:n })

In understanding how this translate to a for loop in Julia....
I have a for loop with a rolling window that may be set like this:
n = 20
[i-n+1:i]

or I can fix the starting point
n=20
[1:i+n]

I thought this was all there was to rolling windows.
How would one code up a centered window? I sifted through the R source code but its not really hitting home.
Answer: Like most other things in Julia, the functionality is in packages. You could check out https://github.com/JeffreySarnoff/RollingFunctions.jl .
A more general multidimensional implementation is in https://github.com/JuliaImages/ImageFiltering.jl

Rolling windows using for loops


What are the norms for naming new hymn tunes?

Question: Anybody who knows their way around a hymnal knows that hymn tunes have names, and hymnal editors sometimes mix and match hymn texts with compatible tunes. Some of the most familiar hymn tunes have odd-sounding names like Nettleton, Darwall, Aberystwyth, Old Hundredth, Dix, Kingsfold, Truro, Solon, Nicaea, Slane, Coronation, Rockingham Old, Bellevue, Diademata, and Erie, not to mention several German phrases.
I have composed a hymn tune which I plan to submit for consideration in a new hymnal. As the composer, I get to name the tune. For recently composed hymns I've seen, the tune name often matches the hymn title. But in this case I'm submitting only the tune, and the editors will pair it with some other text. The song for which I originally composed the tune is a love song, and the title might be unfitting for a hymnal. It would work fine if I used a shortened form of the title. I was just wondering if there are any other considerations I should think about. How do people name new hymn tunes?
Answer: There are no strict rules for naming hymn tunes - as the composer, you're free to name it however you like. From a historical perspective, though, most tune names come from a few different sources:

People. Often, tunes names will be given based on the name of the tune composer, or the author of the text it was written for. (This is almost always done well after-the-fact by hymnal editors, rather than composers naming the tune after themselves.) From your examples, tune names in this category are: Nettleton, Darwall, Dix, and Rockingham.
Places. Frequently, this will be the name of the town where the tune was written but it could also be another place of significance to the composer or a place somehow related to the subject matter of the text. From your examples, tune names in this category are: Aberystwyth, Kingsfold, Truro, Nicaea, Slane, and Erie.
Texts. For tunes written with a particular text in mind, the tune name is often a key word, theme, or phrase from that text. From your examples, tune names in this category are: Coronation, Diademata, and likely the "several German phrases" as well.
Other. Occasionally, hymnal editors will also name tunes according to some other historical event or tidbit relating to the tune. From your examples, "Old Hundredth" is an instance of this - so named because it was originally published as the tune for Psalm 100 in the "old" Genevan psalter.

With all of that in mind, I'd encourage you to think about the origin of and inspiration for your tune as you name it. What prompted you to adapt your love song into a hymn tune? Why did you write the original song in the first place? Was there another person who was instrumental in the creation, revising, or publication of this tune? Even though you didn't write it for a specific text, what kind of hymns would it work well for? Did you have a particular image or idea in your head as you were writing it?
Hopefully one of these questions could spark an idea for a name. Otherwise, you can always submit it without a name and let the hymnal editor(s) supply one.
Answer: Hymnologist Carl Daw (Hymn Society) in an email exchange noted that it is entirely up to the composer to name the tune; in very rare cases, it may be overridden by a hymnal editor due to duplication or some such. You mentioned a couple specifically, so here is some detail:
NETTLETON was named for an evangelist favored by the composer
DARWALL is named for the composer of a tune for the metrical version of Ps. 148
ABERYSTWYTH, a Welsh tune, is the name of a river on the coast of Wales
OLD 100th - like all the 'OLD' names is from Sternhold & Hopkins "Whole Booke of Psalms" (16th C) as the Reformation brought singing into congregational use; this was the tune for the 100th Psalm. A second generation of metrical Psalms acquired arbitrarily-assigned place names, WINCHESTER OLD for example. (In the 19th C. we got WINCHESTER NEW.)
The German tunes are taken from the incipit of the original hymn text, such as LASST UNS ERFREUEN. (When England was in conflict with Germany, that was renamed VIGILES ET SANCTI in English hymnals of the time, as were such as ELLACOMBE, ST THEODULF, etc. - some of which have reverted).


Jquery Validate - Marcar pelo menos 1 checkbox true

Question: Eu uso bootstrap toogle desse exemplo: http://www.bootstraptoggle.com/
Tenho 4 checkbox, uma delas devem ficar com true.
Como fazer isso com jquery validate ?
Segue código:

    <input id="checkbox1" class="checkbox[]" type="checkbox" data-onstyle = "success" data-offstyle = "danger" data-on = "Sim" data-off = "Não" data-size = "mini">

    <input id="checkbox2" class="checkbox[]" type="checkbox" data-onstyle = "success" data-offstyle = "danger" data-on = "Sim" data-off = "Não" data-size = "mini">

    <input id="checkbox3" class="checkbox[]" type="checkbox" data-onstyle = "success" data-offstyle = "danger" data-on = "Sim" data-off = "Não" data-size = "mini">

    <input id="checkbox4" class="checkbox[]" type="checkbox" data-onstyle = "success" data-offstyle = "danger" data-on = "Sim" data-off = "Não" data-size = "mini">

Javasxcript:
$(document).ready(function () {

    $("#myform").validate({
        ignore: ":hidden",
        rules: {
            "checkbox[]": { required: true, minlength: 1 }
        },
                       messages: {
            "checkbox[]": "Uma das opções abaixo devem ser marcada *"
        },
        ....
        ....
        ....
    }
}

Não acontece nada. Não sei o que estou fazendo de errado.
Comment: Eu acho que é o nome da classe, tenta mudar, para não ficar com "[ ]"
Comment: Sim, tenta lá Matheus
Comment: @Miguel, não funcionou
Answer: Esta é uma solução sem o plugin validate. Checar pelo menos um, tive de mudar o nome da classe dos inputs porque me estava a dar um erro.

unrecognized expression: .checkbox[]:checked

Mudei para checkbox

$('input[type="submit"]').on('click', function(e) {
  e.preventDefault();
  if($('.checkbox:checked').length > 0) {
      $(this).parents('form').submit();
      return;
  }
  alert('check em pelo menos um');
  return false;
});

<form>

    <input id="checkbox1" class="checkbox" type="checkbox" data-onstyle = "success" data-offstyle = "danger" data-on = "Sim" data-off = "Não" data-size = "mini">

    <input id="checkbox2" class="checkbox" type="checkbox" data-onstyle = "success" data-offstyle = "danger" data-on = "Sim" data-off = "Não" data-size = "mini">

    <input id="checkbox3" class="checkbox" type="checkbox" data-onstyle = "success" data-offstyle = "danger" data-on = "Sim" data-off = "Não" data-size = "mini">

    <input id="checkbox4" class="checkbox" type="checkbox" data-onstyle = "success" data-offstyle = "danger" data-on = "Sim" data-off = "Não" data-size = "mini">

  <input type="submit">
</form>
Comment: @MatheusMiranda faz com que o formulário não seja submetido antes das verificações/validações
Comment: O que faz `e.preventDefault();` ?


How do I track a publicly downloaded file?

Question: I am creating a custom module to track the file download time and user id with a file link or path. I have tried multiple modules but the download the file time tracking option is not available.
How I can programmatically track the file download time?
This is the code I am using.
function mymodule_file_download($uri) {
$scheme = \Drupal::service('file_system')->uriScheme($uri);
  if (in_array($scheme, ['private', 'temporary', 'session'])) {
    $permission = "read $scheme files";
    $current_user = \Drupal::currentUser();
    $account = $current_user->getAccount();
    if ($account->hasPermission($permission)) {
      return [
        'Content-Type: text/plain',
      ];
    }

    if (\Drupal::currentUser()->isAnonymous()) {
      throw new NotFoundHttpException();
   }

  }
  elseif (in_array($scheme, ['public'])){
    $current_user = \Drupal::currentUser();
    $account = $current_user->getAccount();
   \Drupal::logger('downloads_tracker1')->notice($account);
  }

}

Comment: You need custom code because there is nothing out of the box that will track metrics like this. Those metrics would be tracked in their own table. To trigger the behavior, you would need to serve the files from a particular route.
Comment: first you need to create a module and a schema that will hold your data , then you need to make eather a custom route that will redirect to the file and insert the time / user data in to that that table.
Comment: I have already uploaded files in content type then why i need to create a custom route?
Comment: Since the question is about code, we need to see the code you wrote so far. If you haven't written any code, you are asking the question too early. If you had a specific doubt about how to use a class/method/function, the question could be acceptable, as long as the question isn't too broad or subjective.
Comment: @kiamlaluno I have updated my question with code.
Answer: hook_file_download doesn't run for public file downloads.

Control access to private file downloads and specify HTTP headers.

If you want to track public file downloads, you will need a different approach.
For example, track downloads with Google Analytics event tracking
Comment: Thanks for your reply. Is there any way to do using custom code without google analytics event tracking?
Comment: @Adi you would need to write your own javascript code to store the link click, otherwise some server logs may also show the request for the file. GA is just a bit easier and does that for you.


Center a bootstrap grid

Question: How can I center the bootstrap grid ?
Here is the code

What We Do

  We specialize with some of the most popular coffee in the market such as:

 Caffè Americano

 Cafè Latte

 Cappuccino

Espresso

 Flat White

 Long Black

Here is the image:
Bootstrap Grid Not in Center Image
Here is some css I use to make the image the same sizes
#what-we-do img {
    display: block;
    max-width: 100%;
    width: 500px; /* You can set the dimensions to whatever you want */
    height: 200px;
    object-fit: cover;
  }

I used the class="text-center" in the container but it doesn't work. If possible, is there some BS class I can use to make it centered? I am minimizing my css because I am practicing bootstrap. Thank you.
Comment: Which bootstrap version are you using?
Answer: Use  justify-content-center class on the row div, in case using bootstrap version 4

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

What We Do

    We specialize with some of the most popular coffee in the market such as:

 Caffè Americano

 Cafè Latte

 Cappuccino

Espresso

 Flat White

 Long Black

Comment: Thank you!! a clean way to center the rows. thanks. again
Comment: please upvote also if you found it helpful :)
Comment: Okay, I will upvote it.  :)

Center a bootstrap grid


Ecommerce credit card integration

Question: I am aware of some third-party online payment processor. However, I've seen some sites who doesn't state which payment processor they use (eg. PayPal), the only field I see are registration details and credit card information fields. What are these type of payment processors?
Example, in Linode I wonder what they use as a credit card processor.
Answer: They are called Payment Gateways.  They generally come with an api.  You connect, send the CC details, payment is processed, response is sent back.
A popular gateway in New Zealand is DPS.
http://www.paymentexpress.com/
They are incredibly easy to use and have different options depending on the size of your operation.
Comment: Thanks for this. So does this says it is country/region specific?
Comment: I'm not sure on that, if you are required to have a merchant account with a bank then I imagine you would need your Payment Gateway to have accounts in that country too.

Ecommerce credit card integration


JQuery Accordion Issue

Question: I've been using http://jqueryui.com/themeroller/ for my site and it works fine but for one thing. I want to have a two different layout/design for the accordion UI. How can I accomplish this?
Any suggestion would be very much appreciated.
Thanks
Answer: You probably shouldn't, since the point of a unified set of widgets is to promote consistency. However, I realize that's not your question and you might have reasons.
The "easiest" way to do it is to add a special ID or class to your "alternate" accordion. Then in your CSS you are going to have to have more specificity in order to override the existing one. I would personally avoid adding it directly to your themeroller CSS; add it somewhere else like your site CSS so that Themeroller styles are easily maintained.
So, where jQuery UI automatically applies something like:
<code>.ui-accordion-header { /* original themeroller styles */ }
</code>
you would need to be more specific to give your own rules greater priority:
<code>.customClass .ui-accordion-header { /* override the parts you need to */ }
</code>
I can tell you this: it's going to be a pain. jQuery UI adds a tonne of classes, each with some relatively modular purpose. Overriding all of those to enable another look and feel on a different accordion is going to be some work.
Comment: Thanks for the quick response. I have already thought of this but is expecting some workaround. I guess I have to stick on the hardest way. I really appreciate your help. Thanks mate.

JQuery Accordion Issue


Adding translation to a custom module

Question: I cannot make the module translation strings to be considered, unistalling and installing the module again.
Is the indicated .po relative path correct?
in my module blockForm function i have :
  $form['retrieval_method'] = array(
    '#type' => 'fieldset',
    '#title' => $this->t('Retrieval Method'),
  );

my .info.yml
name: 'amu hal'
type: module
description: display publications from HAL
core: 8.x
version: 8.x-3.0
package: AMU
project: 'amu_hal'
interface translation project: amu_hal
interface translation server pattern: modules/amu_hal/translations/%language.po

and in

/sites/mysite/modules/amu_hal/translations/fr.po :

msgid "Retrieval Method"

msgstr "Méthode d'extraction"

i have activated the core interface traduction module and the

/fr/admin/reports/translations

tells me Missing translations for 11 projects:

amu hal (8.x-3.0). File not found at modules/amu_hal/translations/fr.po

Comment: wrap the keys in single quotes
Comment: The keys are on the left, so `'interface translation project': amu_hal`, for example
Comment: Does it help to read the documentation - https://api.drupal.org/api/drupal/core%21modules%21locale%21locale.api.php/group/interface_translation_properties/8.5.x
Comment: which keys ? this: interface translation project: 'amu_hal'. Does not change
Comment: which ones then ? because if i wrap them all, the module is not listed in the extend interface
Answer: Thanks to comments and doc , i have moved the whole module in modules/custom/ and for info file:
name: 'amu hal'
type: module
description: display publications from HAL
core: 8.x
version: 8.x-3.0
package: AMU
project: amu_hal
'interface translation project': amu_hal
'interface translation server pattern': modules/custom/amu_hal/translations/amu_hal-%language.po

Placing the po file at

modules/custom/mymodule/translations/mymodule-fr.po

now i could update the translation at

/fr/admin/reports/translations

and make string translations
Note that the same po file is not found if the module is placed in sites/mysite/module
Comment: `public://` means file upload directory, usually `.../sites/default/files/...`, I've successfully used a relative path from web root in my own module: `modules/custom/MY_MODULE/translations/MY_MODULE-%version-%language.po`
Comment: The `'` seems to be very important for the key on the right side: `'interface translation server pattern':` (correct) vs `interface translation server pattern:` (not correct)
Comment: Following works: interface translation server pattern: modules/custom/module/translations/module.%language.po, just remember to clear cache after changing info file

Adding translation to a custom module


How to modify the view's CALayer

Question: I see the code in MTAnimatedLabel
 CAGradientLayer *gradientLayer  = (CAGradientLayer *)self.layer;
gradientLayer.backgroundColor   = [super.textColor CGColor];
gradientLayer.startPoint        = CGPointMake(-self.gradientWidth, 0.);
gradientLayer.endPoint          = CGPointMake(0., 0.);
gradientLayer.colors            = [NSArray arrayWithObjects:(id)[self.textColor CGColor],(id)[self.tint CGColor], (id)[self.textColor CGColor], nil];

self is an UILabel. From the document, the layer should be readonly but I don't know why in this repo, it works.
So I try these code in my program.
 UIView *gradientView = [[UIView alloc] initWithFrame:textLayer.frame];
[self.view addSubview:gradientView];
CAGradientLayer *gradient = (CAGradientLayer*)gradientView.layer;
gradient.startPoint = CGPointMake(-0.4, 0.0);
gradient.endPoint = CGPointMake(0.0, 0.0);
gradient.colors = @[(id)[UIColor darkGrayColor].CGColor, (id)[UIColor whiteColor].CGColor, (id)[UIColor darkGrayColor].CGColor];
gradient.backgroundColor = [UIColor clearColor].CGColor;
gradient.frame = textLayer.frame

It throw an error:
-[CALayer setColors:]: unrecognized selector sent to instance 0x8f8dca0
I can't understand why my code is no able to run. Hope anyone can help me.
Answer: looks you missed add
+ (Class)layerClass
{
    return [CAGradientLayer class];
}

to make view layer gradient, by default this method return CALayer, that not have colors property see UIView class reference

How to modify the view's CALayer


Automatic GCP user id change

Question: I have a very strange issue with Google cloud platform. I have a GCP account managed by my organisation and through this account, I have access to 3 development projects. However, I do not get directed to SSO login while trying to login to this account. A few weeks ago, when I tried to login to this GCP account, I was directed to SSO login but when I logged in, I could not see the development projects that my organisation had added me to, even the default project had changed. However, when I look under the list of accounts (top-right), I could see an additional account - the original GCP account ID with gtempaccount.com added to the original account ID. This gtemp account has all the development projects intact but I do not get directed to an SSO login although I do get the message - THIS ACCOUNT IS MANAGED BY YOUR ORGANISATION on the gtemp account as well. How can these automatic changes to my account be explained?
Thanks
Answer: It is possible that, during the few weeks transition period that you mentioned, your organization has switched to a Google Service which caused the creation of this conflicting account. More details on this thread.
Within the same thread, you may find hints to your situation and ways to resolve it. I would also suggest reaching out to the Super Admin to see what changes could have happened in between this time.
Finally, if nothing works, then I suggest reaching out to the support team for your Cloud Identity provider to verify what is happening with your account and why you are not being redirected for the SSO sign-in should that still persists.

Automatic GCP user id change


How to stop NTFS volume auto-mounting on OS X?

Question: I'm a bit newbieish when it comes to the deeper parts of OSX configuration and am having to put up with a fairly irritating niggle which while I can put up with it, I know under Windows I could have sorted in minutes.
Basically, I have an external disk with two volumes:
One is an HFS+ volume which I use for TimeMachine backups.
The other, an NTFS volume that I use for general file copying etc on Mac and Windows boxes.
So what happens is that whenever I plug in the disk into my Mac USB, OSX goes off and mounts both volumes and shows an icon on the desktop for each. The thing is that to remove the disk you have to eject the volume and in this case do it for both volumes, which causes an annoying warning dialog to be shown every time.
What I'd prefer is some way to prevent the NTFS volume from auto-mounting altogether. I've done some hefty googling and here's a list of things I've tried so far:

I've tried going through options in Disk Utility
I've tried setting AutoMount to No in /etc/hostconfig but that is a bit too global for my liking.
I've also tried the suggested approach to putting settings in fstab but it appears the OSX (10.5) is ignoring these settings.

Any other suggestions would be welcomed. Just a little dissapointed that I can't just tick a box somewhere (or untick).
EDIT: Thanks heaps to hop for the answer it worked a treat. For the record it turns out that it wasn't OSX not picking up the settings I actually had "msdos" instead of "ntfs" in the fs type column.
Answer: The following entry in /etc/fstab will do what you want, even on 10.5 (Leopard):
LABEL=VolumeName  none    ntfs    noauto

If the file is not already there, just create it. Do not use /etc/fstab.hd! No reloading of diskarbitrationd needed.
If this still doesn't work for you, maybe you can find a hint in the syslog.
Comment: Sorry, I found it now. But I'm on OS X 10.7.x so it says it does nothing..
Comment: Where can I find this file..?
Comment: @JamesLitewski: which file? the one i explained you have to create if it doesn't exist?
Comment: I have osx 10.7.5 and there isn't fstab here. There is a /etc/fstab.hd, but it is empty.
Answer: This is not directly an answer, but

The thing is that to remove the disk you have to eject the volume and in this case do it for both volumes

I have a similar situation.
OSX remembers where you put your icons on the desktop - I've moved the icons for both of my removable drives to just above where the trash can lives.
Eject procedure becomes

Hit top-left of screen with mouse to show desktop
Drag small box around both removable drives
Drag 2cm onto trash so they both get ejected
Remove firewire cable
Comment: It works only for an external hd. For internal partitions it says they can't be ejected.


showing taxonomy (tags) in alphabetical order on nodes

Question: I just noticed that my tags are appearing at the bottom of my posts in the order I entered them, not in alphabetical order. I'm sure this is something simple, but I can't figure out how to get them to display on my nodes in alphabetical order.
Answer: The first thing that comes to mind, you can try to reorder taxonomy tags in vocabulary in alphabetical order.
Perhaps there is a better solution...
Comment: Thanks. I went into my taxonomies and clicked on the resort to alphabetical (which they already were). Nothing. the tags still appear as they were entered on the nodes and in the teaser.
Answer: Well, this will work but it does seem rather complex for what we are trying to achieve:
<code>function MYMODULE_node_view($node, $view_mode, $langcode) {

  switch ($node->type) {

    case 'article': // Replace with your content type.

        $tags = array();
        // Loop over values.
        foreach($node->content['field_tags'] as $k => $v) { // Replace your field name.
            // We only want the ones with numeric keys (that actually contain tags)
            if(is_numeric($k)) {
                // Add this to the $tag array using the name as a key.
                $tags[$v['#title']] = $v;
                // Unset from the content array.
                unset($node->content['field_tags'][$k]);
            }
        }
        // Now sort by the array keys.
        sort($tags, SORT_STRING);
        // And add back into the content array.
        $node->content['field_tags'] = array_merge($node->content['field_tags'], $tags);

        // Phew!

        break;
  }

}
</code>
Comment: thanks. where would I put this code?


Terminal Git vs Terminal Node vs Terminal Windows

Question: Estou com alguma dificuldade em perceber a necessidade de ter tantos terminais instalados no computador quando preciso usar o git ou node.js. Quais são as diferenças entre os terminais, o que um pode fazer e o outro não?
Por exemplo:
eu quis verificar se tinha o Node.js instalado no meu Windows 10, para isso fiz which node no terminal Windows e sem sucesso, eu percebo que esse comando não está implementado nesse terminal e tenho de usar outro (o Git deu-me o caminho da instalação), mas como saber qual deles usar para cada tarefa se no artigo/tutorial não está especificado?
Comment: Se você tiver feito a instalação como global qualquer um dos terminais vai fazer o que você quiser. O problema é que o terminal do windows não reconhece o comando "which", mas pra todas as operações essenciais funciona perfeitamente.
Answer: De forma bem simples, os "terminais" (como são chamados) ou CLIs (Command Line Interface) são software que te permitem executar comandos, tais comandos podem ser outros software compilado ou simples scripts escritos especificamente para o CLI "x" e interpretado também por ele.
Por que tantos?
Não há uma real necessidade de ter todos, a principal diferença de cada um é como ele é configurado e escrito, o que acaba implicando nos comandos que ele conseguirá rodar.
O terminal do Node, por exemplo, já vem com o comando node disponível, diferente do GitBash, que vem com os comandos de git disponíveis, enquanto o terminal padrão do Windows não tem nenhum deles.
De onde vêm esses comandos?
Cada terminal irá procurar por comandos compatíveis nos lugares onde ele está configurado para procurar. O CMD do Windows, por exemplo, irá consumir a variável de ambiente PATH, indexando todos os comandos compatíveis ao abrir o terminal e toda vez que você der um comando, o CMD irá tentar utilizar algum desses comandos e caso ele tenha achado, irá executá-lo.
Esses "comandos" podem ser arquivos .exe e, no CMD .bat. O Terminal no Mac consegue rodar arquivos .bash, mas não os .bat e por aí vai.
Qual o melhor?
Vai do gosto e da necessidade, eu uso bastante (em ambiente Windows) o emulador cmder, o CLI GitBash e o CLI CMD.
Você ainda pode adicionar o programa que quiser (desde que seja compatível) em qualquer CLI, para adicionar o node no CMD, por exemplo, você só precisa incluir o caminho do arquivo node.exe na PATH do Windows. E isto significa que você pode escolher e utilizar a CLI que quiser.


Error when building the ANTLR4 C++ Demo (macOS Sierra)

Question: When trying to compile and run the antlr4-cpp-demo with Xcode on macOS Sierra I get the following error:
<code>TLexer lexer(&input);    (!) Variable type 'antlrcpptest::TLexer' is an abstract class
</code>
As this is a demo I suppose it should work out of the box...
Any idea what is going wrong?
Answer: Check what exactly is causing the compiler to believe that TLexer is abstract. Probably it doesn't override a function that is abstract in one of its predecessors, which in turn indicates your are using a code generation jar and a C++ runtime that don't match. Did you download both from the ANTLR website?
Comment: Hi Mike,

Thank you very much for your answer!

You where right:  I thought I had installed everything from the ANTLR side - but didn't realize that there was still an old homebrew install as well.  So the versions of antlr4 and grun I used where actually those from the homebrew install (version 4.6) while all the rest was from the newest version (4.7)...

Deinstalling my homebrew version solved the problem and now the demo runs as supposed :)

Thank you again,

Dietrich


Como passar um atributo da classe filha através do construtor para a classe mãe

Question: Tenho 3 classes
Classe mãe: Animal
Classes filhas: Cachorro e Gato
Quero gravar o atributo nome somente quando um dos objetos forem instanciados Gato ou Cachorro.
Na classe mãe eu tenho o atributo Nome que pode ser somente leitura (get)
Como passar o valor (atributo nome) das classe filhas para a classe mãe através dos construtores das classes filhas?
Comment: Se as classes `Cachorro` e `Gato` são herdadas de `Animal` e `Animal` tem a propriedade `Nome` é só fazer `Nome = "nome";`. Para mais detalhes é necessário que você coloque seu código!
Comment: Você terá acesso a sua classe mãe através da palavra reservada `base`. https://msdn.microsoft.com/pt-br/library/hfw7t1ce%28v=vs.120%29.aspx?f=255&MSPPError=-2147217396
Comment: Alguma das respostas resolveu sua dúvida? Acha que pode aceitar uma delas? Veja o [tour] como fazer isso, se ainda não o fez. Você ajudaria a comunidade identificando qual foi a melhor solução para você. Pode aceitar apenas uma delas. Mas pode votar em qualquer pergunta ou resposta que achar útil no site todo.
Answer: Tem várias premissas erradas na pergunta. A primeira é o uso errado do termo atributo. Eu sei, todo mundo ensina errado por causa da praga que é UML que usa este termo. As linguagens não usam, não faz sentido o seu uso.
A outra é que está achando que um campo que está na classe mãe não está na filha ou que o campo da filha precisa ser passado para a classe mãe como se a mãe fosse outra coisa isolada.
Também não está claro para você o que é uma classe e o que é um objeto. De fato parece que as classes são isoladas porque isso é visível no código, mas elas são apenas modelos. Quando tem o objeto é uma coisa só, os modelos não estão presentes de forma isolada, por isso não tem que passar nada de uma para outra, está tudo presente no objeto e basta usar normalmente.
Talvez falte entender melhor Para que serve um construtor?.
Tem um exemplo usando construtores encadeados. Fora isto a pergunta precisaria ser mais específica.
using static System.Console;

public static class Program {
    public static void Main(string[] args) {
        var gato = new Gato("Dener");
        WriteLine(gato.Nome);
    }
}

public abstract class Animal {
    public string Nome { get; private set; }
    public Animal(string nome) => Nome = nome;
}

public class Gato : Animal {
    public Gato(string nome) : base(nome) {}
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Answer: Pelo que eu entendi de sua pergunta, você deseja ter uma propriedade Nome em sua classe Animal com o setter privado e deseja atribuir seu valor através do construtor da classe filha. Você pode utilizar a palavra chave base para chamar o construtor da classe "mãe".
public abstract class Animal

{
    public string Nome { get; private set; }

    public Animal(string nome)
    {
        Nome = nome;
    }
}

public class Gato : Animal
{
    public Gato(string nome) : base(nome)
    {

    }
}

Exemplo:
class Program
{
    static void Main(string[] args)
    {

        var gato = new Gato("Miau");

        Console.WriteLine(gato.Nome);
        Console.Read();
    }

}

Referência


Integration being the opposite of differentiation?

Question: I know that if we start with an original function and take one derivative, we get another function. If we take the integral of that new function we get the original function back. So I see how they are opposite operations but I don't see how they are opposite in the sense that the integral is supposed to be the area under the curve and the derivative is supposed to be the instantaneous slope. It seems like they are separate; deriving one function is the opposite of integrating it but when we look at it graphically it doesn't make sense. Also, if I start with some function, differentiate it and then take the integral I get the original function so how is that the area under the curve? Thanks.
Comment: @KingSquirrel This isn't true. You get a constant of integration when you integrate. For example
$$\int \frac{\mathrm{d}x}{x^2} = -\frac{1}{x}+k \equiv \frac{kx-1}{x}$$
Comment: The two operations are indeed different and not obviously "inverse". That's why the fundamental theorem of calculus is so profound!
Comment: but what about when you start with one function, differentiate it and then integrate it. you end up with the original. So in that sense they are inverse?
Answer: Well...it's not obvious, as you point out, why "finding a slope" and "finding area under a curve" are opposites. That non-obviousness is why it's called a "theorem" (indeed, more formally stated, it's called "the fundamental theorem of calculus").
But maybe I can help out with the intuition a little. Instead of thinking of $f'(b)$ as the slope of the graph of $f$ at the point $(b, f(b))$, think of it this way: if we moved a little to the right of $b$, say, to $b + h$, where $h$ is a small number, what would we expect $f(b+h)$ to be? Well, if you draw a picture, you'll see that we expect it to be
$$
f(b+h) \approx f(b) + h * slope
$$
and since the slope is $f'(b)$, this is
$$
f(b + h) \approx f(b) + h  f'(b).
$$
That's true for any "nice" (smooth, etc.) function, for small values of $h$. Let me define such a function, the "accumulated area" function:
$$
F(x) = \int_0^x f(t) ~dt.
$$
That's the area under the graph of $f$ between $0$ and $x$. In particular, we have
$$
F(b) = \int_0^b f(t) ~dt
$$
is the area under the graph of $f$ from $0$ to $b$. What's the value of $F(b + h)$ for a small value of $h$?
We have two possible answers: the first is from the definition: it's just
$$
F(b+h) = \int_0^{b+h} f(t) ~dt = \int_0^{b} f(t) ~dt + \int_b^{b+h} f(t) ~dt.
$$
Hold that thought.
The second answer comes from that general stuff I wrote above, namely:
$$
F(b+h) \approx F(b) +  h F'(b).
$$
Setting these two equal (since they both represent the value of $F(b+h)$, more or less), we get
$$
F(b) +  h F'(b) \approx \int_0^{b} f(t) ~dt + \int_b^{b+h} f(t) ~dt
$$
Since the $F(b)$ on the left hand side is the same as the first integral on the right hand side, this simplifies to
$$
 h F'(b) \approx  \int_b^{b+h} f(t) ~dt
$$
and dividing through by $h$, becomes
$$
  F'(b) \approx  \frac{1}{h} \int_b^{b+h} f(t) ~dt
$$
Now when $h$ is very small, the integrand, $f(t)$ is roughly constant ... and its value is approximately $f(b)$, So the integral on the right is roughly the integral of the constant $f(b)$ over an interval of width $h$; that value is just $h f(b)$. So we get
$$
  F'(b) \approx  \frac{1}{h} \int_b^{b+h} f(t) ~dt \approx
 \frac{1}{h} [h f(b) ] = f(b).
$$
So the derivative of the "accumulated area" function $F$ is the original function $f$.
As for derivative and integral being "opposites", you might want to look at
$$
f(x) = x^2 + 1.
$$
Try taking its derivative, to get a new function $g$, and then write down the accumulated area function
$$
G(x) = \int_0^x g(t) dt.
$$
Evaluate the integral, and see whether it equals $f$. (Hint: it doesn't!). So "differentiate then integrate" doesn't necessarily bring you back to the original function. On the other hand, for nice enough functions (e.g., continuous), "integrate then differentiate" does bring you back to the original.
Answer: The derivative is the instantaneous rate of change.  The best way to think about the derivative is:
\begin{equation}
f(x + \Delta x) \approx f(x) + f'(x) \Delta x.
\end{equation}
The (second) fundamental theorem of Calculus says, intuitively, that "the total change is the sum of all the little changes".
Suppose we want to know how much a function $f$ changes across an interval $[a,b]$.  Chop up $[a,b]$ into tiny subintervals $[x_i,x_{i+1}]$ of width $\Delta x_i$.  Then
\begin{align}
\underbrace{f(b) - f(a)}_{\text{total change}} &= \sum_i \underbrace{f(x_{i+1}) - f(x_i)}_{\text{little change}} \\
&\approx \sum_i f'(x_i) \Delta x_i \\
&\approx \int_a^b f'(x) \, dx.
\end{align}
It seems plausible that, by chopping up $[a,b]$ into extremely tiny subintervals, we can make this approximation as close as we like.  It follows that the two quantities must be equal:
\begin{equation*}
f(b) - f(a) = \int_a^b f'(x) \, dx.
\end{equation*}
The geometric interpretations of the derivative and the integral, are not always the best way to think about them.
Comment: This is the best answer I've seen so far. The integral from a to b is the two derivatives in reverse order, b - a. That's why they're opposite.
Comment: Why we need to chop into $[a,b]$ into tiny subintervals if always the $\Delta x_i$ is present both on numerator and denominator so always cancels out?
Comment: @user599310 There's no $\Delta x_i$ in $f'(x_i).$ Sometimes the definition of the derivative is written with a $\Delta x$ in the denominator, but by the time you get to $f'(x_i)$ that denominator has already been taken to zero in a limit; it is not the $\Delta x_i$ described in this answer.
Answer:
Suppose that $A(x)$ represents the area under the curve $f$ between $a$ and $x$.
Now try to find A'(x) with limits.
$$A'(x)=\lim_{h\to 0} \frac{A(x+h)-A(x)}{h}$$
Now try graphing $A(x)$ and $A(x+h)-A(x)$ as shaded regions under the graph of $f$, where $A(x+h)$ is the union of the $A(x)$ and $A(x+h)-A(x)$ regions.

I think that you will find that
$$A(x+h)-A(x)\approx hf(x+h)\approx hf(x)$$
where $hf(x+h)$ is the area of an approximating rectangle. The limit then becomes
$$A'(x)=\lim_{h\to 0} \frac{hf(x+h)}{h}=f(x)$$
Comment: Was that made in Paint?
Comment: aww, did I forget the MSPaint NOW! logo?
Comment: Oh no! I preferred it before! (MS pawn? Not I!) But +1 anyway.
Comment: there! logo added
Comment: Re: resisting MS. If at first you don't succeed, give up. Ain't no use in being a damn fool.


Non-archimedean exponential valuation and integral closure

Question: I am trying to solve the following problem from Neukirch's book on ANT:
Let  $L|K$ be a finite field extension, $v$ a nonarchimedean exponential valuation, and $w$ an extension to $L.$ If $\mathcal{O}_L$ is the integral closure of the valuation ring $\mathcal{O}_K$ of $v$ in $L$, then the localization $\mathcal{O}_{L,p}$ of $\mathcal{O}_L$ at the prime ideal $$p = \{ \alpha \in \mathcal{O}_L |  w(\alpha) >0 \}$$ is the valuation ring of $w.$
So, my attempts so far is to take an $x = \alpha / \beta \in L$ where $\alpha,\beta \in \mathcal{O}_L.$ If we could show that we can choose $\beta$ such that $w(\beta) =0,$ I believe we would be done but I don't see why this should be true. Does anyone have an argument or some hint?
Answer: It is easy to see that $\mathcal{O}_{L,p}$ is a subset of the valuation ring $\mathcal{O}_w.$ Call the maximal ideal of $\mathcal{O}_{L,p}$ $p$ as in your post. So, for the other direction consider an element $\alpha \in L$ such that $w(\alpha) \geq 0$ and write $\alpha= x/y.$ $\alpha$ then satisfies an equation with coefficients in $K,$ $$a_n(x/y)^n + \cdots +a_1(x/y)+a_0 = 0.$$ Choose $a_s$ with the smallest value $w(a_s)$ farthest to the left in the equation above. Set $b_m = a_m/a_s$ so that by dividing by $a_s$ we get an equation
$$b_n(x/y)^n+\cdots b_1(x/y)+b_0=0.$$
We see that $b_n,\ldots,b_{s+1}$ all lie in $p$ while all $b_m$ lie in $\mathcal{O}_{L,p}.$ Dividing by $(y/x)^s$ we get an equation
$$(b_n(x/y)^{n-s} + \cdots +b_{s+1}(x/y)+1)+y/x (b_{s-1}+ \cdots b_0 (y/x)^{s-1})=0.$$ Setting $$a =b_n(x/y)^{n-s} + \cdots +b_{s+1}(x/y)+1$$ and $$b = b_{s-1}+ \cdots b_0 (y/x)^{s-1}$$ we can rewrite the above equation as $a+by/x=0.$ Rearranging, we see that $x/y = -b/a$ so it is enough to show that $a$ and $b$ are in $\mathcal{O}$ and $a$ is not in $p.$ For this, we'll use that the integral closure of $\mathcal{O}_v$ in $L$ is the intersection of all valuation rings in $L$ lying above $\mathcal{O}_v$. If $x/y$ has non-negative valuation in some valuation ring $R$ lying above $\mathcal{O}_v$ then clearly $a$ has so as well, since it is a polynomial in $x/y$ and $b$ will also have non-negative valuation. Conversely, if $x/y$ has negative valuation, then $b$ has non-negative valuation since it is a polynomial in $y/x$ and one sees that $a$ then also has non-negative valuation.
Lastly, one shows that $a$ is not in $p$ follows immedieately from $w$ being a non-archimedean valuation.


Excel: match value from an array and return cell value from the same row

Question: I have some data in excel worksheet1 in this form:
person1 person2 person3 score
dave    sarah   jill    4
brandon hank            3

And in worksheet2 I have a column of people listed alphabetically, like this:
person  score
alex
brandon
dave
hank
jill
sarah

I'd like to obtain each person's score from worksheet1 (with blanks for those who are absent):
person  score
alex
brandon 3
dave    4
hank    3
jill    4
sarah   4

I've looked into functions like find, match, lookup, vlookup, but it seems like I will need something more complicated.
Answer: Assuming:

Each person can only ever occur once in the source data
The source data occupies the range A1:D3 (with headers in row 1)
The first person's name for which you wish to return a result is in G2

then this formula in H2:
=IF(COUNTIF($A$2:$C$3,G2),INDEX($D$2:$D$3,SUMPRODUCT(($A$2:$C$3=G2)*(ROW($A$2:$C$3)-MIN(ROW($A$2:$C$3))+1))),"")
Copy down to give equivalent results for names in H3, H4, etc.
Regards
Comment: Given your constraints, and **also** assuming the score is numeric, I think the following would work also:  =IF(COUNTIF($A$2:$C$3,G2),SUMPRODUCT((G2=$A$2:$C$3)*$D$2:$D$3),"")
Comment: Yes. Good point. If that assumption holds then this is indeed a valid, and more succinct, solution. Nice.


Image of countable and uncountable sets

Question: There are two questions:

Image of a countable set of real numbers under any continuous function is countable?

My claim is yes. Let $X$ is countable $\implies X=\{x_1,x_2,\ldots,\}$. Now $f(X)=\{f(x_1),f(x_2),\ldots,\}$ which can be atmost countable. Now my question is "What is the role of continuity here?"

Image of a uncountable set of real numbers under any non-constant continuous function is uncountable?

I feel this is true. But unable to proceed. Please provide me a hint.
Comment: If the functions are from the real line to the real line then mean value theorem gives the complete answer. Just go through what is mean value theorem.
Comment: But the function can be from the set of irrational numbers also there it is not connected. If it is connected then it is not a problem. The only problem arises when it is disconnected.
Comment: Hmm... I don't the continuity is required for the first but I think it is for the second.  Obviously if the continuous condition of the second were removed it wouldn't be true.  (f(x) = 0 if x is rational, f(x) =1 if is irrational has a finite image).  See what is used in the definition of continuity that makes thinks this a clinch.  Maybe try for a a Cantor diagonal type argument.
Answer: There are non-constant continuous functions with an uncountable number of zeroes.
My first thought was to use the Cantor set $C$, and a search for prior art led to this existing example already on this site:
Non-constant continuous function having uncountably many zeros?
The function is:
$$f:[0,1]\to\mathbb{R}, f(x) = \inf_{c \in C}\{ |x - c|\}$$
It can be shown that $f(x) = 0 \quad\forall x \in C$ and that $f$ is continuous on $[0,1$].
Comment: @5xum: This negates the statement that _"image on any uncountable set is uncountable under a non-constant continuous map"_. The shows an $f$ and an uncountable set $C$ for which this statement is not true.
Comment: If $f(x)=0\forall x\in C$, then $f$ is a constant function on $C$, this it is not a counterexample for $2$.
Comment: @5xum: Umm. $f(x) \ne 0$ for $x \notin C$. So $f$ is not constant on $[0, 1]$ and $f(C) = \{0\}$.
Comment: OK, but then how is the function a counterexample? If you take $f$ defined on $\mathbb R$, then $f(\mathbb R)$ is uncountable - which makes it not a counterexample.
Answer: For 1., you do not need continuity.
For $2$, the function $f: (-1, 0)\cup (0,1)$ defined as $$\begin{cases}-1 & x<0\\
1 & x>0\end{cases}$$
is continuous on $(-1,0)\cup(0,1)$ and not constant.
Answer: To 1, you dont need suppose continuous.
To 2, as the function is not constant, use intermediate value Theorem and get an interval in the image.
Comment: As I have mentioned earlier also that intermediate value theorem is for the connected set. It is not true for a disconnected set. And an uncountable set can be disconnected also, for example, $\mathbb{Q}^c$.

Image of countable and uncountable sets


Enum for ISO3166 countries - acceptable practice?

Question: I'm developing an ASP.NET MVC 3 application and it uses a complex model which is serialized/deserialized to/from XML.
Some fields require ISO3166 country codes. I have several defined Enums for other restricted lists (which are very unlikely to change) which are marked with the XmlEnum attribute and displayed neatly using DisplyFor/EditorFor templates.
In order to be consistent I created an Enum of the ISO3166 country codes.
However I am aware these will change overtime requiring me to re-build/deploy the project.
Given the frequency/likelyhood of the ISO3166 codes changing, is this acceptable practice?
Comment: Won't having it in database give you more flexibility ? Your logic should be able to deliver it for the list of codes you can get,Enum you will have to get back to the code always for any change
Comment: @V4Vendetta - Why store them in a DB? Do they change that often?
Comment: @Oded You are right but i have no idea whether its risky or not, how one change can effect the app coz having it as Enum would enforce code having specific conditions based on value rather than a generic one
Answer: Enumerations are conceptually a related collection of constants, ie. they do not change—a client assembly can make this assumption and directly compile in the value of the enum field.
But ISO 3166 does change, often several times a year. For example the creation of the new country South Sudan will need to be reflected in an update.
Comment: Thanks for the answer; the South Sudan example illustrates why an Enum is not a good option perfectly.
Answer: Isn't this just configuration data? I would XML serialize a List<MyCountryCodeClass> of the  country codes and place this in a CountryCodes.xml file in the App_Data folder.
Comment: I agree with making it a configuration file. I'm not sure if I'd use xml-serialization, but that's only a minor implementation detail.
Comment: Thanks for the suggestion. I had only considered using a DB to store the country codes so alternatives are useful.


Values not assigning to nested class field in dto class while sending data from javascript in formdata

Question: While sending data from javascript using formdata values are not mapping properly
I have to send a file and a list of phonesNumbers
javascript file
let fdata = new FormData();
fdata.append("postalCode", $("#c-postalCode").val());
fdata.append("dob", $("#c-dob").val());
fdata.append("contactImage", $("#c-contactimg")[0].files[0]);

fdata.append("phoneNos", [{id:"1",phoneNo:"12345"}]);

fetch("/cm/save/contact/details", {
body: fdata,
method: "POST"
}).then((response) => { //Somecode})

RestController class
In method using ModelAttribute to map data coming from javascript
@PostMapping("/save/contact/details")
    public void saveContactDetails(@ModelAttribute ContactDetailsDto contactDetailsDto) {
        System.out.println(contactDetailsDto);
    }

ContactDetailsDto.java
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ContactDetailsDto {

    //Somecode

    private MultipartFile contactImage;

    @NotBlank
    private List<PhoneNumberDto> phoneNos = new ArrayList<>();

}

PhoneNumberDto.java
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PhoneNumberDto {

    private Integer id;
    private String phoneNo;

    public PhoneNumberDto(String phoneNo) {
        super();
        this.phoneNo = phoneNo;
    }

}

But when printing data id filed is null and phoneNo is showing object
ContactDetailsDto(id=null, name=asd, email=, contactImage=org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile@2dc05cd7, address1=, address2=, postalCode=null, country=101, state=4030, city=57709, dob=null, phoneNos=[PhoneNumberDto(id=null, phoneNo=[object Object])])

I have tried several things like creating different parametrized constructors, and sending different types/forms of data from javascript
How to exactly map data with fields with nested POJO class in it
Comment: Need to improve formatting.
Answer: Take a look at FormData#append documentation
This right here, describes the second argument:

The field's value. This can be a string or Blob (including subclasses
such as File). If none of these are specified the value is converted
to a string.

Which means that you're not setting the FormData correctly - it doesn't allow passing an array or complex objects as a value.
Someone has already described a solution to this problem in this answer.


Meaning of specific part of answer in delta-epsilon limit proof

Question: In a math question I had such as the limit approaches $3$ in $x^4-x^2+1$ (help with formatting please I'm new), the answer was that $\delta$ equals $\left(1, \frac{\epsilon}{168}\right)$.
In another question, I have a limit approaching $5$ in $\frac{x+4}{x-4}$ and the answer equals $\left(\frac{1}{2}, \frac{\epsilon}{16}\right)$.
I can get the $\varepsilon$ answers pretty well but what do the $1$ and $\frac{1}{2}$ mean and how do you go about getting them?
Comment: The answer is not a pair. Check again, you made a mistake transcribing.
Comment: See [here](http://math.stackexchange.com/questions/209440/how-to-show-that-fx-x2-is-continuous-at-x-1/209492#209492).
Comment: This question is very similar to http://math.stackexchange.com/questions/209440/how-to-show-that-fx-x2-is-continuous-at-x-1/209492#209492 (mentioned in a previous comment), http://math.stackexchange.com/questions/780191/why-do-we-impose-the-constraint-delta-le-1-when-proving-the-continuity-of-x, and probably several other questions.
Answer: Finding a suitable $\delta$ as a function of $\epsilon$ is by no means a straightforward process. Infinitely many suitable choices exist! It all depends on your strategy. One popular strategy that I like to use is to set $\delta = \min\{1, \epsilon/M\}$ for some suitable constant $M$. Note that the $1$ here is completely arbitrary; I could also have picked $2$, or $0.7$, or $1/2$, or $42$; I just prefer $1$ because it's a nice, small, round number. That seems to be the strategy used in your first example.
Given any $\epsilon > 0$, let $\delta = \min\{1, \epsilon/M\}$. [Note: The $M$ here is just a placeholder; we're going to go back and replace it with a concrete number once we figure out what it should be later.] Then observe that if $0 < |x - 3| < \delta$, then:
\begin{align*}
&|(x^4 - x^2 + 1) - 73| \\
&= |x^4 - x^2 - 72| \\
&= |x - 3||x^3 + 3x^2 + 8x + 24| \\
&< \frac{\epsilon}{M}|x^3 + 3x^2 + 8x + 24| &\text{since } |x - 3| < \delta \leq \frac{\epsilon}{M}\\
&= \frac{\epsilon}{M}|(x - 3)^3 + 12(x - 3)^2 + 53(x - 3) + 102| \\
&\leq \frac{\epsilon}{M}(|x - 3|^3 + 12|x - 3|^2 + 53|x - 3| + 102) &\text{by the triangle inequality} \\
&< \frac{\epsilon}{M}((1)^3 + 12(1)^2 + 53(1) + 102) &\text{since } |x - 3| < \delta \leq 1 \\
&= \frac{\epsilon}{M}(168) \\
&= \epsilon
\end{align*}
provided that $M = 168$. [Now we can go back in our proof and replace each $M$ with $168$.]
Answer: In the first one, if you compute $|f(x)-L|$ it is $|x-3)|\cdot q(x)$ where $q$ is a cubic, having (luckily) positive coefficients, and by restricting $x$ to be within $1$ of $3$ we can get to $q(x) \le 168$ because of $|x|\le 4.$ Thus we need to have both $|x-3|<1$ and $|x-3|<\varepsilon/168$, and the usual way to express two $x$ restrictions at once is by using the min function, so here you can say $\delta = \min(1,\varepsilon/168).$
Comment: Thank you for the explanation but I still don't understand what the 1 means in your min answer.
Comment: @Jonnathan If one ignores the requirement $|x-3|<1$ then there isn't an upper bound on the factor $q(x)$ in the notation above, which makes the whole process not work. So you need delta both less than 1 AND less than eps/168 to make it work.
Answer: The crux of your question seems to be, "how do you go about getting them"
(the constants $1$ and $\frac 12$).
The short answer is: the choice of constants $1$ or $\frac 12$ is a completely arbitrary choice in many cases; in other cases there are restrictions on what constant you can use, but the choice is still an arbitrary choice within those bounds. There is no formula to "derive" the $1$ or $\frac 12$ exactly, but that's OK, because you don't need a formula.
I've already explained the general idea in a previous answer,
Why do we impose the constraint $\delta\le 1$ when proving the continuity of $x^3$ using the definition of continuity?
That answer talked about a different function than $x^4 - x^2 + 1,$
but the main point is the same: the $1$ comes into play in
$\delta = \min\left\{1, \frac{\epsilon}{168}\right\}$
because your $\delta$-$\epsilon$ assertion must give the desired result
for all positive $\epsilon$,
and a simpler assertion such as $\delta < \frac{\epsilon}{168}$ unfortunately
would not be sufficient for large values of $\epsilon$
(specifically, in this example, any value of $\epsilon$ greater than $168$).
Your second problem is an example of "why $\delta < 1$ is not always helpful"
as explained in my previous answer.
The difficulty is that if $f(x) = \frac{x+4}{x-4},$
the function $f(x)$ is unbounded near $x = 4.$
If you are to find a limit of $f(x)$ at $x = 5,$
the condition $0 < \delta < 1$ tells you only that
$|x - 5| < 1,$ that is, $4 < x < 6,$
and there are values of $x$ in that range (namely, values close to $4$)
that will cause $| f(x) - f(5) |$ to be larger than whatever
value of $\epsilon$ you may be given.
But if you make a stricter condition, such as $0 < \delta < \frac 12,$
then you can avoid the bad behavior of $f(x)$ near $x = 4.$
Comment: Thank you for actually answering the question I had!


What are the arguments for/against interpreting the magnitude of the value of Blue-Red Hackenbush as an objective function?

Question: There appears to be a common assumption in Blue-Red Hackenbush that the Blue player should make whichever move will maximize the position value of the game, and the Red player should make whichever move will minimize the position value of the game, as though a greater position value corresponds to the relevant player winning by a "better" margin.
However, it stands to reason that assuming optimal play (recursive in this definition) for the remainder of the game, any of the Blue player's moves which leave the position value non-negative are equally optimal, and any of the Red player's moves which leave the position value non-positive are equally optimal, since they win deterministically, and conversely any losing move is equally optimal to any other.
How strong of a conclusion can we state regarding the strategic benefits of optimizing the position value of Blue-Red Hackenbush as opposed to hacking just any winnable edge?  Are there any arguments for hacking another edge actually being better in some positions?  How does this conclusion extend to the general assignment of surreal numbers to combinatorial games?
Answer:
"There appears to be a common assumption ..."

Citation needed! However, there is a reasonable sense in which it is often a good idea to focus on better-valued moves when thinking about a Hackenbush game.
Remember that the assignment of values to Hackenbush games comes from game addition: $G$ and $G'$ have the same value iff for every game $H$, the games $G+H$ and $G'+H$ have the same "basic type" (= win for blue, win for red, or win for second player).
With this in mind, we often think of a Hackenbush game $G$ as not existing in a vacuum but rather as part of a larger game $G+H$. Even if $G$ is a win for Blue (say), Blue moving in the $G$-part of the sum $G+H$ may be a losing move depending on what $H$ is; the set of good "$G$-part" moves for Blue in $G+H$ is however (even if empty) always closed under increased value for Blue.


Flink ES connection Not compiling as expected

Question: My problem is somewhat as described here.
Part of Code (actually took from apache site) is as below
val httpHosts = new java.util.ArrayList[HttpHost]
httpHosts.add(new HttpHost("127.0.0.1", 9200, "http"))
httpHosts.add(new HttpHost("10.2.3.1", 9200, "http"))

val esSinkBuilder = new ElasticsearchSink.Builder[String](
  httpHosts,
  new ElasticsearchSinkFunction[String] {
    def createIndexRequest(element: String): IndexRequest = {
      val json = new java.util.HashMap[String, String]
      json.put("data", element)

      return Requests.indexRequest()
              .index("my-index")
              .`type`("my-type")
              .source(json)

If I add these three statements, I am getting error as below
import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkFunction
import org.apache.flink.streaming.connectors.elasticsearch.RequestIndexer
import org.apache.flink.streaming.connectors.elasticsearch6.ElasticsearchSink

Error I am getting
object elasticsearch is not a member of package org.apache.flink.streaming.connectors
object elasticsearch6 is not a member of package org.apache.flink.streaming.connectors

If I do not add those import statements, I get error as below
Compiling 1 Scala source to E:\sar\scala\practice\readstbdata\target\scala-2.11\classes ...
[error] E:\sar\scala\practice\readstbdata\src\main\scala\example\readcsv.scala:35:25: not found: value ElasticsearchSink
[error] val esSinkBuilder = new ElasticsearchSink.Builder[String](
[error]                         ^
[error] E:\sar\scala\practice\readstbdata\src\main\scala\example\readcsv.scala:37:7: not found: type ElasticsearchSinkFunction
[error]   new ElasticsearchSinkFunction[String] {
[error]       ^
[error] two errors found
[error] (Compile / compileIncremental) Compilation failed
[error] Total time: 1 s, completed 10 Feb, 2020 2:15:04 PM

Stackflow question I referred above, some function has been extended. My understanding is, flink.streaming.connectors.elasticsearch have to be extended into REST libraries. 1) Is my understanding correct 2) if Yes, can I have complete extensions 3)If my understanding is wrong, please give me a solution.
Note: I added the following statements in build.sbt
libraryDependencies += "org.elasticsearch.client" % "elasticsearch-rest-high-level-client" % "7.5.2" ,
    libraryDependencies += "org.elasticsearch" % "elasticsearch" % "7.5.2",

Answer: The streaming connectors are not part of the flink binary distribution. You have to package them with your application.
For elasticsearch6 you need to add flink-connector-elasticsearch6_2.11, which you can do as
libraryDependencies += "org.apache.flink" %% "flink-connector-elasticsearch6" % "1.6.0"

Once this jar is part of your build, then the compiler will find the missing components. However, I don't know if this ES6 client will work with version 7.5.2.
Comment: I added the below statement to my build.sbt.
libraryDependencies += "org.apache.flink" % "flink-connector-elasticsearch6_2.11" % "1.9.0" % "provided"

I am getting error as below
object creation impossible, since method process in trait ElasticsearchSinkFunction of type (x$1: String, x$2: org.apache.flink.api.common.functions.RuntimeContext, x$3: org.apache.flink.streaming.connectors.elasticsearch.RequestIndexer)Unit is not defined
[error]   new ElasticsearchSinkFunction[String] {
[error]       ^
Comment: I don't know why the Scala example in the flink docs for ES6 doesn't define a `process` method, but the Java version does. Sounds like maybe this method is needed.
Answer: Flink Elasticsearch Connector 7
Please look at the working and detailed answer which I have provided here, Which is written in Scala.


Allow user to completely delete account (and data), not just cancel it

Question: I want users to provide option to cancel their own account. I know this is supported in D7, and I am using that only. But I want it in a manner that, when a user selects to cancel that account, all of his content and comments should be deleted. Right now, it is just blocking the user account, and keeping his all content.
If I grant user the permission "Select method for cancelling own account", then he may selects the option to retain his content upon cancellation, which I don't want.
So is there any way that when user cancels his account, cancellation method will delete the user account completely, without asking user to select from options.
-- Thanks for your time.
Answer: I found it myself. It is under: Configuration-> Account Settings-> When cancelling a user account section.


Existe alguma maneira de atribuir valores a um vetor mais rapidamente?

Question: Por exemplo, tenho a declaração do seguinte vetor:
float vet[3] = {1, 1, 1};

Teria como mudar todos valores do mesmo de uma só vez, sem ter que mudar um por um elemento ou criar um novo vetor e atribuir a ele:
vet[0] = -1;
vet[1] = 0;
vet[2] = 1;

Algo mais ou menos assim:
vet = {-1, 0, 1};

Answer: De forma direta não tem não. Poderia criar uma função onde passa os parâmetros e ela atribui cada elemento. Mas isso é o oposto de ser mais rápido, no máximo fica mais curto.
Isso de forma geral vai contra a filosofia básica do C, embora nada impede de ser usado se for o mais adequado pontualmente.
Comment: No meu caso isso é o mais adequado, pois tenho que trocar o valor do vetor dezenas ou centenas de vezes. Criei a função `void createVector(float *vet, float e1, float e2, float e3) {
  vet[0] = e1;
  vet[1] = e2;
  vet[2] = e3;
}`
Comment: Aí faz sentido, embora a sintaxe não deveria ser essa.
Comment: Deveria ser como? Sem o ponteiro? Se for isso eu tirei, estava fazendo uns testes aqui daí esqueci de mudar pra `float vet[3]` kk
Comment: Isso mesmo. tem outras formas de formas de fazer, mas se essa te atende, ela é adequada.


Inverse image of a subset of the codomain with elements without corresponding elements in domain

Question: I consider the function $f(x) = x^2 : \mathbb{R} \rightarrow \mathbb{R}$ whose image is $[0, + \infty)$. For the sake of simplicity: domain $D = \mathbb{R}$, codomain $C = \mathbb{R}$.
If I consider $A = [-25, 25]$ subset of the codomain $C$, this subset contains elements $[-25, 0)$ which don't have a corresponding element in the domain $D$. In this case is it possible to evaluate the inverse image of $A$? I tried to do it in this way.
According to the definition of the inverse image:
$$
f^{-1}(A) = \lbrace x \in D : f(x) \in A \rbrace
$$
$$
f^{-1}(A) = f^{-1}([0, 25]) = \lbrace x \in [-5, 5] \rbrace
$$
Is it correct?

EDIT: the Mathematica software gave me the same result I wrote.
Answer: $A=[-25,25]$ is not a subset of the $f$'s range $[0,\infty),$ so $A$ does not have a preimage under $f.$
$f$'s range (let's call it $R$) is a subset of $f$'s codomain, and $R$'s preimage is $f$'s domain.
Comment: "Range" and "image" are synonyms. [The wikipedia entry](https://en.wikipedia.org/wiki/Image_(mathematics)).
Comment: Hello @RyanG is the range the image of the function right?
Comment: thank you so much for your explanation


Using simplejson module to dump usernames as an array

Question: I am trying to implement bootstrap typeahead in django. In my template file, I want a textbox for users to enter text [usernames in my case]. The approach I am shooting for is to have django provide an array user_json to show.html, so bootstrap typeahead could use that array.
In my views.py file I have added the following function:
def users_list_json(request):
    users = User.get_username()

    user_json = simplejson.dumps(users)
    render_to_response("show.html", {"user_json": user_json})

But when I run console.log(user_json) in show.html it throws an error (ReferenceError: user_json is not defined). How should I go about implementing this? Is there an easier way?
I want an array with all the usernames to be available in show.html file so I could use that with typeahead.
Comment: Can you show us the relevant portion of the show.html template, as well as the relevant portion of the rendered page?
Comment: Could you add an error to your question? It will be very helpful to us.
Answer: I solved the problem by changing the function a bit.
def users_list_json(request):
    user_list = [u.username for u in User.objects.exclude(username=username)]
    context.user_json_list = simplejson.dumps(user_list)

And, I called the array in show.html by adding:
{{ user_json_list|safe }}


Android arrange expandable listview content

Question: I got this tutorial on youtube about expandablelistviews, and here is the source code that he gave, http://easyway2in.blogspot.in/2014/10/android-expandable-listview.html , problem is the contents are not arranged when the activity starts. How do i arrange the content of the listview, with the code on the link?
Comment: What do you mean by `the contents are not arranged` ?
Comment: Even when he adds the parent view in sequence on code. it gets jumbled up on start., Action Movies 1st, then Romantic Movies, then Horror Movies, then Comedy Movies. but when the activity starts, its not in there order when puted on code.
Comment: Do you mean `not in the order` you would expect?
Comment: @FrankN.Stein exactly.sorry for my bad grammar. xD
Comment: http://stackoverflow.com/questions/5815423/sorting-arraylist-in-alphabetical-order-case-insensitive
Answer: HashMap is unordered.

This class makes no guarantees as to the order of the map; in
  particular, it does not guarantee that the order will remain constant
  over time.

Use LinkedHashMap, if you want to preserve insertion order.
Comment: Nailed it! :) thanks alot. just changed all to linkedhashmap. it completely fixed everything.
Comment: I see, that explains it. xD
Comment: In the code, i'll just change the hashmap to linkedhashmap?


Sending intents from an Android-NDK application

Question: I am writing an native application in C++ under android, and I need to broadcast some intents. Is this possible?
If you are going to point me to JNI, please give me more details, as I am not sure how this is done :)

What I will do if this is not possible is having a named pipe between the NDK daemon and a Java-Android-Service. The NDK-daemon will write to the named pipe and then the Java-Android-Service will issue the intent.
Is there a better way?
Answer: There is a am command that you can run that will send Intents to Activities or Services.
const char *cmd = "am startservice -a %s"
                  " --ei ars_flag 2 --ei invitationType %d"
                  " --ei mode 1 --es ars_gadget_uuid \"%s\""
                  " --ei ars_conn_handle %d"
                  " --es ars_user_uuid \"%s\" --es ars_username \"%s\"";
sprintf (cmdbuffer, cmd, ...);
system (cmdbuffer);

Comment: adding `--user 0` might also help. E.g. `am startservice --user 0 -a ...`
Comment: @Tamas Thank you so much. I've been battling with security exception and this is the right fix!
Comment: Does `am` offer anything equivalent to `startActivityForResult()`, i.e. send an Intent to start an activity and then retrieve the result?
Answer: You cannot send Intents natively, this is a known limitation of the current NDK (perhaps it will be implemented in the future).
So what you have to do is to use JNI to make an upcall to Java whenever you want to broadcast an Intent (google JNI and upcall if you need to know how this is done), and have Java code that creates and sends the Intent. So if you're starting your application through a Java Activity and calling the native code through JNI, simply implement another method in Java that can receive your upcall. I don't know how much JNI you know, but the wikipedia information should get you started well enough.
Comment: I don't know if it was not possible at that time but it is totally doable at the moment. Future searches should not consider this answer as totally correct.
Comment: So it is 2020 and sending Intents natively is still not supported? Note: part about using JNI is misleading because Java Runtime is not present in native applications.
Comment: I know nothing of JNI, besides the theory. Since my application is pure C++, I understand that this is much harder. I assume a full example of creating the JVM and the intents is out of order here...?